repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/danieljaffe/quantum-algorithms-qiskit
danieljaffe
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 19:13:26 2023 @author: abdullahalshihry """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 19:15:12 2023 @author: abdullahalshihry """ import qiskit as qs import qiskit.visualization as qv import random import qiskit.circuit as qf def Deutsch_Jozsa(circuit): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qc.x(qr[4]) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.h(qr[4]) qc.barrier(range(5)) qc = qc.compose(circuit) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.barrier(range(5)) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024) output1 = job1.result().get_counts() print(output1) qc.draw('mpl') def Oracle(): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qq = qs.QuantumCircuit(5,name='Uf') v = random.randint(1, 2) if v == 1: qc.cx(0,4) qc.cx(1,4) qc.cx(2,4) qc.cx(3,4) print('Balanced (1)') elif v == 2: qq.i(qr[0]) qq.i(qr[1]) qq.i(qr[2]) qq.i(qr[3]) print('Constant (0)') qq =qq.to_gate() qc.append(qq,[0,1,2,3,4]) return qc Deutsch_Jozsa(Oracle())
https://github.com/danieljaffe/quantum-algorithms-qiskit
danieljaffe
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/danieljaffe/quantum-algorithms-qiskit
danieljaffe
#!pip install qiskit import numpy as np import matplotlib.pyplot as plt from math import floor, pi, sqrt from time import process_time from qiskit import * from qiskit.quantum_info.operators import Operator from qiskit.visualization import plot_histogram from qiskit.circuit import Gate def get_bitstring_permutations(index, lst, n, args): """ This function populates a list with all the combinations of bit strings of length n """ if (index == n): # append combination to list lst.append(list.copy(args)) else: # handle the case where the preceding bit is 0 args[index] = 0 get_bitstring_permutations(index + 1, lst, n, args) # handle the case where the preceding bit is 1 args[index] = 1 get_bitstring_permutations(index + 1, lst, n, args) def generate_uf(f, n): """ Parameters: f is an anonymous function and n is the number of bits in input: f:{0,1}^n -> {0,1}^n This function returns an oracle gate representing the function f for all x in {0,1}^n and y in {0,1}^n, the desired result is of the oracle is mapping the input x,y> to |x, y + f(x)> where + is addition modulo 2. The function first finds the list of bitstring permutations of n bits, it then establishes a mapping which is representative of the decimal number of the bitstring represents. For each |x,y>, it calculates |x, y + f(x)>. Finally it constructs a permutation gate which treats each permutation as a different basis vector in the 2^(n+1) dimensional complex Hilbert space that represents a system of 2*n qubits. Returns: the permutation gate """ # generate list of all bitstrings of size n bitstrings = [] get_bitstring_permutations(0, bitstrings, n + 1, [0] * (n + 1)) # initialize mapping and permutation list perm_dict = dict() perm_list = [] # populate mapping for permutation, bitstring in enumerate(bitstrings): values = [0] * (len(bitstrings)) values[permutation] = 1 perm_dict["".join(str(bit) for bit in bitstring)] = values # Send each |xy> to |x, f(x) + y> for bitstring in bitstrings: params = bitstring[:n] params.append((f(params) + bitstring[-1]) % 2) perm_list.append(perm_dict["".join(str(bit) for bit in params)]) return Operator(np.array(perm_list)) def apply_H(circuit, apply_to_list): """ Apply Hadamards to all specified qubits (if apply_to_list[index] == 1). Designed for a large amount of Hadamards being applied at once. """ for index, qubit in enumerate(apply_to_list): if qubit == 1: circuit.h(index) return circuit def initialize_dj(n): """ This function sets initial states and applies Hadamards to each qubit Note: apply_H isn't called because it is actually more efficient to initialize in one loop as opposed to 2. """ # apply H to first n qubits and X H to the last qubit (ancilla qubit) quantum_register = QuantumRegister(n + 1) classical_register = ClassicalRegister(n) quantum_circuit = QuantumCircuit(quantum_register, classical_register) # In qiskit, all quantum registers start in the low energy |0> state so we must apply an x gate to our helper bit # in order to put it in the state |1> quantum_circuit.x(quantum_register[-1]) for index in range(n + 1): quantum_circuit.h(quantum_register[index]) quantum_circuit.barrier() return quantum_circuit, quantum_register, classical_register def initialize_bv(states): """ This function sets initial states and applies Hadamards to each qubit Note: apply_H isn't called because it is actually more efficient to initialize in one loop as opposed to 2. """ n = len(states) circuit = QuantumCircuit(n, n-1) for index, state in enumerate(states): if state == 1: circuit.x(index) circuit.h(index) return circuit def deutsch_jozsa_algorithm(f, n, shots=1024, threshold=0.9): """ This function is intended to determine if f is constant or balanced for a given function f s.t. f:{0,1}^n -> {0,1}. The algorithm initializes the qubits with H for the first n qubits and X and H for the last qubit. The algorithm then constructs a Uf oracle gate based on the function input f. It then applies Uf to all the qubits and applies H to the first n qubits. Finally, the simulator is run on the circuit and measures the results. If upon measurement, the first n qubits are all 0, 1 is returned and the function is constant, otherwise 0 is returned and the function is balanced. This function has an anonymous function and integer n as parameters. This function uses 9q-squared-qvm, so it assumes that n <= 9. """ # apply H to first n qubits and X H to the last qubit (ancilla qubit) quantum_circuit, quantum_register, classical_register = initialize_dj(n) # Generate Uf oracle from f (anonymous function) uf_gate = generate_uf(f, n) # Applying the uf_gate must be done with the qubits in the reverse order due to the implementation of qiskit rv_qr = list() for index in range(n + 1): rv_qr.append(index) rv_qr.reverse() quantum_circuit.unitary(uf_gate, rv_qr) quantum_circuit.barrier() # Apply Hadamards to first n qubits for index in range(n): quantum_circuit.h(quantum_register[index]) # Run simulator quantum_simulator = Aer.get_backend('qasm_simulator') quantum_circuit.measure(quantum_register[0:n], classical_register) # quantum_circuit.draw('mpl') # plt.show() # Evaluate the job results # start = process_time() job = execute(quantum_circuit, quantum_simulator, shots=shots) # end = process_time() # total_time = end - start results = job.result() counts = results.get_counts(quantum_circuit) # NOTE: 1 = constant, 0 = balanced # To compensate for the error rates of actual quantum machines, the threshold for being consider balanced is # set to be threshold * shots, or a percentage of shots given at runtime. # Function is constant key = '0' * n if key in counts: if counts[key] >= threshold * shots: return 1 key = '1' * n if key in counts: if counts[key] >= threshold * shots: return 1 # Function is balanced return 0 def f_balanced(args): return args[0] def f_constant(args): return 1 input_size = 10 times = [] for i in range(1,input_size+1): start = process_time() res = deutsch_jozsa_algorithm(f_balanced, i, shots=1) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.3f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 15, step=1)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("DJ: Execution Time for Balanced Function vs. Input Size") times = [] for i in range(1,input_size+1): start = process_time() res = deutsch_jozsa_algorithm(f_constant, i, shots=1) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.3f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 14, step=1)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("DJ: Execution Time for Constant Function vs. Input Size") def bernstein_vazirani_algorithm(f, n): initialize_list = [0] * n # calculate b by f(0^n) = b b = f(initialize_list) # Initialize circuit by applying H to first n qubits and X H to last qubit (ancilla qubit) initialize_list.append(1) qubits = list(range(len(initialize_list))) circuit = initialize_bv(initialize_list) # Generate Uf oracle from f (anonymous function) uf_gate = generate_uf(f, n) # Applying the uf_gate must be done with the qubits in the reverse order due to the implementation of qiskit rv_qubits = qubits[::-1] circuit.unitary(uf_gate, rv_qubits) # Apply H to all qubits except for the last qubit apply_to_list = [1] * n apply_to_list.append(0) circuit = apply_H(circuit, apply_to_list) circuit.measure(range(n),range(n)) # run simulator and measure qubits simulator = Aer.get_backend("qasm_simulator") job = execute(circuit, simulator, shots=1) result = job.result() counts = result.get_counts(circuit) plot_histogram(counts) for count in counts: a = count return a,b def f_bv(x): n = len(x) y = 0 for i,x_i in enumerate(x): y = (y + (x_i*(i%2)))%2 y = (y+(n%2))%2 return(y) times = [] for i in range(1,input_size+1): start = process_time() res = bernstein_vazirani_algorithm(f_bv, i) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.3f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 15, step=1)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("BV: Execution Time vs. Input Size") def get_Z0(n): """ This function generates the Z0 gate satisfying the conditions for x in {0,1}^n Z0|x> -> -|x> iff x = 0^n otherwise Z0|x> -> |x> The parameter to this function is only the size n, a 2^n x 2^n dimensional matrix is created satisfying the conditions above. This function has one dependency, the DefGate function defined in pyquil.quil This function is designed to absorb the negative in G, so the returned gate is actually -Z0 Returns -Z0 """ # Create a 2^n x 2^n matrix with all 0's gate = np.zeros((2 ** n, 2 ** n), dtype=int) # since this is -Z0, set first element to 1 not -1 gate[0][0] = 1 # set all other elements on the diagonal to -1, again not 1 because this is -Z0 for i in range(1, 2 ** n): gate[i][i] = -1 # Return gate return Operator(gate) def get_Zf(f, n): """ This function generates the Zf gate satisfying the condition for x in {0,1}^n where Zf|x> -> (-1)^f(X)|x> This function requires that f(x) be calculated for all x, so f is passed as an anonymous function, the other parameter is n. The function has one dependency, the DefGate function defined in pyquil.quil This function finds all permutations of bitstrings of length n, then initializes a 2^n x 2^n matrix of all 0's, and sets all elements along the diagonal to either 1 or -1 depending on f(x) Finally a gate representation of this matrix is returned. """ # generate bitstring permutations bitstrings = list() get_bitstring_permutations(0, bitstrings, n, [0] * n) # initialize a 2^n x 2^n matrix of all 0's gate = np.zeros((2 ** n, 2 ** n), dtype=int) # set diagonals of matrix based on f(x) for i in range(2 ** n): gate[i][i] = -1 if f(bitstrings[i]) == 1 else 1 # create and return gate return Operator(gate) def grovers_algorithm(f, n, shots=1024, threshold=0.9): """ This function is intended to determine if there exists an x in {0,1}^n s.t. f(x) = 1 for a given function f s.t. f:{0,1}^n -> {0,1}. The algorithm first constructs Zf, -Z0 gates, initializes with Hanamard matrices, and applies G = -H^n o Z0 o H^n o Zf. This algorithm is not deterministic, so G is applied multiple times. More specifically, G is run (pi / 4 * sqrt(n)) times. Furthermore, there are 10 trials to minimize the chance of a false negative. This function has an anonymous function and integer n as parameters. This function runs the algorithm as described for each 10 trials, and then checks if for any of the outputted states x, if f(x) = 1. If this is true, then 1 is returned, otherwise 0 is returned. The function returns 0 if there is an issue with the simulator. This function uses 9q-squared-qvm, so it assumes that n <= 9 """ # Initialize the circuit and apply Hadamards to all qubits quantum_circuit, quantum_register, classical_register = initialize_dj(n) # Needed for application of custom gates since Operator works in reverse rv_qr = list() for index in range(n): rv_qr.append(index) rv_qr.reverse() # Define and generate Z0 gate (really -Z0) z0_gate = get_Z0(n) # Define and generate Zf gate zf_gate = get_Zf(f, n) # Determine the number of times to apply G iteration_count = floor(pi / 4 * sqrt(2 ** n)) # Apply G iteration_count times for i in range(iteration_count): # Apply Zf quantum_circuit.unitary(zf_gate, rv_qr) # Apply H to all qubits for index in range(n): quantum_circuit.h(quantum_register[index]) # Apply -Z0 quantum_circuit.unitary(z0_gate, rv_qr) # Apply H to all qubits for index in range(n): quantum_circuit.h(quantum_register[index]) quantum_circuit.barrier() # Run simulator quantum_simulator = Aer.get_backend('qasm_simulator') quantum_circuit.measure(quantum_register[0:n], classical_register) # Display circuit diagram quantum_circuit.draw('mpl') plt.show() # Execute and evaluate the job results job = execute(quantum_circuit, quantum_simulator, shots=shots) results = job.result() counts = results.get_counts(quantum_circuit) return counts # Parse results and return 1 or 0 accordingly # dict = {} # for key in counts: # if counts[key] >= (shots/(2**n)): # dict[key] = counts[key] # for key in dict: # poop = list(key) # poop = [int(i) for i in poop] # poop.reverse() # if f(poop) == 1: # return 1 # return 0 def f_0(args): return 0 def f_1(args): return 1 def f_100(args): n = len(args) marked = [0]*(n-1) marked.append(1) if(args == marked): return 1 return 0 input_size = 8 times = [] for i in range(1,input_size+1): start = process_time() res = grovers_algorithm(f_0, i, shots=1024, threshold=0.9) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.4f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 3.5, step=0.5)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("Grover's: Execution Time of Zero-Function vs. Input Size") times = [] for i in range(1,input_size+1): start = process_time() res = grovers_algorithm(f_1, i, shots=1024, threshold=0.9) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.4f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 3.5, step=0.5)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("Grover's: Execution Time of One-Function vs. Input Size") times = [] for i in range(1,input_size+1): start = process_time() res = grovers_algorithm(f_100, i, shots=1024, threshold=0.9) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.4f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 3.5, step=0.5)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("Grover's: Execution Time of First-Bit-Function vs. Input Size") def generate_uf_simons(f, n): """ Parameters: f is an anonymous function and n is the number of bits in input: f:{0,1}^n -> {0,1}^n This function returns an oracle gate representing the function f for all x in {0,1}^n and y in {0,1}^n, the desired result is of the oracle is mapping the input x,y> to |x, y + f(x)> where + is addition modulo 2. The function first finds the list of bitstring permutations of n bits, it then establishes a mapping which is representative of the decimal number of the bitstring represents. For each |x,y>, it calculates |x, y + f(x)>. Finally it constructs a permutation gate which treats each permutation as a different basis vector in the 2^(n+1) dimensional complex Hilbert space that represents a system of 2*n qubits. Returns: the permutation gate """ # generate list of all bitstrings of size n bitstrings = [] get_bitstring_permutations(0, bitstrings, 2 * n, [0] * (2 * n)) # initialize mapping and permutation list perm_dict = dict() perm_list = [] # populate mapping for permutation, bitstring in enumerate(bitstrings): values = [0]*(len(bitstrings)) values[permutation] = 1 perm_dict["".join(str(bit) for bit in bitstring)] = values # Send each |xy> to |x, f(x) + y> for bitstring in bitstrings: params = bitstring[:n] params2 = bitstring[n:2 * n] f_values = f(bitstring[:n]) for i in range(n): params.append((params2[i] + f_values[i]) % 2) perm_list.append(perm_dict["".join(str(bit) for bit in params)]) return Operator(np.array(perm_list)) def simons_solver(Y, n): """ Inputs: Y is a linear system of n-1 equations in matrix form. n is the dimension of the input into f. This function acts as a binary linear matrix solver. Returns: the key string s, if found, or the zero bitstring """ # Create all possible bit strings to test for s bitstrings = [] get_bitstring_permutations(0, bitstrings, n, [0] * n) # For each possible s, test to see if it's a candidate for s in bitstrings: if s == [0] * n: continue candidate = True # For each equation in Y, bit by bit test that y*s = [0]*n for y in Y: value = 0 for i in np.arange(n): value = value + s[i] * y[i] # If a bit doesn't evaluate to 0... if (value % 2 == 1): candidate = False if (candidate): return s return [0] * n def simons_algorithm(f, n): """ Inputs: f is a blackbox function (f:{0,1}^n -> {0,1}^n) that is either one-to-one or two-to-one. n is the dimension of the input into f. This function finds and returns the key s, if one exists, for a two-to-one function by first creating a matrix U_f that represents f, then applying the appropriate quantum gates to generate a linear equation. By running the circuit until we generate n-1 unique equations, the set of equations can solve for s. The Classical solver returns s. Returns: the key string s, if found, or the zero bitstring """ #Generate the oracle gate oracle = generate_uf_simons(f, n) #Initialize the circuit circuit = QuantumCircuit(2*n, 2*n) #initialize the simulator, use qasm_simulator simulator = Aer.get_backend("qasm_simulator") indices = list(range(2*n)) indices.reverse() #apply Hadamards to first n qubits for i in range(n): circuit.h(i) #apply oracle gate circuit.unitary(oracle, indices, label="oracle") #apply Hadamards again to first n qubits for i in range(n): circuit.h(i) indices = list(range(n)) #measure first n qubits circuit.measure(indices, indices) #Run the entire process 20 times for i in range(20): s = set() s_trials = [] #Run quantum circuit until at least n-1 unique eqautions are obtained while(len(s) < n-1): job = execute(circuit, simulator, shots=1) result = job.result() counts = result.get_counts() for count in counts: s.add(count[2*n:n-1:-1]) for bitstring in s: s_trials.append([int(bit) for bit in bitstring]) s_trials = np.array(s_trials) #Solve system of equations val = simons_solver(s_trials, n) if val == [0] * n: continue #if the correct function value is found, no need to keep searching f_val = f(val) if f_val == f([0]*n): return val #s not found, return 0 bit string return [0] * n def f_oto(x): return x def f_tto(x): res = [0] if (len(x)>1): res = res + x[1:] return res input_size = 5 times = [] for i in range(1,input_size+1): start = process_time() res = simons_algorithm(f_oto, i) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.4f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 450, step=50)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("Simon's: Execution Time of One-to-One Function vs. Input Size") input_size = 5 times = [] for i in range(1,input_size+1): start = process_time() res = simons_algorithm(f_tto, i) times.append(process_time()-start) print(times) plt.plot(range(1,input_size+1), times) for x,y in zip(range(1,input_size+1),times): label = "{:.4f}".format(y) plt.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='right') # horizontal alignment can be left, right or center plt.xticks(np.arange(0, input_size+1, step=1)) plt.yticks(np.arange(0, 10, step=1)) plt.ylabel("Execution Time (s)") plt.xlabel("Input Size (n)") plt.title("Simon's: Execution Time of Two-to-One Function vs. Input Size")
https://github.com/danieljaffe/quantum-algorithms-qiskit
danieljaffe
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/bibscore/qiskit_kindergarten
bibscore
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/bibscore/qiskit_kindergarten
bibscore
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/bibscore/qiskit_kindergarten
bibscore
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.tools.monitor import job_monitor import matplotlib as mpl import numpy as np # import basic plot tools from qiskit.visualization import plot_histogram # length of the n-bit string n = 4 constant_oracle = QuantumCircuit(n+1) constant_oracle.clear() output = np.random.randint(2) # random no. 0/1 as output if output == 1: constant_oracle.x(n) balance_oracle = QuantumCircuit(n+1) balance_oracle.clear() b_str = "1000" # implementing x-gates for i in range(len(b_str)): if b_str[i] == '1': balance_oracle.x(i) balance_oracle.barrier() # implementing cnot gates for qubit in range(n): balance_oracle.cx(qubit, n) balance_oracle.barrier() balance_oracle.draw() # implemneting x-gates for i in range (len(b_str)): if b_str[i] == '1': balance_oracle.x(i) balance_oracle.barrier() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(constant_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) dj_circuit.draw('mpl') aer_sim = Aer.get_backend('aer_simulator') #Local Simulator shots = 1024 #No. of times the circuit is running qobj = assemble(dj_circuit, shots = shots) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts)
https://github.com/bibscore/qiskit_kindergarten
bibscore
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.tools.monitor import job_monitor import matplotlib as mpl # import basic plot tools from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np from numpy import pi qft_circuit = QuantumCircuit(3) qft_circuit.clear() #input state= 5 qft_circuit.x(0) qft_circuit.x(2) qft_circuit.h(0) qft_circuit.cp(pi/2,0,1) qft_circuit.cp(pi/4,0,2) qft_circuit.h(1) qft_circuit.cp(pi/2,1,2) qft_circuit.h(2) #qft_circuit.swap(0,2) qft_circuit.draw('mpl') #output is the bloch sphere representation in the fourier basis sim = Aer.get_backend("aer_simulator") qft_circuit_init = qft_circuit.copy() qft_circuit_init.save_statevector() statevector = sim.run(qft_circuit_init).result().get_statevector() plot_bloch_multivector(statevector) IBMQ.save_account('') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True)) print(backend) t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything job = backend.run(t_qc)#backend means device job_monitor(job)
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os from qiskit import * import qiskit.tools.visualization as qt from PIL import Image from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(3, 'q') crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") circuit = QuantumCircuit(qreg_q, crz, crx) circuit.x(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) initial = circuit.copy() circuit.barrier() circuit.h(qreg_q[1]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.barrier() circuit.cx(qreg_q[0], qreg_q[1]) circuit.h(qreg_q[0]) circuit.barrier() circuit.measure(qreg_q[0], 0) circuit.measure(qreg_q[1], 1) circuit.barrier() circuit.draw(output='mpl') simulator_qasm = Aer.get_backend('qasm_simulator') simulator_aer = Aer.get_backend("aer_simulator") result = execute(circuit, backend=simulator_qasm, shots=1024).result() counts = result.get_counts() qt.plot_histogram(counts, color="#625BF5", title="Qubits outputs for quantum teleportation circuit") def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) bob_gates(circuit, 2, crz, crx) circuit.draw(output='mpl') initial.draw(output='mpl') initial.save_statevector() statevector = simulator_aer.run(initial).result().get_statevector() qt.plot_bloch_multivector(statevector) circuit.save_statevector() statevector2 = simulator_aer.run(circuit).result().get_statevector() qt.plot_bloch_multivector(statevector2)
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuits = [] for i in range(0, 4): circuits.append(QuantumCircuit(qreg_q, creg_c)) def entlanging(circuit, qreg_q): circuit.barrier() circuit.h(qreg_q[0]) circuit.cnot(qreg_q[0], qreg_q[1]) circuit.barrier() # 00 state circuits[0].reset(qreg_q[0]) circuits[0].reset(qreg_q[1]) entlanging(circuits[0], qreg_q) # 01 state circuits[1].reset(qreg_q[0]) circuits[1].x(qreg_q[1]) entlanging(circuits[1], qreg_q) # 10 state circuits[2].x(qreg_q[0]) circuits[2].reset(qreg_q[1]) entlanging(circuits[2], qreg_q) # 11 state circuits[3].x(qreg_q[0]) circuits[3].x(qreg_q[1]) entlanging(circuits[3], qreg_q) simulator = Aer.get_backend('qasm_simulator') circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].measure(qreg_q[1], creg_c[1]) result0 = execute(circuits[0], backend=simulator, shots=1024).result() counts0 = result0.get_counts() qt.plot_histogram(counts0, color="#5C9DFF", title="Entangled qubits values for input |00>") circuits[0].draw(output='mpl') circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].measure(qreg_q[1], creg_c[1]) result1 = execute(circuits[1], backend=simulator, shots=1024).result() counts1 = result1.get_counts() qt.plot_histogram(counts1, color="#5C9DFF", title="Entangled qubits values for input |01>") circuits[1].draw(output='mpl') circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].measure(qreg_q[1], creg_c[1]) result2 = execute(circuits[2], backend=simulator, shots=1024).result() counts2 = result2.get_counts() qt.plot_histogram(counts2, color="#5C9DFF", title="Entangled qubits values for input |10>") circuits[2].draw(output='mpl') circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].measure(qreg_q[1], creg_c[1]) result3 = execute(circuits[3], backend=simulator, shots=1024).result() counts3 = result3.get_counts() qt.plot_histogram(counts3, color="#5C9DFF", title="Entangled qubits values for input |11>") circuits[3].draw(output='mpl')
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') circuits = [] for i in range(0, 4): circuits.append(QuantumCircuit(qreg_q, creg_c)) circuits[0].reset(qreg_q[0]) circuits[0].reset(qreg_q[1]) circuits[0].cx(qreg_q[0], qreg_q[1]) circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].measure(qreg_q[1], creg_c[1]) circuits[0].draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result00 = execute(circuits[0], backend = simulator, shots = 1).result() counts00 = result00.get_counts() print(counts00) qt.plot_histogram(counts00, title="Histogram with the evaluating of |00> state under CNOT transformation") circuits[1].reset(qreg_q[0]) circuits[1].x(qreg_q[1]) circuits[1].cx(qreg_q[0], qreg_q[1]) circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].measure(qreg_q[1], creg_c[1]) circuits[1].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result01 = execute(circuits[1], backend = simulator, shots = 1).result() counts01 = result01.get_counts() print(counts01) qt.plot_histogram(counts01, title="Histogram with the evaluating of |01> state under CNOT transformation") circuits[2].x(qreg_q[0]) circuits[2].reset(qreg_q[1]) circuits[2].cx(qreg_q[0], qreg_q[1]) circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].measure(qreg_q[1], creg_c[1]) circuits[2].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result10 = execute(circuits[2], backend = simulator, shots = 1).result() counts10 = result10.get_counts() print(counts10) qt.plot_histogram(counts10, title="Histogram with the evaluating of |10> state under CNOT transformation") circuits[3].x(qreg_q[0]) circuits[3].x(qreg_q[1]) circuits[3].cx(qreg_q[0], qreg_q[1]) circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].measure(qreg_q[1], creg_c[1]) circuits[3].draw(output="mpl") simulator = Aer.get_backend('qasm_simulator') result11 = execute(circuits[3], backend = simulator, shots = 1).result() counts11 = result11.get_counts() print(counts11) qt.plot_histogram(counts11, title="Histogram with the evaluating of |11> state under CNOT transformation")
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(3, 'q') creg_c = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.x(qreg_q[0]) circuit.x(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.toffoli(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[2], creg_c[2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 1024).result() counts = result.get_counts() print(counts) qt.plot_histogram(counts, title="Histogram with the evaluating of |011> state under Toffoli transformation")
https://github.com/bibscore/qiskit_kindergarten
bibscore
import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.quantum_info import Statevector from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram %matplotlib inline import matplotlib.pyplot as plt from itertools import chain simulator = QasmSimulator() qreg = QuantumRegister(1, 'q') creg = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg, creg) circuit.reset(qreg[0]) circuit.h(qreg[0]) circuit.measure(qreg[0], creg[0]) circuit.draw(output='mpl') y0 = [] y1 = [] cont_zero = 0 cont_one = 0 for i in range(0, 100): circuit.measure(qreg[0], creg[0]) compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=1000) result = job.result() if(i == 0): counts0 = result.get_counts(compiled_circuit) counts = result.get_counts(compiled_circuit) y0.append(counts['0']/1000) y1.append(counts['1']/1000) cont_zero = cont_zero + counts['0']/1000.0 cont_one = cont_one + counts['1']/1000.0 print("\nTotal count for 0 and 1 are: ", counts) print("\naverage probability value of obtaining a 0 qubit state is: ", cont_zero/100.0) print("average probability value of obtaining a 1 qubit state is: ", cont_one/100.0) values = [counts0, counts] legend = ["first execution", "second execution"] color =["#625BF5", "#39D4D0"] plot_histogram(values, legend=legend, color=color, title="Hadamard gate measurement probability") fig, ax = plt.subplots(figsize=(10, 7)) x = np.arange(0, len(y0)) ax.plot(x, y0, "--*", color="#625BF5", label="collapsing into |0>") ax.plot(x, y1, "--*", color="#64CCC3", label="collapsing into |1>") plt.title("Hadamard gate measurement per iteration") plt.xlabel("Iterations") plt.ylabel("H gate measurement probability") plt.legend() plt.show()
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os import glob import numpy as np from numpy import pi from qiskit import * from qiskit.tools.visualization import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer import Aer import kaleidoscope.qiskit from kaleidoscope import qsphere import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(1, 'q') creg_c = ClassicalRegister(1, 'c') circuits = [] for i in range(0, 6): circuits.append(QuantumCircuit(qreg_q, creg_c)) inits = [] circuits[0].reset(qreg_q[0]) inits.append(circuits[0].copy()) circuits[0].x(qreg_q[0]) circuits[0].measure(qreg_q[0], creg_c[0]) circuits[0].draw(output="mpl") circuits[1].x(qreg_q[0]) inits.append(circuits[1].copy()) circuits[1].z(qreg_q[0]) circuits[1].measure(qreg_q[0], creg_c[0]) circuits[1].draw(output='mpl') circuits[2].x(qreg_q[0]) inits.append(circuits[2].copy()) circuits[2].s(qreg_q[0]) circuits[2].measure(qreg_q[0], creg_c[0]) circuits[2].draw(output='mpl') circuits[3].x(qreg_q[0]) inits.append(circuits[3].copy()) circuits[3].t(qreg_q[0]) circuits[3].measure(qreg_q[0], creg_c[0]) circuits[3].draw(output='mpl') circuits[4].x(qreg_q[0]) inits.append(circuits[4].copy()) circuits[4].y(qreg_q[0]) circuits[4].measure(qreg_q[0], creg_c[0]) circuits[4].draw(output='mpl') circuits[5].x(qreg_q[0]) inits.append(circuits[5].copy()) circuits[5].p(np.pi/2, qreg_q[0]) circuits[5].measure(qreg_q[0], creg_c[0]) circuits[5].draw(output='mpl') simulator_aer = Aer.get_backend("aer_simulator") statevector_init = [] statevector_circ = [] for i in range(0, 6): inits[i].save_statevector() statevector_init.append(simulator_aer.run(inits[i]).result().get_statevector()) circuits[i].save_statevector() statevector_circ.append(simulator_aer.run(circuits[i]).result().get_statevector()) archive_path = os.path.abspath('') os.chdir(archive_path) for index in range(0, len(statevector_init)): initial_figure = qsphere(statevector_init[index]) initial_figure.savefig("images/bloch_init" + str(index) + ".png") for index in range(0, len(statevector_circ)): final_figure = qsphere(statevector_circ[index]) final_figure.savefig("images/bloch_final" + str(index) + ".png")
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * 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) # Toffoli gate 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 = AND(inp1, inp2) print('AND with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n') # run the cell to define AND gate for real quantum system from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * from qiskit.tools.monitor import job_monitor from qiskit import IBMQ 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 #IBMQ.save_account('') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider('ibm-q') provider.backends() backend_ex = provider.get_backend('ibmq_lima') backend_ex #from qiskit.providers.ibmq import least_busy #backends = provider.backends(filters = lambda x:x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True) #backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) # run this cell backend = provider.get_backend('ibmq_quito') layout=None 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('') 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('mpl') print('') 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('mpl') print('') 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('mpl') print('') 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('mpl')
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * 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) # Toffoli gate 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')
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * 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.ccx(0,1,2) 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')
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.extensions import * from qiskit.tools.visualization import * 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('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 = XOR(inp1, inp2) print('XOR with inputs',inp1,inp2,'gives output',output) display(qc.draw()) print('\n')
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
from qiskit import * from qiskit.result import * from qiskit.extensions import * from qiskit.tools.visualization import * import numpy as np pi = np.pi def BoxIsVain(n): qreg_q = QuantumRegister(2, 'q') creg_c = ClassicalRegister(2, 'c') qc = QuantumCircuit(qreg_q, creg_c) qc.reset(0) for i in range(n): qc.reset(1) qc.rx(pi/(2*n), 0) # Bomb is a CNot gate, will send the result to secundary qubit #qc.cx(0, 1) #qc.measure(0, 0) qc.measure(1, 0) # output from qubit 2 is measured # We'll run the program on a simulator backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend,memory=True) output = job.result().get_memory()[0] display(plot_histogram(job.result().get_counts(qc))) return qc, output def BoxIsBomb(n): qr = QuantumRegister(4, 'q') cr = ClassicalRegister(4, 'c') qc = QuantumCircuit(qr, cr) qc.reset(0) for i in range(n): qc.reset(1) qc.rx(pi/(2*n), 0) # Bomb is a CNot gate, will send the result to secundary qubit qc.cx(0, 1) # Or gate qc.ccx(1,2,3) qc.cx(1,3) qc.cx(2,3) #qc.measure(0, 0) qc.measure(3, 0) # output from qubit 4 is measured # We'll run the program on a simulator backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend,memory=True) output = job.result().get_memory()[0] display(plot_histogram(job.result().get_counts(qc))) return qc, output ## Test the functions n=1 print("Test with 1 iteration => [ n=1 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n') n=2 print("Test with 2 iterations => [ n=2 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n') n=500 print("Test with 500 iterations => [ n=500 ] :") print('\n') qc, output = BoxIsVain(n) print('Box is Vain: Number of iterations n=',n,' gives output=Succeed Vain') display(qc.draw()) print('\n') qc, output = BoxIsBomb(n) if output[3] == '0': print('Box is Bomb: Number of iterations n=',n,' gives output=Succeed Bomb') elif output[3] == '1': print('Box is Bomb: Number of iterations n=',n,' gives output=blown up') display(qc.draw()) print('\n')
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
### Quantum Phase Estimation with 3 qubits ### import matplotlib.pyplot as plt import numpy as np import math from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.visualization import plot_histogram def qft_dagger(qc, n): for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe = QuantumCircuit(4, 3) qpe.x(3) for qubit in range(3): qpe.h(qubit) repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU repetitions *= 2 qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
DuarteSerranoR
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,4,7,8,11,13]: raise ValueError("'a' must be 2,4,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a in [4, 11]: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U # Specify variables n_count = 8 # number of counting qubits a = 7 # Period finding # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' # Factoring N = 39 #np.random.seed(1) # This is to make sure we get reproduceable results #a = randint(2, 15) #print(a) a = 2 from math import gcd # greatest common divisor gcd(a, N) def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # Initialize counting qubits in state |+> qc.x(3+n_count) # And auxiliary register in state |1> for q in range(n_count): # Do controlled-U operations qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT qc.measure(range(n_count), range(n_count)) # Simulate Results aer_sim = Aer.get_backend('aer_simulator') # Setting memory=True below allows us to see a list of each sequential reading t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc, shots=1) result = aer_sim.run(qobj, memory=True).result() readings = result.get_memory() print("Register Reading: " + readings[0]) phase = int(readings[0],2)/(2**n_count) print("Corresponding Phase: %f" % phase) return phase phase = qpe_amod15(a) # Phase = s/r Fraction(phase).limit_denominator(15) # Denominator should (hopefully!) tell us r frac = Fraction(phase).limit_denominator(15) s, r = frac.numerator, frac.denominator print(r) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print(guesses) a = 2 #a = 7 factor_found = False attempt = 0 while not factor_found: attempt += 1 print("\nAttempt %i:" % attempt) phase = qpe_amod15(a) # Phase = s/r frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r r = frac.denominator print("Result: r = %i" % r) if phase != 0: # Guesses for factors are gcd(x^{r/2} ±1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("Guessed Factors: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor print("*** Non-trivial factor found: %i ***" % guess) factor_found = True
https://github.com/ikemmm/qiskit-quantum-algorithms
ikemmm
# This algorithm demonstrates the creation of a Bell state. # In this state, 2 qubits are entangled to create a link between their final and intermediate states. # Let X and Y be the entangled qubits. # When qubit X collapses into the state 0, Y then must be in the state 1. # Through this concept, we create a unified final state probability distribution between # the two and proceed with the execution on the QASM simulator, a quantum virtual # machine. import qiskit as qk from qiskit import execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') STATE_MEASUREMENTS = 10000 # Create the circuit registers. qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) # Create the quantum circuit. # Contains a single Hadamard gate and a CNOT gate qc = qk.QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Prepare the measurement. measure_z = qk.QuantumCircuit(qr, cr) measure_z.measure(qr, cr) # Execute the job and take the measurement with the specified number of shots. test_z = qc + measure_z job_1 = qk.execute([test_z], backend, shots = STATE_MEASUREMENTS) counts = job_1.result().get_counts(test_z) print(counts)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import ( CircuitSampler, ListOp, StateFn, OperatorBase, ExpectationBase, ) from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_func from .list_or_dict import ListOrDict @deprecate_func( additional_msg=( "Instead, use the function " "``qiskit_algorithms.observables_evaluator.estimate_observables``. See " "https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def eval_observables( quantum_instance: QuantumInstance | Backend, quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, complex]]: """ Deprecated: Accepts a list or a dictionary of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. This function has been superseded by the :func:`qiskit_algorithms.observables_evaluator.eval_observables` function. It will be deprecated in a future release and subsequently removed after that. Args: quantum_instance: A quantum instance used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: A list or a dictionary of tuples (mean, standard deviation). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. """ if ( isinstance( quantum_state, (QuantumCircuit, OperatorBase) ) # Statevector cannot be parametrized and len(quantum_state.parameters) > 0 ): raise ValueError( "A parametrized representation of a quantum_state was provided. It is not " "allowed - it cannot have free parameters." ) # Create new CircuitSampler to avoid breaking existing one's caches. sampler = CircuitSampler(quantum_instance) list_op = _prepare_list_op(quantum_state, observables) observables_expect = expectation.convert(list_op) observables_expect_sampled = sampler.convert(observables_expect) # compute means values = np.real(observables_expect_sampled.eval()) # compute standard deviations # We use sampler.quantum_instance to take care of case in which quantum_instance is Backend std_devs = _compute_std_devs( observables_expect_sampled, observables, expectation, sampler.quantum_instance ) # Discard values below threshold observables_means = values * (np.abs(values) > threshold) # zip means and standard deviations into tuples observables_results = list(zip(observables_means, std_devs)) # Return None eigenvalues for None operators if observables is a list. # None operators are already dropped in compute_minimum_eigenvalue if observables is a dict. return _prepare_result(observables_results, observables) def _prepare_list_op( quantum_state: Statevector | QuantumCircuit | OperatorBase, observables: ListOrDict[OperatorBase], ) -> ListOp: """ Accepts a list or a dictionary of operators and converts them to a ``ListOp``. Args: quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators. Returns: A ``ListOp`` that includes all provided observables. """ if isinstance(observables, dict): observables = list(observables.values()) if not isinstance(quantum_state, StateFn): quantum_state = StateFn(quantum_state) return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables]) def _prepare_result( observables_results: list[tuple[complex, complex]], observables: ListOrDict[OperatorBase], ) -> ListOrDict[tuple[complex, complex]]: """ Prepares a list or a dictionary of eigenvalues from ``observables_results`` and ``observables``. Args: observables_results: A list of of tuples (mean, standard deviation). observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: A list or a dictionary of tuples (mean, standard deviation). """ if isinstance(observables, list): observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: observables_eigenvalues = {} key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: if observables[key] is not None: observables_eigenvalues[key] = value return observables_eigenvalues def _compute_std_devs( observables_expect_sampled: OperatorBase, observables: ListOrDict[OperatorBase], expectation: ExpectationBase, quantum_instance: QuantumInstance | Backend, ) -> list[complex]: """ Calculates a list of standard deviations from expectation values of observables provided. Args: observables_expect_sampled: Expected values of observables. observables: A list or a dictionary of operators whose expectation values are to be calculated. expectation: An instance of ExpectationBase which defines a method for calculating expectation values. quantum_instance: A quantum instance used for calculations. Returns: A list of standard deviations. """ variances = np.real(expectation.compute_variance(observables_expect_sampled)) if not isinstance(variances, np.ndarray) and variances == 0.0: # when `variances` is a single value equal to 0., our expectation value is exact and we # manually ensure the variances to be a list of the correct length variances = np.zeros(len(observables), dtype=float) # TODO: this will crash if quantum_instance is a backend std_devs = np.sqrt(variances / quantum_instance.run_config.shots) return std_devs
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Evaluator of observables for algorithms.""" from __future__ import annotations from collections.abc import Sequence from typing import Any import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.quantum_info import SparsePauliOp from .exceptions import AlgorithmError from .list_or_dict import ListOrDict from ..primitives import BaseEstimator from ..quantum_info.operators.base_operator import BaseOperator def estimate_observables( estimator: BaseEstimator, quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], parameter_values: Sequence[float] | None = None, threshold: float = 1e-12, ) -> ListOrDict[tuple[complex, dict[str, Any]]]: """ Accepts a sequence of operators and calculates their expectation values - means and metadata. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. Args: estimator: An estimator primitive used for calculations. quantum_state: A (parameterized) quantum circuit preparing a quantum state that expectation values are computed against. observables: A list or a dictionary of operators whose expectation values are to be calculated. parameter_values: Optional list of parameters values to evaluate the quantum circuit on. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: A list or a dictionary of tuples (mean, metadata). Raises: AlgorithmError: If a primitive job is not successful. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables if len(observables_list) > 0: observables_list = _handle_zero_ops(observables_list) quantum_state = [quantum_state] * len(observables) if parameter_values is not None: parameter_values = [parameter_values] * len(observables) try: estimator_job = estimator.run(quantum_state, observables_list, parameter_values) expectation_values = estimator_job.result().values except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc metadata = estimator_job.result().metadata # Discard values below threshold observables_means = expectation_values * (np.abs(expectation_values) > threshold) # zip means and metadata into tuples observables_results = list(zip(observables_means, metadata)) else: observables_results = [] return _prepare_result(observables_results, observables) def _handle_zero_ops( observables_list: list[BaseOperator | PauliSumOp], ) -> list[BaseOperator | PauliSumOp]: """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" if observables_list: zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)]) for ind, observable in enumerate(observables_list): if observable == 0: observables_list[ind] = zero_op return observables_list def _prepare_result( observables_results: list[tuple[complex, dict]], observables: ListOrDict[BaseOperator | PauliSumOp], ) -> ListOrDict[tuple[complex, dict[str, Any]]]: """ Prepares a list of tuples of eigenvalues and metadata tuples from ``observables_results`` and ``observables``. Args: observables_results: A list of tuples (mean, metadata). observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: A list or a dictionary of tuples (mean, metadata). """ if isinstance(observables, list): # by construction, all None values will be overwritten observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: observables_eigenvalues = {} key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: observables_eigenvalues[key] = value return observables_eigenvalues
https://github.com/ElePT/qiskit-algorithms-test
ElePT
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# -*- 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 Amplitude Estimation Algorithm. """ import logging from collections import OrderedDict import numpy as np from qiskit import ClassicalRegister from qiskit.aqua import AquaError from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.circuits import PhaseEstimationCircuit from qiskit.aqua.components.iqfts import Standard from .q_factory import QFactory logger = logging.getLogger(__name__) class AmplitudeEstimation(QuantumAlgorithm): """ The Amplitude Estimation algorithm. """ CONFIGURATION = { 'name': 'AmplitudeEstimation', 'description': 'Amplitude Estimation Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'AmplitudeEstimation_schema', 'type': 'object', 'properties': { 'num_eval_qubits': { 'type': 'integer', 'default': 5, 'minimum': 1 } }, 'additionalProperties': False }, 'problems': ['uncertainty'], 'depends': [ { 'pluggable_type': 'uncertainty_problem', 'default': { 'name': 'EuropeanCallDelta' } }, { 'pluggable_type': 'iqft', 'default': { 'name': 'STANDARD', } }, ], } def __init__(self, num_eval_qubits, a_factory, i_objective=None, q_factory=None, iqft=None): """ Constructor. Args: num_eval_qubits (int): number of evaluation qubits a_factory (CircuitFactory): the CircuitFactory subclass object representing the problem unitary q_factory (CircuitFactory): the CircuitFactory subclass object representing an amplitude estimation sample (based on a_factory) iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component, defaults to using a standard iqft when None """ self.validate(locals()) super().__init__() # get/construct A/Q operator self.a_factory = a_factory if q_factory is None: if i_objective is None: i_objective = self.a_factory.num_target_qubits - 1 self.q_factory = QFactory(a_factory, i_objective) else: self.q_factory = q_factory # get parameters self._m = num_eval_qubits self._M = 2 ** num_eval_qubits # determine number of ancillas self._num_ancillas = self.q_factory.required_ancillas_controlled() self._num_qubits = self.a_factory.num_target_qubits + self._m + self._num_ancillas if iqft is None: iqft = Standard(self._m) self._iqft = iqft self._circuit = None self._ret = {} @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance Args: params: parameters dictionary algo_input: Input instance """ if algo_input is not None: raise AquaError("Input instance not supported.") ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) num_eval_qubits = ae_params.get('num_eval_qubits') # Set up uncertainty problem. The params can include an uncertainty model # type dependent on the uncertainty problem and is this its responsibility # to create for itself from the complete params set that is passed to it. uncertainty_problem_params = params.get(Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM) uncertainty_problem = get_pluggable_class( PluggableType.UNCERTAINTY_PROBLEM, uncertainty_problem_params['name']).init_params(params) # Set up iqft, we need to add num qubits to params which is our num_ancillae bits here iqft_params = params.get(Pluggable.SECTION_KEY_IQFT) iqft_params['num_qubits'] = num_eval_qubits iqft = get_pluggable_class(PluggableType.IQFT, iqft_params['name']).init_params(params) return cls(num_eval_qubits, uncertainty_problem, q_factory=None, iqft=iqft) def construct_circuit(self, measurement=False): """ Construct the Amplitude Estimation quantum circuit. Args: measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: the QuantumCircuit object for the constructed circuit """ pec = PhaseEstimationCircuit( iqft=self._iqft, num_ancillae=self._m, state_in_circuit_factory=self.a_factory, unitary_circuit_factory=self.q_factory ) self._circuit = pec.construct_circuit(measurement=measurement) return self._circuit def _evaluate_statevector_results(self, probabilities): # map measured results to estimates y_probabilities = OrderedDict() for i, probability in enumerate(probabilities): b = "{0:b}".format(i).rjust(self._num_qubits, '0')[::-1] y = int(b[:self._m], 2) y_probabilities[y] = y_probabilities.get(y, 0) + probability a_probabilities = OrderedDict() for y, probability in y_probabilities.items(): if y >= int(self._M / 2): y = self._M - y a = np.power(np.sin(y * np.pi / 2 ** self._m), 2) a_probabilities[a] = a_probabilities.get(a, 0) + probability return a_probabilities, y_probabilities def _run(self): if self._quantum_instance.is_statevector: self.construct_circuit(measurement=False) # run circuit on statevector simlator ret = self._quantum_instance.execute(self._circuit) state_vector = np.asarray([ret.get_statevector(self._circuit)]) self._ret['statevector'] = state_vector # get state probabilities state_probabilities = np.real(state_vector.conj() * state_vector)[0] # evaluate results a_probabilities, y_probabilities = self._evaluate_statevector_results(state_probabilities) else: # run circuit on QASM simulator self.construct_circuit(measurement=True) ret = self._quantum_instance.execute(self._circuit) # get counts self._ret['counts'] = ret.get_counts() # construct probabilities y_probabilities = {} a_probabilities = {} shots = sum(ret.get_counts().values()) for state, counts in ret.get_counts().items(): y = int(state.replace(' ', '')[:self._m][::-1], 2) p = counts / shots y_probabilities[y] = p a = np.power(np.sin(y * np.pi / 2 ** self._m), 2) a_probabilities[a] = a_probabilities.get(a, 0.0) + p # construct a_items and y_items a_items = [(a, p) for (a, p) in a_probabilities.items() if p > 1e-6] y_items = [(y, p) for (y, p) in y_probabilities.items() if p > 1e-6] a_items = sorted(a_items) y_items = sorted(y_items) self._ret['a_items'] = a_items self._ret['y_items'] = y_items # map estimated values to original range and extract probabilities self._ret['mapped_values'] = [self.a_factory.value_to_estimation(a_item[0]) for a_item in self._ret['a_items']] self._ret['values'] = [a_item[0] for a_item in self._ret['a_items']] self._ret['y_values'] = [y_item[0] for y_item in y_items] self._ret['probabilities'] = [a_item[1] for a_item in self._ret['a_items']] self._ret['mapped_items'] = [(self._ret['mapped_values'][i], self._ret['probabilities'][i]) for i in range(len(self._ret['mapped_values']))] # determine most likely estimator self._ret['estimation'] = None self._ret['max_probability'] = 0 for val, prob in self._ret['mapped_items']: if prob > self._ret['max_probability']: self._ret['max_probability'] = prob self._ret['estimation'] = val return self._ret
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The Iterative Quantum Amplitude Estimation Algorithm.""" from __future__ import annotations from typing import cast import warnings import numpy as np from scipy.stats import beta from qiskit import ClassicalRegister, QuantumCircuit from qiskit.providers import Backend from qiskit.primitives import BaseSampler from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg, deprecate_func from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult from .estimation_problem import EstimationProblem from ..exceptions import AlgorithmError class IterativeAmplitudeEstimation(AmplitudeEstimator): r"""The Iterative Amplitude Estimation algorithm. This class implements the Iterative Quantum Amplitude Estimation (IQAE) algorithm, proposed in [1]. The output of the algorithm is an estimate that, with at least probability :math:`1 - \alpha`, differs by epsilon to the target value, where both alpha and epsilon can be specified. It differs from the original QAE algorithm proposed by Brassard [2] in that it does not rely on Quantum Phase Estimation, but is only based on Grover's algorithm. IQAE iteratively applies carefully selected Grover iterations to find an estimate for the target amplitude. References: [1]: Grinko, D., Gacon, J., Zoufal, C., & Woerner, S. (2019). Iterative Quantum Amplitude Estimation. `arXiv:1912.05559 <https://arxiv.org/abs/1912.05559>`_. [2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000). Quantum Amplitude Amplification and Estimation. `arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_. """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, epsilon_target: float, alpha: float, confint_method: str = "beta", min_ratio: float = 2, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" The output of the algorithm is an estimate for the amplitude `a`, that with at least probability 1 - alpha has an error of epsilon. The number of A operator calls scales linearly in 1/epsilon (up to a logarithmic factor). Args: epsilon_target: Target precision for estimation target `a`, has values between 0 and 0.5 alpha: Confidence level, the target probability is 1 - alpha, has values between 0 and 1 confint_method: Statistical method used to estimate the confidence intervals in each iteration, can be 'chernoff' for the Chernoff intervals or 'beta' for the Clopper-Pearson intervals (default) min_ratio: Minimal q-ratio (:math:`K_{i+1} / K_i`) for FindNextK quantum_instance: Deprecated: Quantum Instance or Backend sampler: A sampler primitive to evaluate the circuits. Raises: AlgorithmError: if the method to compute the confidence intervals is not supported ValueError: If the target epsilon is not in (0, 0.5] ValueError: If alpha is not in (0, 1) ValueError: If confint_method is not supported """ # validate ranges of input arguments if not 0 < epsilon_target <= 0.5: raise ValueError(f"The target epsilon must be in (0, 0.5], but is {epsilon_target}.") if not 0 < alpha < 1: raise ValueError(f"The confidence level alpha must be in (0, 1), but is {alpha}") if confint_method not in {"chernoff", "beta"}: raise ValueError( f"The confidence interval method must be chernoff or beta, but is {confint_method}." ) super().__init__() # set quantum instance with warnings.catch_warnings(): warnings.simplefilter("ignore") self.quantum_instance = quantum_instance # store parameters self._epsilon = epsilon_target self._alpha = alpha self._min_ratio = min_ratio self._confint_method = confint_method self._sampler = sampler @property def sampler(self) -> BaseSampler | None: """Get the sampler primitive. Returns: The sampler primitive to evaluate the circuits. """ return self._sampler @sampler.setter def sampler(self, sampler: BaseSampler) -> None: """Set sampler primitive. Args: sampler: A sampler primitive to evaluate the circuits. """ self._sampler = sampler @property @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self) -> QuantumInstance | None: """Deprecated. Get the quantum instance. Returns: The quantum instance used to run this algorithm. """ return self._quantum_instance @quantum_instance.setter @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Deprecated. Set quantum instance. Args: quantum_instance: The quantum instance used to run this algorithm. """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance @property def epsilon_target(self) -> float: """Returns the target precision ``epsilon_target`` of the algorithm. Returns: The target precision (which is half the width of the confidence interval). """ return self._epsilon @epsilon_target.setter def epsilon_target(self, epsilon: float) -> None: """Set the target precision of the algorithm. Args: epsilon: Target precision for estimation target `a`. """ self._epsilon = epsilon def _find_next_k( self, k: int, upper_half_circle: bool, theta_interval: tuple[float, float], min_ratio: float = 2.0, ) -> tuple[int, bool]: """Find the largest integer k_next, such that the interval (4 * k_next + 2)*theta_interval lies completely in [0, pi] or [pi, 2pi], for theta_interval = (theta_lower, theta_upper). Args: k: The current power of the Q operator. upper_half_circle: Boolean flag of whether theta_interval lies in the upper half-circle [0, pi] or in the lower one [pi, 2pi]. theta_interval: The current confidence interval for the angle theta, i.e. (theta_lower, theta_upper). min_ratio: Minimal ratio K/K_next allowed in the algorithm. Returns: The next power k, and boolean flag for the extrapolated interval. Raises: AlgorithmError: if min_ratio is smaller or equal to 1 """ if min_ratio <= 1: raise AlgorithmError("min_ratio must be larger than 1 to ensure convergence") # initialize variables theta_l, theta_u = theta_interval old_scaling = 4 * k + 2 # current scaling factor, called K := (4k + 2) # the largest feasible scaling factor K cannot be larger than K_max, # which is bounded by the length of the current confidence interval max_scaling = int(1 / (2 * (theta_u - theta_l))) scaling = max_scaling - (max_scaling - 2) % 4 # bring into the form 4 * k_max + 2 # find the largest feasible scaling factor K_next, and thus k_next while scaling >= min_ratio * old_scaling: theta_min = scaling * theta_l - int(scaling * theta_l) theta_max = scaling * theta_u - int(scaling * theta_u) if theta_min <= theta_max <= 0.5 and theta_min <= 0.5: # the extrapolated theta interval is in the upper half-circle upper_half_circle = True return int((scaling - 2) / 4), upper_half_circle elif theta_max >= 0.5 and theta_max >= theta_min >= 0.5: # the extrapolated theta interval is in the upper half-circle upper_half_circle = False return int((scaling - 2) / 4), upper_half_circle scaling -= 4 # if we do not find a feasible k, return the old one return int(k), upper_half_circle def construct_circuit( self, estimation_problem: EstimationProblem, k: int = 0, measurement: bool = False ) -> QuantumCircuit: r"""Construct the circuit :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`. The A operator is the unitary specifying the QAE problem and Q the associated Grover operator. Args: estimation_problem: The estimation problem for which to construct the QAE circuit. k: The power of the Q operator. measurement: Boolean flag to indicate if measurements should be included in the circuits. Returns: The circuit implementing :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`. """ num_qubits = max( estimation_problem.state_preparation.num_qubits, estimation_problem.grover_operator.num_qubits, ) circuit = QuantumCircuit(num_qubits, name="circuit") # add classical register if needed if measurement: c = ClassicalRegister(len(estimation_problem.objective_qubits)) circuit.add_register(c) # add A operator circuit.compose(estimation_problem.state_preparation, inplace=True) # add Q^k if k != 0: circuit.compose(estimation_problem.grover_operator.power(k), inplace=True) # add optional measurement if measurement: # real hardware can currently not handle operations after measurements, which might # happen if the circuit gets transpiled, hence we're adding a safeguard-barrier circuit.barrier() circuit.measure(estimation_problem.objective_qubits, c[:]) return circuit def _good_state_probability( self, problem: EstimationProblem, counts_or_statevector: dict[str, int] | np.ndarray, num_state_qubits: int, ) -> tuple[int, float] | float: """Get the probability to measure '1' in the last qubit. Args: problem: The estimation problem, used to obtain the number of objective qubits and the ``is_good_state`` function. counts_or_statevector: Either a counts-dictionary (with one measured qubit only!) or the statevector returned from the statevector_simulator. num_state_qubits: The number of state qubits. Returns: If a dict is given, return (#one-counts, #one-counts/#all-counts), otherwise Pr(measure '1' in the last qubit). """ if isinstance(counts_or_statevector, dict): one_counts = 0 for state, counts in counts_or_statevector.items(): if problem.is_good_state(state): one_counts += counts return int(one_counts), one_counts / sum(counts_or_statevector.values()) else: statevector = counts_or_statevector num_qubits = int(np.log2(len(statevector))) # the total number of qubits # sum over all amplitudes where the objective qubit is 1 prob = 0 for i, amplitude in enumerate(statevector): # consider only state qubits and revert bit order bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1] objectives = [bitstr[index] for index in problem.objective_qubits] if problem.is_good_state(objectives): prob = prob + np.abs(amplitude) ** 2 return prob def estimate( self, estimation_problem: EstimationProblem ) -> "IterativeAmplitudeEstimationResult": """Run the amplitude estimation algorithm on provided estimation problem. Args: estimation_problem: The estimation problem. Returns: An amplitude estimation results object. Raises: ValueError: A quantum instance or Sampler must be provided. AlgorithmError: Sampler job run error. """ if self._quantum_instance is None and self._sampler is None: raise ValueError("A quantum instance or sampler must be provided.") # initialize memory variables powers = [0] # list of powers k: Q^k, (called 'k' in paper) ratios = [] # list of multiplication factors (called 'q' in paper) theta_intervals = [[0, 1 / 4]] # a priori knowledge of theta / 2 / pi a_intervals = [[0.0, 1.0]] # a priori knowledge of the confidence interval of the estimate num_oracle_queries = 0 num_one_shots = [] # maximum number of rounds max_rounds = ( int(np.log(self._min_ratio * np.pi / 8 / self._epsilon) / np.log(self._min_ratio)) + 1 ) upper_half_circle = True # initially theta is in the upper half-circle if self._quantum_instance is not None and self._quantum_instance.is_statevector: # for statevector we can directly return the probability to measure 1 # note, that no iterations here are necessary # simulate circuit circuit = self.construct_circuit(estimation_problem, k=0, measurement=False) ret = self._quantum_instance.execute(circuit) # get statevector statevector = ret.get_statevector(circuit) # calculate the probability of measuring '1' num_qubits = circuit.num_qubits - circuit.num_ancillas prob = self._good_state_probability(estimation_problem, statevector, num_qubits) prob = cast(float, prob) # tell MyPy it's a float and not Tuple[int, float ] a_confidence_interval = [prob, prob] # type: list[float] a_intervals.append(a_confidence_interval) theta_i_interval = [ np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval # type: ignore ] theta_intervals.append(theta_i_interval) num_oracle_queries = 0 # no Q-oracle call, only a single one to A else: num_iterations = 0 # keep track of the number of iterations # number of shots per iteration shots = 0 # do while loop, keep in mind that we scaled theta mod 2pi such that it lies in [0,1] while theta_intervals[-1][1] - theta_intervals[-1][0] > self._epsilon / np.pi: num_iterations += 1 # get the next k k, upper_half_circle = self._find_next_k( powers[-1], upper_half_circle, theta_intervals[-1], # type: ignore min_ratio=self._min_ratio, ) # store the variables powers.append(k) ratios.append((2 * powers[-1] + 1) / (2 * powers[-2] + 1)) # run measurements for Q^k A|0> circuit circuit = self.construct_circuit(estimation_problem, k, measurement=True) counts = {} if self._quantum_instance is not None: ret = self._quantum_instance.execute(circuit) # get the counts and store them counts = ret.get_counts(circuit) shots = self._quantum_instance._run_config.shots else: try: job = self._sampler.run([circuit]) ret = job.result() except Exception as exc: raise AlgorithmError("The job was not completed successfully. ") from exc shots = ret.metadata[0].get("shots") if shots is None: circuit = self.construct_circuit(estimation_problem, k=0, measurement=True) try: job = self._sampler.run([circuit]) ret = job.result() except Exception as exc: raise AlgorithmError( "The job was not completed successfully. " ) from exc # calculate the probability of measuring '1' prob = 0.0 for bit, probabilities in ret.quasi_dists[0].binary_probabilities().items(): # check if it is a good state if estimation_problem.is_good_state(bit): prob += probabilities a_confidence_interval = [prob, prob] a_intervals.append(a_confidence_interval) theta_i_interval = [ np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval ] theta_intervals.append(theta_i_interval) num_oracle_queries = 0 # no Q-oracle call, only a single one to A break counts = { k: round(v * shots) for k, v in ret.quasi_dists[0].binary_probabilities().items() } # calculate the probability of measuring '1', 'prob' is a_i in the paper num_qubits = circuit.num_qubits - circuit.num_ancillas # type: ignore one_counts, prob = self._good_state_probability( estimation_problem, counts, num_qubits ) num_one_shots.append(one_counts) # track number of Q-oracle calls num_oracle_queries += shots * k # if on the previous iterations we have K_{i-1} == K_i, we sum these samples up j = 1 # number of times we stayed fixed at the same K round_shots = shots round_one_counts = one_counts if num_iterations > 1: while ( powers[num_iterations - j] == powers[num_iterations] and num_iterations >= j + 1 ): j = j + 1 round_shots += shots round_one_counts += num_one_shots[-j] # compute a_min_i, a_max_i if self._confint_method == "chernoff": a_i_min, a_i_max = _chernoff_confint(prob, round_shots, max_rounds, self._alpha) else: # 'beta' a_i_min, a_i_max = _clopper_pearson_confint( round_one_counts, round_shots, self._alpha / max_rounds ) # compute theta_min_i, theta_max_i if upper_half_circle: theta_min_i = np.arccos(1 - 2 * a_i_min) / 2 / np.pi theta_max_i = np.arccos(1 - 2 * a_i_max) / 2 / np.pi else: theta_min_i = 1 - np.arccos(1 - 2 * a_i_max) / 2 / np.pi theta_max_i = 1 - np.arccos(1 - 2 * a_i_min) / 2 / np.pi # compute theta_u, theta_l of this iteration scaling = 4 * k + 2 # current K_i factor theta_u = (int(scaling * theta_intervals[-1][1]) + theta_max_i) / scaling theta_l = (int(scaling * theta_intervals[-1][0]) + theta_min_i) / scaling theta_intervals.append([theta_l, theta_u]) # compute a_u_i, a_l_i a_u = np.sin(2 * np.pi * theta_u) ** 2 a_l = np.sin(2 * np.pi * theta_l) ** 2 a_u = cast(float, a_u) a_l = cast(float, a_l) a_intervals.append([a_l, a_u]) # get the latest confidence interval for the estimate of a confidence_interval = tuple(a_intervals[-1]) # the final estimate is the mean of the confidence interval estimation = np.mean(confidence_interval) result = IterativeAmplitudeEstimationResult() result.alpha = self._alpha result.post_processing = estimation_problem.post_processing result.num_oracle_queries = num_oracle_queries result.estimation = estimation result.epsilon_estimated = (confidence_interval[1] - confidence_interval[0]) / 2 result.confidence_interval = confidence_interval result.estimation_processed = estimation_problem.post_processing(estimation) confidence_interval = tuple( estimation_problem.post_processing(x) for x in confidence_interval ) result.confidence_interval_processed = confidence_interval result.epsilon_estimated_processed = (confidence_interval[1] - confidence_interval[0]) / 2 result.estimate_intervals = a_intervals result.theta_intervals = theta_intervals result.powers = powers result.ratios = ratios return result class IterativeAmplitudeEstimationResult(AmplitudeEstimatorResult): """The ``IterativeAmplitudeEstimation`` result object.""" def __init__(self) -> None: super().__init__() self._alpha: float | None = None self._epsilon_target: float | None = None self._epsilon_estimated: float | None = None self._epsilon_estimated_processed: float | None = None self._estimate_intervals: list[list[float]] | None = None self._theta_intervals: list[list[float]] | None = None self._powers: list[int] | None = None self._ratios: list[float] | None = None self._confidence_interval_processed: tuple[float, float] | None = None @property def alpha(self) -> float: r"""Return the confidence level :math:`\alpha`.""" return self._alpha @alpha.setter def alpha(self, value: float) -> None: r"""Set the confidence level :math:`\alpha`.""" self._alpha = value @property def epsilon_target(self) -> float: """Return the target half-width of the confidence interval.""" return self._epsilon_target @epsilon_target.setter def epsilon_target(self, value: float) -> None: """Set the target half-width of the confidence interval.""" self._epsilon_target = value @property def epsilon_estimated(self) -> float: """Return the estimated half-width of the confidence interval.""" return self._epsilon_estimated @epsilon_estimated.setter def epsilon_estimated(self, value: float) -> None: """Set the estimated half-width of the confidence interval.""" self._epsilon_estimated = value @property def epsilon_estimated_processed(self) -> float: """Return the post-processed estimated half-width of the confidence interval.""" return self._epsilon_estimated_processed @epsilon_estimated_processed.setter def epsilon_estimated_processed(self, value: float) -> None: """Set the post-processed estimated half-width of the confidence interval.""" self._epsilon_estimated_processed = value @property def estimate_intervals(self) -> list[list[float]]: """Return the confidence intervals for the estimate in each iteration.""" return self._estimate_intervals @estimate_intervals.setter def estimate_intervals(self, value: list[list[float]]) -> None: """Set the confidence intervals for the estimate in each iteration.""" self._estimate_intervals = value @property def theta_intervals(self) -> list[list[float]]: """Return the confidence intervals for the angles in each iteration.""" return self._theta_intervals @theta_intervals.setter def theta_intervals(self, value: list[list[float]]) -> None: """Set the confidence intervals for the angles in each iteration.""" self._theta_intervals = value @property def powers(self) -> list[int]: """Return the powers of the Grover operator in each iteration.""" return self._powers @powers.setter def powers(self, value: list[int]) -> None: """Set the powers of the Grover operator in each iteration.""" self._powers = value @property def ratios(self) -> list[float]: r"""Return the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" return self._ratios @ratios.setter def ratios(self, value: list[float]) -> None: r"""Set the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" self._ratios = value @property def confidence_interval_processed(self) -> tuple[float, float]: """Return the post-processed confidence interval.""" return self._confidence_interval_processed @confidence_interval_processed.setter def confidence_interval_processed(self, value: tuple[float, float]) -> None: """Set the post-processed confidence interval.""" self._confidence_interval_processed = value def _chernoff_confint( value: float, shots: int, max_rounds: int, alpha: float ) -> tuple[float, float]: """Compute the Chernoff confidence interval for `shots` i.i.d. Bernoulli trials. The confidence interval is [value - eps, value + eps], where eps = sqrt(3 * log(2 * max_rounds/ alpha) / shots) but at most [0, 1]. Args: value: The current estimate. shots: The number of shots. max_rounds: The maximum number of rounds, used to compute epsilon_a. alpha: The confidence level, used to compute epsilon_a. Returns: The Chernoff confidence interval. """ eps = np.sqrt(3 * np.log(2 * max_rounds / alpha) / shots) lower = np.maximum(0, value - eps) upper = np.minimum(1, value + eps) return lower, upper def _clopper_pearson_confint(counts: int, shots: int, alpha: float) -> tuple[float, float]: """Compute the Clopper-Pearson confidence interval for `shots` i.i.d. Bernoulli trials. Args: counts: The number of positive counts. shots: The number of shots. alpha: The confidence level for the confidence interval. Returns: The Clopper-Pearson confidence interval. """ lower, upper = 0, 1 # if counts == 0, the beta quantile returns nan if counts != 0: lower = beta.ppf(alpha / 2, counts, shots - counts + 1) # if counts == shots, the beta quantile returns nan if counts != shots: upper = beta.ppf(1 - alpha / 2, counts + 1, shots - counts) return lower, upper
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The Maximum Likelihood Amplitude Estimation algorithm.""" from __future__ import annotations import warnings from collections.abc import Sequence from typing import Callable, List, Tuple import numpy as np from scipy.optimize import brute from scipy.stats import norm, chi2 from qiskit.providers import Backend from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.primitives import BaseSampler from qiskit.utils.deprecation import deprecate_arg, deprecate_func from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult from .estimation_problem import EstimationProblem from ..exceptions import AlgorithmError MINIMIZER = Callable[[Callable[[float], float], List[Tuple[float, float]]], float] class MaximumLikelihoodAmplitudeEstimation(AmplitudeEstimator): """The Maximum Likelihood Amplitude Estimation algorithm. This class implements the quantum amplitude estimation (QAE) algorithm without phase estimation, as introduced in [1]. In comparison to the original QAE algorithm [2], this implementation relies solely on different powers of the Grover operator and does not require additional evaluation qubits. Finally, the estimate is determined via a maximum likelihood estimation, which is why this class in named ``MaximumLikelihoodAmplitudeEstimation``. References: [1]: Suzuki, Y., Uno, S., Raymond, R., Tanaka, T., Onodera, T., & Yamamoto, N. (2019). Amplitude Estimation without Phase Estimation. `arXiv:1904.10246 <https://arxiv.org/abs/1904.10246>`_. [2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000). Quantum Amplitude Amplification and Estimation. `arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_. """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, evaluation_schedule: list[int] | int, minimizer: MINIMIZER | None = None, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: evaluation_schedule: If a list, the powers applied to the Grover operator. The list element must be non-negative. If a non-negative integer, an exponential schedule is used where the highest power is 2 to the integer minus 1: `[id, Q^2^0, ..., Q^2^(evaluation_schedule-1)]`. minimizer: A minimizer used to find the minimum of the likelihood function. Defaults to a brute search where the number of evaluation points is determined according to ``evaluation_schedule``. The minimizer takes a function as first argument and a list of (float, float) tuples (as bounds) as second argument and returns a single float which is the found minimum. quantum_instance: Deprecated: Quantum Instance or Backend sampler: A sampler primitive to evaluate the circuits. Raises: ValueError: If the number of oracle circuits is smaller than 1. """ super().__init__() # set quantum instance with warnings.catch_warnings(): warnings.simplefilter("ignore") self.quantum_instance = quantum_instance # get parameters if isinstance(evaluation_schedule, int): if evaluation_schedule < 0: raise ValueError("The evaluation schedule cannot be < 0.") self._evaluation_schedule = [0] + [2**j for j in range(evaluation_schedule)] else: if any(value < 0 for value in evaluation_schedule): raise ValueError("The elements of the evaluation schedule cannot be < 0.") self._evaluation_schedule = evaluation_schedule if minimizer is None: # default number of evaluations is max(10^4, pi/2 * 10^3 * 2^(m)) nevals = max(10000, int(np.pi / 2 * 1000 * 2 * self._evaluation_schedule[-1])) def default_minimizer(objective_fn, bounds): return brute(objective_fn, bounds, Ns=nevals)[0] self._minimizer = default_minimizer else: self._minimizer = minimizer self._sampler = sampler @property def sampler(self) -> BaseSampler | None: """Get the sampler primitive. Returns: The sampler primitive to evaluate the circuits. """ return self._sampler @sampler.setter def sampler(self, sampler: BaseSampler) -> None: """Set sampler primitive. Args: sampler: A sampler primitive to evaluate the circuits. """ self._sampler = sampler @property @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self) -> QuantumInstance | None: """Deprecated. Get the quantum instance. Returns: The quantum instance used to run this algorithm. """ return self._quantum_instance @quantum_instance.setter @deprecate_func( since="0.24.0", is_property=True, additional_msg="See https://qisk.it/algo_migration for a migration guide.", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Deprecated. Set quantum instance. Args: quantum_instance: The quantum instance used to run this algorithm. """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance def construct_circuits( self, estimation_problem: EstimationProblem, measurement: bool = False ) -> list[QuantumCircuit]: """Construct the Amplitude Estimation w/o QPE quantum circuits. Args: estimation_problem: The estimation problem for which to construct the QAE circuit. measurement: Boolean flag to indicate if measurement should be included in the circuits. Returns: A list with the QuantumCircuit objects for the algorithm. """ # keep track of the Q-oracle queries circuits = [] num_qubits = max( estimation_problem.state_preparation.num_qubits, estimation_problem.grover_operator.num_qubits, ) q = QuantumRegister(num_qubits, "q") qc_0 = QuantumCircuit(q, name="qc_a") # 0 applications of Q, only a single A operator # add classical register if needed if measurement: c = ClassicalRegister(len(estimation_problem.objective_qubits)) qc_0.add_register(c) qc_0.compose(estimation_problem.state_preparation, inplace=True) for k in self._evaluation_schedule: qc_k = qc_0.copy(name=f"qc_a_q_{k}") if k != 0: qc_k.compose(estimation_problem.grover_operator.power(k), inplace=True) if measurement: # real hardware can currently not handle operations after measurements, # which might happen if the circuit gets transpiled, hence we're adding # a safeguard-barrier qc_k.barrier() qc_k.measure(estimation_problem.objective_qubits, c[:]) circuits += [qc_k] return circuits @staticmethod def compute_confidence_interval( result: "MaximumLikelihoodAmplitudeEstimationResult", alpha: float, kind: str = "fisher", apply_post_processing: bool = False, ) -> tuple[float, float]: """Compute the `alpha` confidence interval using the method `kind`. The confidence level is (1 - `alpha`) and supported kinds are 'fisher', 'likelihood_ratio' and 'observed_fisher' with shorthand notations 'fi', 'lr' and 'oi', respectively. Args: result: A maximum likelihood amplitude estimation result. alpha: The confidence level. kind: The method to compute the confidence interval. Defaults to 'fisher', which computes the theoretical Fisher information. apply_post_processing: If True, apply post-processing to the confidence interval. Returns: The specified confidence interval. Raises: AlgorithmError: If `run()` hasn't been called yet. NotImplementedError: If the method `kind` is not supported. """ interval: tuple[float, float] | None = None # if statevector simulator the estimate is exact if all(isinstance(data, (list, np.ndarray)) for data in result.circuit_results): interval = (result.estimation, result.estimation) elif kind in ["likelihood_ratio", "lr"]: interval = _likelihood_ratio_confint(result, alpha) elif kind in ["fisher", "fi"]: interval = _fisher_confint(result, alpha, observed=False) elif kind in ["observed_fisher", "observed_information", "oi"]: interval = _fisher_confint(result, alpha, observed=True) if interval is None: raise NotImplementedError(f"CI `{kind}` is not implemented.") if apply_post_processing: return result.post_processing(interval[0]), result.post_processing(interval[1]) return interval def compute_mle( self, circuit_results: list[dict[str, int] | np.ndarray], estimation_problem: EstimationProblem, num_state_qubits: int | None = None, return_counts: bool = False, ) -> float | tuple[float, list[float]]: """Compute the MLE via a grid-search. This is a stable approach if sufficient gridpoints are used. Args: circuit_results: A list of circuit outcomes. Can be counts or statevectors. estimation_problem: The estimation problem containing the evaluation schedule and the number of likelihood function evaluations used to find the minimum. num_state_qubits: The number of state qubits, required for statevector simulations. return_counts: If True, returns the good counts. Returns: The MLE for the provided result object. """ good_counts, all_counts = _get_counts(circuit_results, estimation_problem, num_state_qubits) # search range eps = 1e-15 # to avoid invalid value in log search_range = [0 + eps, np.pi / 2 - eps] def loglikelihood(theta): # loglik contains the first `it` terms of the full loglikelihood loglik = 0 for i, k in enumerate(self._evaluation_schedule): angle = (2 * k + 1) * theta loglik += np.log(np.sin(angle) ** 2) * good_counts[i] loglik += np.log(np.cos(angle) ** 2) * (all_counts[i] - good_counts[i]) return -loglik est_theta = self._minimizer(loglikelihood, [search_range]) if return_counts: return est_theta, good_counts return est_theta def estimate( self, estimation_problem: EstimationProblem ) -> "MaximumLikelihoodAmplitudeEstimationResult": """Run the amplitude estimation algorithm on provided estimation problem. Args: estimation_problem: The estimation problem. Returns: An amplitude estimation results object. Raises: ValueError: A quantum instance or Sampler must be provided. AlgorithmError: If `state_preparation` is not set in `estimation_problem`. AlgorithmError: Sampler job run error """ if self._quantum_instance is None and self._sampler is None: raise ValueError("A quantum instance or sampler must be provided.") if estimation_problem.state_preparation is None: raise AlgorithmError( "The state_preparation property of the estimation problem must be set." ) result = MaximumLikelihoodAmplitudeEstimationResult() result.evaluation_schedule = self._evaluation_schedule result.minimizer = self._minimizer result.post_processing = estimation_problem.post_processing shots = 0 if self._quantum_instance is not None and self._quantum_instance.is_statevector: # run circuit on statevector simulator circuits = self.construct_circuits(estimation_problem, measurement=False) ret = self._quantum_instance.execute(circuits) # get statevectors and construct MLE input statevectors = [np.asarray(ret.get_statevector(circuit)) for circuit in circuits] result.circuit_results = statevectors # to count the number of Q-oracle calls (don't count shots) result.shots = 1 else: circuits = self.construct_circuits(estimation_problem, measurement=True) if self._quantum_instance is not None: # run circuit on QASM simulator ret = self._quantum_instance.execute(circuits) # get counts and construct MLE input result.circuit_results = [ret.get_counts(circuit) for circuit in circuits] shots = self._quantum_instance._run_config.shots else: try: job = self._sampler.run(circuits) ret = job.result() except Exception as exc: raise AlgorithmError("The job was not completed successfully. ") from exc result.circuit_results = [] shots = ret.metadata[0].get("shots") if shots is None: for quasi_dist in ret.quasi_dists: circuit_result = quasi_dist.binary_probabilities() result.circuit_results.append(circuit_result) shots = 1 else: # get counts and construct MLE input for quasi_dist in ret.quasi_dists: counts = { k: round(v * shots) for k, v in quasi_dist.binary_probabilities().items() } result.circuit_results.append(counts) result.shots = shots # run maximum likelihood estimation num_state_qubits = circuits[0].num_qubits - circuits[0].num_ancillas theta, good_counts = self.compute_mle( result.circuit_results, estimation_problem, num_state_qubits, True ) # store results result.theta = theta result.good_counts = good_counts result.estimation = np.sin(result.theta) ** 2 # not sure why pylint complains, this is a callable and the tests pass # pylint: disable=not-callable result.estimation_processed = result.post_processing(result.estimation) result.fisher_information = _compute_fisher_information(result) result.num_oracle_queries = result.shots * sum(k for k in result.evaluation_schedule) # compute and store confidence interval confidence_interval = self.compute_confidence_interval(result, alpha=0.05, kind="fisher") result.confidence_interval = confidence_interval result.confidence_interval_processed = tuple( estimation_problem.post_processing(value) for value in confidence_interval ) return result class MaximumLikelihoodAmplitudeEstimationResult(AmplitudeEstimatorResult): """The ``MaximumLikelihoodAmplitudeEstimation`` result object.""" def __init__(self) -> None: super().__init__() self._theta: float | None = None self._minimizer: Callable | None = None self._good_counts: list[float] | None = None self._evaluation_schedule: list[int] | None = None self._fisher_information: float | None = None @property def theta(self) -> float: r"""Return the estimate for the angle :math:`\theta`.""" return self._theta @theta.setter def theta(self, value: float) -> None: r"""Set the estimate for the angle :math:`\theta`.""" self._theta = value @property def minimizer(self) -> Callable: """Return the minimizer used for the search of the likelihood function.""" return self._minimizer @minimizer.setter def minimizer(self, value: Callable) -> None: """Set the number minimizer used for the search of the likelihood function.""" self._minimizer = value @property def good_counts(self) -> list[float]: """Return the percentage of good counts per circuit power.""" return self._good_counts @good_counts.setter def good_counts(self, counts: list[float]) -> None: """Set the percentage of good counts per circuit power.""" self._good_counts = counts @property def evaluation_schedule(self) -> list[int]: """Return the evaluation schedule for the powers of the Grover operator.""" return self._evaluation_schedule @evaluation_schedule.setter def evaluation_schedule(self, evaluation_schedule: list[int]) -> None: """Set the evaluation schedule for the powers of the Grover operator.""" self._evaluation_schedule = evaluation_schedule @property def fisher_information(self) -> float: """Return the Fisher information for the estimated amplitude.""" return self._fisher_information @fisher_information.setter def fisher_information(self, value: float) -> None: """Set the Fisher information for the estimated amplitude.""" self._fisher_information = value def _safe_min(array, default=0): if len(array) == 0: return default return np.min(array) def _safe_max(array, default=(np.pi / 2)): if len(array) == 0: return default return np.max(array) def _compute_fisher_information( result: "MaximumLikelihoodAmplitudeEstimationResult", num_sum_terms: int | None = None, observed: bool = False, ) -> float: """Compute the Fisher information. Args: result: A maximum likelihood amplitude estimation result. num_sum_terms: The number of sum terms to be included in the calculation of the Fisher information. By default all values are included. observed: If True, compute the observed Fisher information, otherwise the theoretical one. Returns: The computed Fisher information, or np.inf if statevector simulation was used. Raises: KeyError: Call run() first! """ a = result.estimation # Corresponding angle to the value a (only use real part of 'a') theta_a = np.arcsin(np.sqrt(np.real(a))) # Get the number of hits (shots_k) and one-hits (h_k) one_hits = result.good_counts all_hits = [result.shots] * len(one_hits) # Include all sum terms or just up to a certain term? evaluation_schedule = result.evaluation_schedule if num_sum_terms is not None: evaluation_schedule = evaluation_schedule[:num_sum_terms] # not necessary since zip goes as far as shortest list: # all_hits = all_hits[:num_sum_terms] # one_hits = one_hits[:num_sum_terms] # Compute the Fisher information fisher_information = None if observed: # Note, that the observed Fisher information is very unreliable in this algorithm! d_loglik = 0 for shots_k, h_k, m_k in zip(all_hits, one_hits, evaluation_schedule): tan = np.tan((2 * m_k + 1) * theta_a) d_loglik += (2 * m_k + 1) * (h_k / tan + (shots_k - h_k) * tan) d_loglik /= np.sqrt(a * (1 - a)) fisher_information = d_loglik**2 / len(all_hits) else: fisher_information = sum( shots_k * (2 * m_k + 1) ** 2 for shots_k, m_k in zip(all_hits, evaluation_schedule) ) fisher_information /= a * (1 - a) return fisher_information def _fisher_confint( result: MaximumLikelihoodAmplitudeEstimationResult, alpha: float = 0.05, observed: bool = False ) -> tuple[float, float]: """Compute the `alpha` confidence interval based on the Fisher information. Args: result: A maximum likelihood amplitude estimation results object. alpha: The level of the confidence interval (must be <= 0.5), default to 0.05. observed: If True, use observed Fisher information. Returns: float: The alpha confidence interval based on the Fisher information Raises: AssertionError: Call run() first! """ # Get the (observed) Fisher information fisher_information = None try: fisher_information = result.fisher_information except KeyError as ex: raise AssertionError("Call run() first!") from ex if observed: fisher_information = _compute_fisher_information(result, observed=True) normal_quantile = norm.ppf(1 - alpha / 2) confint = np.real(result.estimation) + normal_quantile / np.sqrt(fisher_information) * np.array( [-1, 1] ) return result.post_processing(confint[0]), result.post_processing(confint[1]) def _likelihood_ratio_confint( result: MaximumLikelihoodAmplitudeEstimationResult, alpha: float = 0.05, nevals: int | None = None, ) -> tuple[float, float]: """Compute the likelihood-ratio confidence interval. Args: result: A maximum likelihood amplitude estimation results object. alpha: The level of the confidence interval (< 0.5), defaults to 0.05. nevals: The number of evaluations to find the intersection with the loglikelihood function. Defaults to an adaptive value based on the maximal power of Q. Returns: The alpha-likelihood-ratio confidence interval. """ if nevals is None: nevals = max(10000, int(np.pi / 2 * 1000 * 2 * result.evaluation_schedule[-1])) def loglikelihood(theta, one_counts, all_counts): loglik = 0 for i, k in enumerate(result.evaluation_schedule): loglik += np.log(np.sin((2 * k + 1) * theta) ** 2) * one_counts[i] loglik += np.log(np.cos((2 * k + 1) * theta) ** 2) * (all_counts[i] - one_counts[i]) return loglik one_counts = result.good_counts all_counts = [result.shots] * len(one_counts) eps = 1e-15 # to avoid invalid value in log thetas = np.linspace(0 + eps, np.pi / 2 - eps, nevals) values = np.zeros(len(thetas)) for i, theta in enumerate(thetas): values[i] = loglikelihood(theta, one_counts, all_counts) loglik_mle = loglikelihood(result.theta, one_counts, all_counts) chi2_quantile = chi2.ppf(1 - alpha, df=1) thres = loglik_mle - chi2_quantile / 2 # the (outer) LR confidence interval above_thres = thetas[values >= thres] # it might happen that the `above_thres` array is empty, # to still provide a valid result use safe_min/max which # then yield [0, pi/2] confint = [_safe_min(above_thres, default=0), _safe_max(above_thres, default=np.pi / 2)] mapped_confint = tuple(result.post_processing(np.sin(bound) ** 2) for bound in confint) return mapped_confint def _get_counts( circuit_results: Sequence[np.ndarray | list[float] | dict[str, int]], estimation_problem: EstimationProblem, num_state_qubits: int, ) -> tuple[list[float], list[int]]: """Get the good and total counts. Returns: A pair of two lists, ([1-counts per experiment], [shots per experiment]). Raises: AlgorithmError: If self.run() has not been called yet. """ one_hits = [] # h_k: how often 1 has been measured, for a power Q^(m_k) # shots_k: how often has been measured at a power Q^(m_k) all_hits: np.ndarray | list[float] = [] if all(isinstance(data, (list, np.ndarray)) for data in circuit_results): probabilities = [] num_qubits = int(np.log2(len(circuit_results[0]))) # the total number of qubits for statevector in circuit_results: p_k = 0.0 for i, amplitude in enumerate(statevector): probability = np.abs(amplitude) ** 2 # consider only state qubits and revert bit order bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1] objectives = [bitstr[index] for index in estimation_problem.objective_qubits] if estimation_problem.is_good_state(objectives): p_k += probability probabilities += [p_k] one_hits = probabilities all_hits = np.ones_like(one_hits) else: for counts in circuit_results: all_hits.append(sum(counts.values())) one_hits.append( sum( count for bitstr, count in counts.items() if estimation_problem.is_good_state(bitstr) ) ) return one_hits, all_hits
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Evolution problem class.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import OperatorBase, StateFn from qiskit.utils.deprecation import deprecate_func from ..list_or_dict import ListOrDict class EvolutionProblem: """Deprecated: Evolution problem class. The EvolutionProblem class has been superseded by the :class:`qiskit_algorithms.time_evolvers.TimeEvolutionProblem` class. This class will be deprecated in a future release and subsequently removed after that. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. """ @deprecate_func( additional_msg=( "Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionProblem``. " "See https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def __init__( self, hamiltonian: OperatorBase, time: float, initial_state: StateFn | QuantumCircuit | None = None, aux_operators: ListOrDict[OperatorBase] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, param_value_dict: dict[Parameter, complex] | None = None, ): """ Args: hamiltonian: The Hamiltonian under which to evolve the system. time: Total time of evolution. initial_state: The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators: Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold: Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param: Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_dict: Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. Raises: ValueError: If non-positive time of evolution is provided. """ self.t_param = t_param self.param_value_dict = param_value_dict self.hamiltonian = hamiltonian self.time = time self.initial_state = initial_state self.aux_operators = aux_operators self.truncation_threshold = truncation_threshold @property def time(self) -> float: """Returns time.""" return self._time @time.setter def time(self, time: float) -> None: """ Sets time and validates it. Raises: ValueError: If time is not positive. """ if time <= 0: raise ValueError(f"Evolution time must be > 0 but was {time}.") self._time = time def validate_params(self) -> None: """ Checks if all parameters present in the Hamiltonian are also present in the dictionary that maps them to values. Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ if isinstance(self.hamiltonian, OperatorBase): t_param_set = set() if self.t_param is not None: t_param_set.add(self.t_param) hamiltonian_dict_param_set: set[Parameter] = set() if self.param_value_dict is not None: hamiltonian_dict_param_set = hamiltonian_dict_param_set.union( set(self.param_value_dict.keys()) ) params_set = t_param_set.union(hamiltonian_dict_param_set) hamiltonian_param_set = set(self.hamiltonian.parameters) if hamiltonian_param_set != params_set: raise ValueError( f"Provided parameters {params_set} do not match Hamiltonian parameters " f"{hamiltonian_param_set}." )
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for holding evolution result.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.opflow import StateFn, OperatorBase from qiskit.utils.deprecation import deprecate_func from ..algorithm_result import AlgorithmResult class EvolutionResult(AlgorithmResult): """Deprecated: Class for holding evolution result. The EvolutionResult class has been superseded by the :class:`qiskit_algorithms.time_evolvers.TimeEvolutionResult` class. This class will be deprecated in a future release and subsequently removed after that. """ @deprecate_func( additional_msg=( "Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionResult``. " "See https://qisk.it/algo_migration for a migration guide." ), since="0.24.0", ) def __init__( self, evolved_state: StateFn | QuantumCircuit | OperatorBase, aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, ): """ Args: evolved_state: An evolved quantum state. aux_ops_evaluated: Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). """ self.evolved_state = evolved_state self.aux_ops_evaluated = aux_ops_evaluated
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An algorithm to implement a Trotterization real time-evolution.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit_algorithms.observables_evaluator import estimate_observables from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.circuit.parametertable import ParameterView from qiskit.primitives import BaseEstimator from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.synthesis import ProductFormula, LieTrotter class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ``ProductFormula`` provided. Examples: .. code-block:: python from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit_algorithms.time_evolvers import TrotterQRTE from qiskit.primitives import Estimator operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) # LieTrotter with 1 rep estimator = Estimator() trotter_qrte = TrotterQRTE(estimator=estimator) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ def __init__( self, product_formula: ProductFormula | None = None, estimator: BaseEstimator | None = None, num_timesteps: int = 1, ) -> None: """ Args: product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the Lie-Trotter first order product formula with a single repetition is used. ``reps`` should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps`` is larger than 1, the true number of time-steps will be ``num_timesteps * reps``. num_timesteps: The number of time-steps the full evolution time is devided into (repetitions of ``product_formula``) estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. """ self.product_formula = product_formula self.num_timesteps = num_timesteps self.estimator = estimator @property def product_formula(self) -> ProductFormula: """Returns a product formula.""" return self._product_formula @product_formula.setter def product_formula(self, product_formula: ProductFormula | None): """Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product formula with a single repetition.""" if product_formula is None: product_formula = LieTrotter() self._product_formula = product_formula @property def estimator(self) -> BaseEstimator | None: """ Returns an estimator. """ return self._estimator @estimator.setter def estimator(self, estimator: BaseEstimator) -> None: """ Sets an estimator. """ self._estimator = estimator @property def num_timesteps(self) -> int: """Returns the number of timesteps.""" return self._num_timesteps @num_timesteps.setter def num_timesteps(self, num_timesteps: int) -> None: """ Sets the number of time-steps. Raises: ValueError: If num_timesteps is not positive. """ if num_timesteps <= 0: raise ValueError( f"Number of time steps must be positive integer, {num_timesteps} provided" ) self._num_timesteps = num_timesteps @classmethod def supports_aux_operators(cls) -> bool: """ Whether computing the expectation value of auxiliary operators is supported. Returns: ``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be evaluated, ``False`` otherwise. """ return True def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: """ Evolves a quantum state for a given time using the Trotterization method based on a product formula provided. The result is provided in the form of a quantum circuit. If auxiliary operators are included in the ``evolution_problem``, they are evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps`` times) using an estimator primitive provided. Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, ``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE. Returns: Evolution result that includes an evolved state as a quantum circuit and, optionally, auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` (feature not currently supported). ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator provided to the algorithm. ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "The time evolution problem contained ``aux_operators`` but no estimator was " "provided. The algorithm continues without calculating these quantities. " ) # ensure the hamiltonian is a sparse pauli op hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)): raise ValueError( f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} " "provided." ) if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.primitive * hamiltonian.coeff elif isinstance(hamiltonian, Pauli): hamiltonian = SparsePauliOp(hamiltonian) t_param = evolution_problem.t_param free_parameters = hamiltonian.parameters if t_param is not None and free_parameters != ParameterView([t_param]): raise ValueError( f"Hamiltonian time parameters ({free_parameters}) do not match " f"evolution_problem.t_param ({t_param})." ) # make sure PauliEvolutionGate does not implement more than one Trotter step dt = evolution_problem.time / self.num_timesteps if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state else: raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.") evolved_state = QuantumCircuit(initial_state.num_qubits) evolved_state.append(initial_state, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables = [] observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) else: observables = None if t_param is None: # the evolution gate single_step_evolution_gate = PauliEvolutionGate( hamiltonian, dt, synthesis=self.product_formula ) for n in range(self.num_timesteps): # if hamiltonian is time-dependent, bind new time-value at every step to construct # evolution for next step if t_param is not None: time_value = (n + 1) * dt bound_hamiltonian = hamiltonian.assign_parameters([time_value]) single_step_evolution_gate = PauliEvolutionGate( bound_hamiltonian, dt, synthesis=self.product_formula, ) evolved_state.append(single_step_evolution_gate, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) evaluated_aux_ops = None if evolution_problem.aux_operators is not None: evaluated_aux_ops = observables[-1] return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An implementation of the AdaptVQE algorithm.""" from __future__ import annotations from collections.abc import Sequence from enum import Enum import re import logging from typing import Any import numpy as np from qiskit import QiskitError from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.opflow import OperatorBase, PauliSumOp from qiskit.circuit.library import EvolvedOperatorAnsatz from qiskit.utils.deprecation import deprecate_arg, deprecate_func from qiskit.utils.validation import validate_min from .minimum_eigensolver import MinimumEigensolver from .vqe import VQE, VQEResult from ..observables_evaluator import estimate_observables from ..variational_algorithm import VariationalAlgorithm logger = logging.getLogger(__name__) class TerminationCriterion(Enum): """A class enumerating the various finishing criteria.""" CONVERGED = "Threshold converged" CYCLICITY = "Aborted due to a cyclic selection of evolution operators" MAXIMUM = "Maximum number of iterations reached" class AdaptVQE(VariationalAlgorithm, MinimumEigensolver): """The Adaptive Variational Quantum Eigensolver algorithm. `AdaptVQE <https://arxiv.org/abs/1812.11173>`__ is a quantum algorithm which creates a compact ansatz from a set of evolution operators. It iteratively extends the ansatz circuit, by selecting the building block that leads to the largest gradient from a set of candidates. In chemistry, this is usually a list of orbital excitations. Thus, a common choice of ansatz to be used with this algorithm is the Unitary Coupled Cluster ansatz implemented in Qiskit Nature. This results in a wavefunction ansatz which is uniquely adapted to the operator whose minimum eigenvalue is being determined. This class relies on a supplied instance of :class:`~.VQE` to find the minimum eigenvalue. The performance of AdaptVQE significantly depends on the minimization routine. .. code-block:: python from qiskit_algorithms.minimum_eigensolvers import AdaptVQE, VQE from qiskit_algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit.circuit.library import EvolvedOperatorAnsatz # get your Hamiltonian hamiltonian = ... # construct your ansatz ansatz = EvolvedOperatorAnsatz(...) vqe = VQE(Estimator(), ansatz, SLSQP()) adapt_vqe = AdaptVQE(vqe) eigenvalue, _ = adapt_vqe.compute_minimum_eigenvalue(hamiltonian) The following attributes can be set via the initializer but can also be read and updated once the AdaptVQE object has been constructed. Attributes: solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues. It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type :class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`. gradient_threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from one iteration to the next, the algorithm has converged and terminates. When this case occurs, the excitation included in the final iteration did not result in a significant improvement of the eigenvalue and, thus, the results from this iteration are not considered. max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the algorithm is not bound in its number of iterations. """ @deprecate_arg( "threshold", since="0.24.0", pending=True, new_alias="gradient_threshold", ) def __init__( self, solver: VQE, *, gradient_threshold: float = 1e-5, eigenvalue_threshold: float = 1e-5, max_iterations: int | None = None, threshold: float | None = None, # pylint: disable=unused-argument ) -> None: """ Args: solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues. It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type :class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`. gradient_threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from one iteration to the next, the algorithm has converged and terminates. When this case occurs, the excitation included in the final iteration did not result in a significant improvement of the eigenvalue and, thus, the results from this iteration are not considered. max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the algorithm is not bound in its number of iterations. threshold: once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. Defaults to ``1e-5``. """ validate_min("gradient_threshold", gradient_threshold, 1e-15) validate_min("eigenvalue_threshold", eigenvalue_threshold, 1e-15) self.solver = solver self.gradient_threshold = gradient_threshold self.eigenvalue_threshold = eigenvalue_threshold self.max_iterations = max_iterations self._tmp_ansatz: EvolvedOperatorAnsatz | None = None self._excitation_pool: list[OperatorBase] = [] self._excitation_list: list[OperatorBase] = [] @property @deprecate_func( since="0.24.0", pending=True, is_property=True, additional_msg="Instead, use the gradient_threshold attribute.", ) def threshold(self) -> float: """The threshold for the gradients. Once all gradients have an absolute value smaller than this threshold, the algorithm has converged and terminates. """ return self.gradient_threshold @threshold.setter @deprecate_func( since="0.24.0", pending=True, is_property=True, additional_msg="Instead, use the gradient_threshold attribute.", ) def threshold(self, threshold: float) -> None: self.gradient_threshold = threshold @property def initial_point(self) -> Sequence[float] | None: """Returns the initial point of the internal :class:`~.VQE` solver.""" return self.solver.initial_point @initial_point.setter def initial_point(self, value: Sequence[float] | None) -> None: """Sets the initial point of the internal :class:`~.VQE` solver.""" self.solver.initial_point = value @classmethod def supports_aux_operators(cls) -> bool: return True def _compute_gradients( self, theta: list[float], operator: BaseOperator | OperatorBase, ) -> list[tuple[complex, dict[str, Any]]]: """ Computes the gradients for all available excitation operators. Args: theta: List of (up to now) optimal parameters. operator: operator whose gradient needs to be computed. Returns: List of pairs consisting of the computed gradient and excitation operator. """ # The excitations operators are applied later as exp(i*theta*excitation). # For this commutator, we need to explicitly pull in the imaginary phase. commutators = [1j * (operator @ exc - exc @ operator) for exc in self._excitation_pool] res = estimate_observables(self.solver.estimator, self.solver.ansatz, commutators, theta) return res @staticmethod def _check_cyclicity(indices: list[int]) -> bool: """ Auxiliary function to check for cycles in the indices of the selected excitations. Args: indices: The list of chosen gradient indices. Returns: Whether repeating sequences of indices have been detected. """ cycle_regex = re.compile(r"(\b.+ .+\b)( \b\1\b)+") # reg-ex explanation: # 1. (\b.+ .+\b) will match at least two numbers and try to match as many as possible. The # word boundaries in the beginning and end ensure that now numbers are split into digits. # 2. the match of this part is placed into capture group 1 # 3. ( \b\1\b)+ will match a space followed by the contents of capture group 1 (again # delimited by word boundaries to avoid separation into digits). # -> this results in any sequence of at least two numbers being detected match = cycle_regex.search(" ".join(map(str, indices))) logger.debug("Cycle detected: %s", match) # Additionally we also need to check whether the last two numbers are identical, because the # reg-ex above will only find cycles of at least two consecutive numbers. # It is sufficient to assert that the last two numbers are different due to the iterative # nature of the algorithm. return match is not None or (len(indices) > 1 and indices[-2] == indices[-1]) def compute_minimum_eigenvalue( self, operator: BaseOperator | PauliSumOp, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, ) -> AdaptVQEResult: """Computes the minimum eigenvalue. Args: operator: Operator whose minimum eigenvalue we want to find. aux_operators: Additional auxiliary operators to evaluate. Raises: TypeError: If an ansatz other than :class:`~.EvolvedOperatorAnsatz` is provided. QiskitError: If all evaluated gradients lie below the convergence threshold in the first iteration of the algorithm. Returns: An :class:`~.AdaptVQEResult` which is a :class:`~.VQEResult` but also but also includes runtime information about the AdaptVQE algorithm like the number of iterations, termination criterion, and the final maximum gradient. """ if not isinstance(self.solver.ansatz, EvolvedOperatorAnsatz): raise TypeError("The AdaptVQE ansatz must be of the EvolvedOperatorAnsatz type.") # Overwrite the solver's ansatz with the initial state self._tmp_ansatz = self.solver.ansatz self._excitation_pool = self._tmp_ansatz.operators self.solver.ansatz = self._tmp_ansatz.initial_state prev_op_indices: list[int] = [] prev_raw_vqe_result: VQEResult | None = None raw_vqe_result: VQEResult | None = None theta: list[float] = [] max_grad: tuple[complex, dict[str, Any] | None] = (0.0, None) self._excitation_list = [] history: list[complex] = [] iteration = 0 while self.max_iterations is None or iteration < self.max_iterations: iteration += 1 logger.info("--- Iteration #%s ---", str(iteration)) # compute gradients logger.debug("Computing gradients") cur_grads = self._compute_gradients(theta, operator) # pick maximum gradient max_grad_index, max_grad = max( enumerate(cur_grads), key=lambda item: np.abs(item[1][0]) ) logger.info( "Found maximum gradient %s at index %s", str(np.abs(max_grad[0])), str(max_grad_index), ) # log gradients if np.abs(max_grad[0]) < self.gradient_threshold: if iteration == 1: raise QiskitError( "All gradients have been evaluated to lie below the convergence threshold " "during the first iteration of the algorithm. Try to either tighten the " "convergence threshold or pick a different ansatz." ) logger.info( "AdaptVQE terminated successfully with a final maximum gradient: %s", str(np.abs(max_grad[0])), ) termination_criterion = TerminationCriterion.CONVERGED break # store maximum gradient's index for cycle detection prev_op_indices.append(max_grad_index) # check indices of picked gradients for cycles if self._check_cyclicity(prev_op_indices): logger.info("Alternating sequence found. Finishing.") logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0]))) termination_criterion = TerminationCriterion.CYCLICITY break # add new excitation to self._ansatz logger.info( "Adding new operator to the ansatz: %s", str(self._excitation_pool[max_grad_index]) ) self._excitation_list.append(self._excitation_pool[max_grad_index]) theta.append(0.0) # setting up the ansatz for the VQE iteration self._tmp_ansatz.operators = self._excitation_list self.solver.ansatz = self._tmp_ansatz self.solver.initial_point = theta # evaluating the eigenvalue with the internal VQE prev_raw_vqe_result = raw_vqe_result raw_vqe_result = self.solver.compute_minimum_eigenvalue(operator) theta = raw_vqe_result.optimal_point.tolist() # checking convergence based on the change in eigenvalue if iteration > 1: eigenvalue_diff = np.abs(raw_vqe_result.eigenvalue - history[-1]) if eigenvalue_diff < self.eigenvalue_threshold: logger.info( "AdaptVQE terminated successfully with a final change in eigenvalue: %s", str(eigenvalue_diff), ) termination_criterion = TerminationCriterion.CONVERGED logger.debug( "Reverting the addition of the last excitation to the ansatz since it " "resulted in a change of the eigenvalue below the configured threshold." ) self._excitation_list.pop() theta.pop() self._tmp_ansatz.operators = self._excitation_list self.solver.ansatz = self._tmp_ansatz self.solver.initial_point = theta raw_vqe_result = prev_raw_vqe_result break # appending the computed eigenvalue to the tracking history history.append(raw_vqe_result.eigenvalue) logger.info("Current eigenvalue: %s", str(raw_vqe_result.eigenvalue)) else: # reached maximum number of iterations termination_criterion = TerminationCriterion.MAXIMUM logger.info("Maximum number of iterations reached. Finishing.") logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0]))) result = AdaptVQEResult() result.combine(raw_vqe_result) result.num_iterations = iteration result.final_max_gradient = max_grad[0] result.termination_criterion = termination_criterion result.eigenvalue_history = history # once finished evaluate auxiliary operators if any if aux_operators is not None: aux_values = estimate_observables( self.solver.estimator, self.solver.ansatz, aux_operators, result.optimal_point ) result.aux_operators_evaluated = aux_values logger.info("The final eigenvalue is: %s", str(result.eigenvalue)) self.solver.ansatz.operators = self._excitation_pool return result class AdaptVQEResult(VQEResult): """AdaptVQE Result.""" def __init__(self) -> None: super().__init__() self._num_iterations: int | None = None self._final_max_gradient: float | None = None self._termination_criterion: str = "" self._eigenvalue_history: list[float] | None = None @property def num_iterations(self) -> int: """Returns the number of iterations.""" return self._num_iterations @num_iterations.setter def num_iterations(self, value: int) -> None: """Sets the number of iterations.""" self._num_iterations = value @property def final_max_gradient(self) -> float: """Returns the final maximum gradient.""" return self._final_max_gradient @final_max_gradient.setter def final_max_gradient(self, value: float) -> None: """Sets the final maximum gradient.""" self._final_max_gradient = value @property def termination_criterion(self) -> str: """Returns the termination criterion.""" return self._termination_criterion @termination_criterion.setter def termination_criterion(self, value: str) -> None: """Sets the termination criterion.""" self._termination_criterion = value @property def eigenvalue_history(self) -> list[float]: """Returns the history of computed eigenvalues. The history's length matches the number of iterations and includes the final computed value. """ return self._eigenvalue_history @eigenvalue_history.setter def eigenvalue_history(self, eigenvalue_history: list[float]) -> None: """Sets the history of computed eigenvalues.""" self._eigenvalue_history = eigenvalue_history
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Univariate Marginal Distribution Algorithm (Estimation-of-Distribution-Algorithm).""" from __future__ import annotations from collections.abc import Callable from typing import Any import numpy as np from scipy.stats import norm from qiskit.utils import algorithm_globals from .optimizer import OptimizerResult, POINT from .scipy_optimizer import Optimizer, OptimizerSupportLevel class UMDA(Optimizer): """Continuous Univariate Marginal Distribution Algorithm (UMDA). UMDA [1] is a specific type of Estimation of Distribution Algorithm (EDA) where new individuals are sampled from univariate normal distributions and are updated in each iteration of the algorithm by the best individuals found in the previous iteration. .. seealso:: This original implementation of the UDMA optimizer for Qiskit was inspired by my (Vicente P. Soloviev) work on the EDAspy Python package [2]. EDAs are stochastic search algorithms and belong to the family of the evolutionary algorithms. The main difference is that EDAs have a probabilistic model which is updated in each iteration from the best individuals of previous generations (elite selection). Depending on the complexity of the probabilistic model, EDAs can be classified in different ways. In this case, UMDA is a univariate EDA as the embedded probabilistic model is univariate. UMDA has been compared to some of the already implemented algorithms in Qiskit library to optimize the parameters of variational algorithms such as QAOA or VQE and competitive results have been obtained [1]. UMDA seems to provide very good solutions for those circuits in which the number of layers is not big. The optimization process can be personalized depending on the paremeters chosen in the initialization. The main parameter is the population size. The bigger it is, the final result will be better. However, this increases the complexity of the algorithm and the runtime will be much heavier. In the work [1] different experiments have been performed where population size has been set to 20 - 30. .. note:: The UMDA implementation has more parameters but these have default values for the initialization for better understanding of the user. For example, ``\alpha`` parameter has been set to 0.5 and is the percentage of the population which is selected in each iteration to update the probabilistic model. Example: This short example runs UMDA to optimize the parameters of a variational algorithm. Here we will use the same operator as used in the algorithms introduction, which was originally computed by Qiskit Nature for an H2 molecule. The minimum energy of the H2 Hamiltonian can be found quite easily so we are able to set maxiters to a small value. .. code-block:: python from qiskit.opflow import X, Z, I from qiskit import Aer from qiskit_algorithms.optimizers import UMDA from qiskit_algorithms import QAOA from qiskit.utils import QuantumInstance H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) p = 2 # Toy example: 2 layers with 2 parameters in each layer: 4 variables opt = UMDA(maxiter=100, size_gen=20) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=H2_op) If it is desired to modify the percentage of individuals considered to update the probabilistic model, then this code can be used. Here for example we set the 60% instead of the 50% predefined. .. code-block:: python opt = UMDA(maxiter=100, size_gen=20, alpha = 0.6) backend = Aer.get_backend('statevector_simulator') vqe = QAOA(opt, quantum_instance=QuantumInstance(backend=backend), reps=p) result = vqe.compute_minimum_eigenvalue(operator=qubit_op) References: [1]: Vicente P. Soloviev, Pedro Larrañaga and Concha Bielza (2022, July). Quantum Parametric Circuit Optimization with Estimation of Distribution Algorithms. In 2022 The Genetic and Evolutionary Computation Conference (GECCO). DOI: https://doi.org/10.1145/3520304.3533963 [2]: Vicente P. Soloviev. Python package EDAspy. https://github.com/VicentePerezSoloviev/EDAspy. """ ELITE_FACTOR = 0.4 STD_BOUND = 0.3 def __init__( self, maxiter: int = 100, size_gen: int = 20, alpha: float = 0.5, callback: Callable[[int, np.array, float], None] | None = None, ) -> None: r""" Args: maxiter: Maximum number of iterations. size_gen: Population size of each generation. alpha: Percentage (0, 1] of the population to be selected as elite selection. callback: A callback function passed information in each iteration step. The information is, in this order: the number of function evaluations, the parameters, the best function value in this iteration. """ self.size_gen = size_gen self.maxiter = maxiter self.alpha = alpha self._vector: np.ndarray | None = None # initialization of generation self._generation: np.ndarray | None = None self._dead_iter = int(self._maxiter / 5) self._truncation_length = int(size_gen * alpha) super().__init__() self._best_cost_global: float | None = None self._best_ind_global: int | None = None self._evaluations: np.ndarray | None = None self._n_variables: int | None = None self.callback = callback def _initialization(self) -> np.ndarray: vector = np.zeros((4, self._n_variables)) vector[0, :] = np.pi # mu vector[1, :] = 0.5 # std return vector # build a generation of size SIZE_GEN from prob vector def _new_generation(self): """Build a new generation sampled from the vector of probabilities. Updates the generation pandas dataframe """ gen = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) self._generation = self._generation[: int(self.ELITE_FACTOR * len(self._generation))] self._generation = np.vstack((self._generation, gen)) # truncate the generation at alpha percent def _truncation(self): """Selection of the best individuals of the actual generation. Updates the generation by selecting the best individuals. """ best_indices = self._evaluations.argsort()[: self._truncation_length] self._generation = self._generation[best_indices, :] self._evaluations = np.take(self._evaluations, best_indices) # check each individual of the generation def _check_generation(self, objective_function): """Check the cost of each individual in the cost function implemented by the user.""" self._evaluations = np.apply_along_axis(objective_function, 1, self._generation) # update the probability vector def _update_vector(self): """From the best individuals update the vector of normal distributions in order to the next generation can sample from it. Update the vector of normal distributions """ for i in range(self._n_variables): self._vector[0, i], self._vector[1, i] = norm.fit(self._generation[:, i]) if self._vector[1, i] < self.STD_BOUND: self._vector[1, i] = self.STD_BOUND def minimize( self, fun: Callable[[POINT], float], x0: POINT, jac: Callable[[POINT], POINT] | None = None, bounds: list[tuple[float, float]] | None = None, ) -> OptimizerResult: not_better_count = 0 result = OptimizerResult() if isinstance(x0, float): x0 = [x0] self._n_variables = len(x0) self._best_cost_global = 999999999999 self._best_ind_global = 9999999 history = [] self._evaluations = np.array(0) self._vector = self._initialization() # initialization of generation self._generation = algorithm_globals.random.normal( self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables] ) for _ in range(self._maxiter): self._check_generation(fun) self._truncation() self._update_vector() best_mae_local: float = min(self._evaluations) history.append(best_mae_local) best_ind_local = np.where(self._evaluations == best_mae_local)[0][0] best_ind_local = self._generation[best_ind_local] # update the best values ever if best_mae_local < self._best_cost_global: self._best_cost_global = best_mae_local self._best_ind_global = best_ind_local not_better_count = 0 else: not_better_count += 1 if not_better_count >= self._dead_iter: break if self.callback is not None: self.callback( len(history) * self._size_gen, self._best_ind_global, self._best_cost_global ) self._new_generation() result.x = self._best_ind_global result.fun = self._best_cost_global result.nfev = len(history) * self._size_gen return result @property def size_gen(self) -> int: """Returns the size of the generations (number of individuals per generation)""" return self._size_gen @size_gen.setter def size_gen(self, value: int): """ Sets the size of the generations of the algorithm. Args: value: Size of the generations (number of individuals per generation). Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The size of the generation should be greater than 0.") self._size_gen = value @property def maxiter(self) -> int: """Returns the maximum number of iterations""" return self._maxiter @maxiter.setter def maxiter(self, value: int): """ Sets the maximum number of iterations of the algorithm. Args: value: Maximum number of iterations of the algorithm. Raises: ValueError: If `value` is lower than 1. """ if value <= 0: raise ValueError("The maximum number of iterations should be greater than 0.") self._maxiter = value @property def alpha(self) -> float: """Returns the alpha parameter value (percentage of population selected to update probabilistic model)""" return self._alpha @alpha.setter def alpha(self, value: float): """ Sets the alpha parameter (percentage of individuals selected to update the probabilistic model) Args: value: Percentage (0,1] of generation selected to update the probabilistic model. Raises: ValueError: If `value` is lower than 0 or greater than 1. """ if (value <= 0) or (value > 1): raise ValueError(f"alpha must be in the range (0, 1], value given was {value}") self._alpha = value @property def settings(self) -> dict[str, Any]: return { "maxiter": self.maxiter, "alpha": self.alpha, "size_gen": self.size_gen, "callback": self.callback, } def get_support_level(self): """Get the support level dictionary.""" return { "gradient": OptimizerSupportLevel.ignored, "bounds": OptimizerSupportLevel.ignored, "initial_point": OptimizerSupportLevel.required, }
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Phase estimation for the spectrum of a Hamiltonian""" from __future__ import annotations import warnings from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg from qiskit.opflow import ( SummedOp, PauliOp, MatrixOp, PauliSumOp, StateFn, EvolutionBase, PauliTrotterEvolution, I, ) from qiskit.providers import Backend from .phase_estimation import PhaseEstimation from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult from .phase_estimation_scale import PhaseEstimationScale from ...circuit.library import PauliEvolutionGate from ...primitives import BaseSampler from ...quantum_info import SparsePauliOp, Statevector, Pauli from ...synthesis import EvolutionSynthesis class HamiltonianPhaseEstimation: r"""Run the Quantum Phase Estimation algorithm to find the eigenvalues of a Hermitian operator. This class is nearly the same as :class:`~qiskit_algorithms.PhaseEstimation`, differing only in that the input in that class is a unitary operator, whereas here the input is a Hermitian operator from which a unitary will be obtained by scaling and exponentiating. The scaling is performed in order to prevent the phases from wrapping around :math:`2\pi`. The problem of estimating eigenvalues :math:`\lambda_j` of the Hermitian operator :math:`H` is solved by running a circuit representing .. math:: \exp(i b H) |\psi\rangle = \sum_j \exp(i b \lambda_j) c_j |\lambda_j\rangle, where the input state is .. math:: |\psi\rangle = \sum_j c_j |\lambda_j\rangle, and :math:`\lambda_j` are the eigenvalues of :math:`H`. Here, :math:`b` is a scaling factor sufficiently large to map positive :math:`\lambda` to :math:`[0,\pi)` and negative :math:`\lambda` to :math:`[\pi,2\pi)`. Each time the circuit is run, one measures a phase corresponding to :math:`lambda_j` with probability :math:`|c_j|^2`. If :math:`H` is a Pauli sum, the bound :math:`b` is computed from the sum of the absolute values of the coefficients of the terms. There is no way to reliably recover eigenvalues from phases very near the endpoints of these intervals. Because of this you should be aware that for degenerate cases, such as :math:`H=Z`, the eigenvalues :math:`\pm 1` will be mapped to the same phase, :math:`\pi`, and so cannot be distinguished. In this case, you need to specify a larger bound as an argument to the method ``estimate``. This class uses and works together with :class:`~qiskit_algorithms.PhaseEstimationScale` to manage scaling the Hamiltonian and the phases that are obtained by the QPE algorithm. This includes setting, or computing, a bound on the eigenvalues of the operator, using this bound to obtain a scale factor, scaling the operator, and shifting and scaling the measured phases to recover the eigenvalues. Note that, although we speak of "evolving" the state according the Hamiltonian, in the present algorithm, we are not actually considering time evolution. Rather, the role of time is played by the scaling factor, which is chosen to best extract the eigenvalues of the Hamiltonian. A few of the ideas in the algorithm may be found in Ref. [1]. **Reference:** [1]: Quantum phase estimation of multiple eigenvalues for small-scale (noisy) experiments T.E. O'Brien, B. Tarasinski, B.M. Terhal `arXiv:1809.09697 <https://arxiv.org/abs/1809.09697>`_ """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, num_evaluation_qubits: int, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will be estimated as a binary string with this many bits. quantum_instance: Deprecated: The quantum instance on which the circuit will be run. sampler: The sampler primitive on which the circuit will be sampled. """ # Avoid double warning on deprecated used of `quantum_instance`. with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self._phase_estimation = PhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance, sampler=sampler, ) def _get_scale(self, hamiltonian, bound=None) -> PhaseEstimationScale: if bound is None: return PhaseEstimationScale.from_pauli_sum(hamiltonian) return PhaseEstimationScale(bound) def _get_unitary( self, hamiltonian, pe_scale, evolution: EvolutionSynthesis | EvolutionBase ) -> QuantumCircuit: """Evolve the Hamiltonian to obtain a unitary. Apply the scaling to the Hamiltonian that has been computed from an eigenvalue bound and compute the unitary by applying the evolution object. """ if self._phase_estimation._sampler is not None: evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution) unitary = QuantumCircuit(evo.num_qubits) unitary.append(evo, unitary.qubits) return unitary.decompose().decompose() else: # scale so that phase does not wrap. scaled_hamiltonian = -pe_scale.scale * hamiltonian unitary = evolution.convert(scaled_hamiltonian.exp_i()) if not isinstance(unitary, QuantumCircuit): unitary = unitary.to_circuit() return unitary.decompose().decompose() # Decomposing twice allows some 1Q Hamiltonians to give correct results # when using MatrixEvolution(), that otherwise would give incorrect results. # It does not break any others that we tested. def estimate( self, hamiltonian: PauliOp | MatrixOp | SummedOp | Pauli | SparsePauliOp | PauliSumOp, state_preparation: StateFn | QuantumCircuit | Statevector | None = None, evolution: EvolutionSynthesis | EvolutionBase | None = None, bound: float | None = None, ) -> HamiltonianPhaseEstimationResult: """Run the Hamiltonian phase estimation algorithm. Args: hamiltonian: A Hermitian operator. If the algorithm is used with a ``Sampler`` primitive, the allowed types are ``Pauli``, ``SparsePauliOp``, and ``PauliSumOp``. If the algorithm is used with a ``QuantumInstance``, ``PauliOp, ``MatrixOp``, ``PauliSumOp``, and ``SummedOp`` types are allowed. state_preparation: The ``StateFn`` to be prepared, whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. evolution: An evolution converter that generates a unitary from ``hamiltonian``. If ``None``, then the default ``PauliTrotterEvolution`` is used. bound: An upper bound on the absolute value of the eigenvalues of ``hamiltonian``. If omitted, then ``hamiltonian`` must be a Pauli sum, or a ``PauliOp``, in which case a bound will be computed. If ``hamiltonian`` is a ``MatrixOp``, then ``bound`` may not be ``None``. The tighter the bound, the higher the resolution of computed phases. Returns: ``HamiltonianPhaseEstimationResult`` instance containing the result of the estimation and diagnostic information. Raises: TypeError: If ``evolution`` is not of type ``EvolutionSynthesis`` when a ``Sampler`` is provided. TypeError: If ``hamiltonian`` type is not ``Pauli`` or ``SparsePauliOp`` or ``PauliSumOp`` when a ``Sampler`` is provided. ValueError: If ``bound`` is ``None`` and ``hamiltonian`` is not a Pauli sum, i.e. a ``PauliSumOp`` or a ``SummedOp`` whose terms are of type ``PauliOp``. TypeError: If ``evolution`` is not of type ``EvolutionBase`` when no ``Sampler`` is provided. """ if self._phase_estimation._sampler is not None: if evolution is not None and not isinstance(evolution, EvolutionSynthesis): raise TypeError(f"Expecting type EvolutionSynthesis, got {type(evolution)}") if not isinstance(hamiltonian, (Pauli, SparsePauliOp, PauliSumOp)): raise TypeError( f"Expecting Hamiltonian type Pauli, SparsePauliOp or PauliSumOp, " f"got {type(hamiltonian)}." ) if isinstance(state_preparation, Statevector): circuit = QuantumCircuit(state_preparation.num_qubits) circuit.prepare_state(state_preparation.data) state_preparation = circuit if isinstance(hamiltonian, PauliSumOp): id_coefficient, hamiltonian_no_id = _remove_identity_pauli_sum_op(hamiltonian) else: id_coefficient = 0.0 hamiltonian_no_id = hamiltonian pe_scale = self._get_scale(hamiltonian_no_id, bound) unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution) else: if evolution is None: evolution = PauliTrotterEvolution() elif not isinstance(evolution, EvolutionBase): raise TypeError(f"Expecting type EvolutionBase, got {type(evolution)}") if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.to_pauli_op() elif isinstance(hamiltonian, PauliOp): hamiltonian = SummedOp([hamiltonian]) if isinstance(hamiltonian, SummedOp): # remove identitiy terms # The term prop to the identity is removed from hamiltonian. # This is done for three reasons: # 1. Work around an unknown bug that otherwise causes the energies to be wrong in some # cases. # 2. Allow working with a simpler Hamiltonian, one with fewer terms. # 3. Tighten the bound on the eigenvalues so that the spectrum is better resolved, i.e. # occupies more of the range of values representable by the qubit register. # The coefficient of this term will be added to the eigenvalues. id_coefficient, hamiltonian_no_id = _remove_identity(hamiltonian) # get the rescaling object pe_scale = self._get_scale(hamiltonian_no_id, bound) # get the unitary unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution) elif isinstance(hamiltonian, MatrixOp): if bound is None: raise ValueError("bound must be specified if Hermitian operator is MatrixOp") # Do not subtract an identity term from the matrix, so do not compensate. id_coefficient = 0.0 pe_scale = self._get_scale(hamiltonian, bound) unitary = self._get_unitary(hamiltonian, pe_scale, evolution) else: raise TypeError(f"Hermitian operator of type {type(hamiltonian)} not supported.") if state_preparation is not None and isinstance(state_preparation, StateFn): state_preparation = state_preparation.to_circuit_op().to_circuit() # run phase estimation phase_estimation_result = self._phase_estimation.estimate( unitary=unitary, state_preparation=state_preparation ) return HamiltonianPhaseEstimationResult( phase_estimation_result=phase_estimation_result, id_coefficient=id_coefficient, phase_estimation_scale=pe_scale, ) def _remove_identity(pauli_sum: SummedOp): """Remove any identity operators from `pauli_sum`. Return the sum of the coefficients of the identities and the new operator. """ idcoeff = 0.0 ops = [] for op in pauli_sum: p = op.primitive if p.x.any() or p.z.any(): ops.append(op) else: idcoeff += op.coeff return idcoeff, SummedOp(ops) def _remove_identity_pauli_sum_op(pauli_sum: PauliSumOp | SparsePauliOp): """Remove any identity operators from ``pauli_sum``. Return the sum of the coefficients of the identities and the new operator. """ def _get_identity(size): identity = I for _ in range(size - 1): identity = identity ^ I return identity idcoeff = 0.0 if isinstance(pauli_sum, PauliSumOp): for operator in pauli_sum: if operator.primitive.paulis == ["I" * pauli_sum.num_qubits]: idcoeff += operator.primitive.coeffs[0] pauli_sum = pauli_sum - operator.primitive.coeffs[0] * _get_identity( pauli_sum.num_qubits ) return idcoeff, pauli_sum.reduce()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The Iterative Quantum Phase Estimation Algorithm.""" from __future__ import annotations import numpy import qiskit from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister from qiskit.providers import Backend from qiskit.utils import QuantumInstance from qiskit.utils.deprecation import deprecate_arg from qiskit_algorithms.exceptions import AlgorithmError from .phase_estimator import PhaseEstimator from .phase_estimator import PhaseEstimatorResult from ...primitives import BaseSampler class IterativePhaseEstimation(PhaseEstimator): """Run the Iterative quantum phase estimation (QPE) algorithm. Given a unitary circuit and a circuit preparing an eigenstate, return the phase of the eigenvalue as a number in :math:`[0,1)` using the iterative phase estimation algorithm. [1]: Dobsicek et al. (2006), Arbitrary accuracy iterative phase estimation algorithm as a two qubit benchmark, `arxiv/quant-ph/0610214 <https://arxiv.org/abs/quant-ph/0610214>`_ """ @deprecate_arg( "quantum_instance", additional_msg=( "Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a " "migration guide." ), since="0.24.0", ) def __init__( self, num_iterations: int, quantum_instance: QuantumInstance | Backend | None = None, sampler: BaseSampler | None = None, ) -> None: r""" Args: num_iterations: The number of iterations (rounds) of the phase estimation to run. quantum_instance: Deprecated: The quantum instance on which the circuit will be run. sampler: The sampler primitive on which the circuit will be sampled. Raises: ValueError: if num_iterations is not greater than zero. AlgorithmError: If neither sampler nor quantum instance is provided. """ if sampler is None and quantum_instance is None: raise AlgorithmError( "Neither a sampler nor a quantum instance was provided. Please provide one of them." ) if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance if num_iterations <= 0: raise ValueError("`num_iterations` must be greater than zero.") self._num_iterations = num_iterations self._sampler = sampler def construct_circuit( self, unitary: QuantumCircuit, state_preparation: QuantumCircuit, k: int, omega: float = 0.0, measurement: bool = False, ) -> QuantumCircuit: """Construct the kth iteration Quantum Phase Estimation circuit. For details of parameters, see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf. Args: unitary: The circuit representing the unitary operator whose eigenvalue (via phase) will be measured. state_preparation: The circuit that prepares the state whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. k: the iteration idx. omega: the feedback angle. measurement: Boolean flag to indicate if measurement should be included in the circuit. Returns: QuantumCircuit: the quantum circuit per iteration """ k = self._num_iterations if k is None else k # The auxiliary (phase measurement) qubit phase_register = QuantumRegister(1, name="a") eigenstate_register = QuantumRegister(unitary.num_qubits, name="q") qc = QuantumCircuit(eigenstate_register) qc.add_register(phase_register) if isinstance(state_preparation, QuantumCircuit): qc.append(state_preparation, eigenstate_register) elif state_preparation is not None: qc += state_preparation.construct_circuit("circuit", eigenstate_register) # hadamard on phase_register[0] qc.h(phase_register[0]) # controlled-U # TODO: We may want to allow flexibility in how the power is computed # For example, it may be desirable to compute the power via Trotterization, if # we are doing Trotterization anyway. unitary_power = unitary.power(2 ** (k - 1)).control() qc = qc.compose(unitary_power, [unitary.num_qubits] + list(range(0, unitary.num_qubits))) qc.p(omega, phase_register[0]) # hadamard on phase_register[0] qc.h(phase_register[0]) if measurement: c = ClassicalRegister(1, name="c") qc.add_register(c) qc.measure(phase_register, c) return qc def _estimate_phase_iteratively(self, unitary, state_preparation): """ Main loop of iterative phase estimation. """ omega_coef = 0 # k runs from the number of iterations back to 1 for k in range(self._num_iterations, 0, -1): omega_coef /= 2 if self._sampler is not None: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True ) try: sampler_job = self._sampler.run([qc]) result = sampler_job.result().quasi_dists[0] except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc x = 1 if result.get(1, 0) > result.get(0, 0) else 0 elif self._quantum_instance.is_statevector: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=False ) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) ancilla_density_mat = qiskit.quantum_info.partial_trace( complete_state_vec, range(unitary.num_qubits) ) ancilla_density_mat_diag = numpy.diag(ancilla_density_mat) max_amplitude = max( ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs ) x = numpy.where(ancilla_density_mat_diag == max_amplitude)[0][0] else: qc = self.construct_circuit( unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=True ) measurements = self._quantum_instance.execute(qc).get_counts(qc) x = 1 if measurements.get("1", 0) > measurements.get("0", 0) else 0 omega_coef = omega_coef + x / 2 return omega_coef # pylint: disable=signature-differs def estimate( self, unitary: QuantumCircuit, state_preparation: QuantumCircuit ) -> "IterativePhaseEstimationResult": """ Estimate the eigenphase of the input unitary and initial-state pair. Args: unitary: The circuit representing the unitary operator whose eigenvalue (via phase) will be measured. state_preparation: The circuit that prepares the state whose eigenphase will be measured. If this parameter is omitted, no preparation circuit will be run and input state will be the all-zero state in the computational basis. Returns: Estimated phase in an IterativePhaseEstimationResult object. Raises: AlgorithmError: If neither sampler nor quantum instance is provided. """ phase = self._estimate_phase_iteratively(unitary, state_preparation) return IterativePhaseEstimationResult(self._num_iterations, phase) class IterativePhaseEstimationResult(PhaseEstimatorResult): """Phase Estimation Result.""" def __init__(self, num_iterations: int, phase: float) -> None: """ Args: num_iterations: number of iterations used in the phase estimation. phase: the estimated phase. """ self._num_iterations = num_iterations self._phase = phase @property def phase(self) -> float: r"""Return the estimated phase as a number in :math:`[0.0, 1.0)`. 1.0 corresponds to a phase of :math:`2\pi`. It is assumed that the input vector is an eigenvector of the unitary so that the peak of the probability density occurs at the bit string that most closely approximates the true phase. """ return self._phase @property def num_iterations(self) -> int: r"""Return the number of iterations used in the estimation algorithm.""" return self._num_iterations
https://github.com/ElePT/qiskit-algorithms-test
ElePT
from qiskit import QuantumCircuit, Aer, execute from math import pi, sin from qiskit.compiler import transpile, assemble from grover_operator import GroverOperator def qft(n): # returns circuit for inverse quantum fourier transformation for given n circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n // 2): circuit.swap(qubit, n - qubit - 1) return circuit def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi / 2 ** (n - qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit class PhaseEstimation: def get_control_gft(self, label="QFT †"): qft_dagger = self.qft_circuit.to_gate().inverse() qft_dagger.label = label return qft_dagger def get_main_circuit(self): qc = QuantumCircuit(self.c_bits + self.s_bits, self.c_bits) # Circuit with n+t qubits and t classical bits # Initialize all qubits to |+> qc.h(range(self.c_bits + self.n_bits)) qc.h(self.c_bits + self.s_bits - 1) qc.z(self.c_bits + self.s_bits - 1) # Begin controlled Grover iterations iterations = 1 for qubit in range(self.c_bits): for i in range(iterations): qc.append(self.c_grover, [qubit] + [*range(self.c_bits, self.s_bits + self.c_bits)]) iterations *= 2 # Do inverse QFT on counting qubits qc.append(self.c_qft, range(self.c_bits)) # Measure counting qubits qc.measure(range(self.c_bits), range(self.c_bits)) return qc def simulate(self): aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(self.main_circuit, aer_sim) qobj = assemble(transpiled_qc) job = aer_sim.run(qobj) hist = job.result().get_counts() # plot_histogram(hist) measured_int = int(max(hist, key=hist.get), 2) theta = (measured_int / (2 ** self.c_bits)) * pi * 2 N = 2 ** self.n_bits M = N * (sin(theta / 2) ** 2) # print(N - M, round(N - M)) return round(N - M) def __init__(self, grover: GroverOperator, c_bits=5): self.c_grover = grover.get_control_circuit() self.c_bits = c_bits self.n_bits = grover.n_bits self.s_bits = grover.total_bits self.qft_circuit = qft(c_bits) self.c_qft = self.get_control_gft() self.main_circuit = self.get_main_circuit() self.M = self.simulate()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Base state fidelity interface """ from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence, Mapping import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from ..algorithm_job import AlgorithmJob from .state_fidelity_result import StateFidelityResult class BaseStateFidelity(ABC): r""" An interface to calculate state fidelities (state overlaps) for pairs of (parametrized) quantum circuits. The calculation depends on the particular fidelity method implementation, but can be always defined as the state overlap: .. math:: |\langle\psi(x)|\phi(y)\rangle|^2 where :math:`x` and :math:`y` are optional parametrizations of the states :math:`\psi` and :math:`\phi` prepared by the circuits ``circuit_1`` and ``circuit_2``, respectively. """ def __init__(self) -> None: # use cache for preventing unnecessary circuit compositions self._circuit_cache: Mapping[tuple[int, int], QuantumCircuit] = {} @staticmethod def _preprocess_values( circuits: QuantumCircuit | Sequence[QuantumCircuit], values: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> Sequence[Sequence[float]]: """ Checks whether the passed values match the shape of the parameters of the corresponding circuits and formats values to 2D list. Args: circuits: List of circuits to be checked. values: Parameter values corresponding to the circuits to be checked. Returns: A 2D value list if the values match the circuits, or an empty 2D list if values is None. Raises: ValueError: if the number of parameter values doesn't match the number of circuit parameters TypeError: if the input values are not a sequence. """ if isinstance(circuits, QuantumCircuit): circuits = [circuits] if values is None: for circuit in circuits: if circuit.num_parameters != 0: raise ValueError( f"`values` cannot be `None` because circuit <{circuit.name}> has " f"{circuit.num_parameters} free parameters." ) return [[]] else: # Support ndarray if isinstance(values, np.ndarray): values = values.tolist() if len(values) > 0 and isinstance(values[0], np.ndarray): values = [v.tolist() for v in values] if not isinstance(values, Sequence): raise TypeError( f"Expected a sequence of numerical parameter values, " f"but got input type {type(values)} instead." ) # ensure 2d if len(values) > 0 and not isinstance(values[0], Sequence) or len(values) == 0: values = [values] return values def _check_qubits_match(self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit) -> None: """ Checks that the number of qubits of 2 circuits matches. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Raises: ValueError: when ``circuit_1`` and ``circuit_2`` don't have the same number of qubits. """ if circuit_1.num_qubits != circuit_2.num_qubits: raise ValueError( f"The number of qubits for the first circuit ({circuit_1.num_qubits}) " f"and second circuit ({circuit_2.num_qubits}) are not the same." ) @abstractmethod def create_fidelity_circuit( self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit ) -> QuantumCircuit: """ Implementation-dependent method to create a fidelity circuit from 2 circuit inputs. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Returns: The fidelity quantum circuit corresponding to ``circuit_1`` and ``circuit_2``. """ raise NotImplementedError def _construct_circuits( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], ) -> Sequence[QuantumCircuit]: """ Constructs the list of fidelity circuits to be evaluated. These circuits represent the state overlap between pairs of input circuits, and their construction depends on the fidelity method implementations. Args: circuits_1: (Parametrized) quantum circuits. circuits_2: (Parametrized) quantum circuits. Returns: List of constructed fidelity circuits. Raises: ValueError: if the length of the input circuit lists doesn't match. """ if isinstance(circuits_1, QuantumCircuit): circuits_1 = [circuits_1] if isinstance(circuits_2, QuantumCircuit): circuits_2 = [circuits_2] if len(circuits_1) != len(circuits_2): raise ValueError( f"The length of the first circuit list({len(circuits_1)}) " f"and second circuit list ({len(circuits_2)}) is not the same." ) circuits = [] for (circuit_1, circuit_2) in zip(circuits_1, circuits_2): # TODO: improve caching, what if the circuit is modified without changing the id? circuit = self._circuit_cache.get((id(circuit_1), id(circuit_2))) if circuit is not None: circuits.append(circuit) else: self._check_qubits_match(circuit_1, circuit_2) # re-parametrize input circuits # TODO: make smarter checks to avoid unnecesary reparametrizations parameters_1 = ParameterVector("x", circuit_1.num_parameters) parametrized_circuit_1 = circuit_1.assign_parameters(parameters_1) parameters_2 = ParameterVector("y", circuit_2.num_parameters) parametrized_circuit_2 = circuit_2.assign_parameters(parameters_2) circuit = self.create_fidelity_circuit( parametrized_circuit_1, parametrized_circuit_2 ) circuits.append(circuit) # update cache self._circuit_cache[id(circuit_1), id(circuit_2)] = circuit return circuits def _construct_value_list( self, circuits_1: Sequence[QuantumCircuit], circuits_2: Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, ) -> list[float]: """ Preprocesses input parameter values to match the fidelity circuit parametrization, and return in list format. Args: circuits_1: (Parametrized) quantum circuits preparing the first list of quantum states. circuits_2: (Parametrized) quantum circuits preparing the second list of quantum states. values_1: Numerical parameters to be bound to the first circuits. values_2: Numerical parameters to be bound to the second circuits. Returns: List of parameter values for fidelity circuit. """ values_1 = self._preprocess_values(circuits_1, values_1) values_2 = self._preprocess_values(circuits_2, values_2) values = [] if len(values_2[0]) == 0: values = list(values_1) elif len(values_1[0]) == 0: values = list(values_2) else: for (val_1, val_2) in zip(values_1, values_2): values.append(val_1 + val_2) return values @abstractmethod def _run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> StateFidelityResult: r""" Computes the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: The result of the fidelity calculation. """ raise NotImplementedError def run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> AlgorithmJob: r""" Runs asynchronously the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second). This calculation depends on the particular fidelity method implementation. Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first set of circuits. values_2: Numerical parameters to be bound to the second set of circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is\: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: Primitive job for the fidelity calculation. The job's result is an instance of ``StateFidelityResult``. """ job = AlgorithmJob(self._run, circuits_1, circuits_2, values_1, values_2, **options) job.submit() return job def _truncate_fidelities(self, fidelities: Sequence[float]) -> Sequence[float]: """ Ensures fidelity result in [0,1]. Args: fidelities: Sequence of raw fidelity results. Returns: List of truncated fidelities. """ return np.clip(fidelities, 0, 1).tolist()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Compute-uncompute fidelity interface using primitives """ from __future__ import annotations from collections.abc import Sequence from copy import copy from qiskit import QuantumCircuit from qiskit.primitives import BaseSampler from qiskit.providers import Options from ..exceptions import AlgorithmError from .base_state_fidelity import BaseStateFidelity from .state_fidelity_result import StateFidelityResult class ComputeUncompute(BaseStateFidelity): r""" This class leverages the sampler primitive to calculate the state fidelity of two quantum circuits following the compute-uncompute method (see [1] for further reference). The fidelity can be defined as the state overlap. .. math:: |\langle\psi(x)|\phi(y)\rangle|^2 where :math:`x` and :math:`y` are optional parametrizations of the states :math:`\psi` and :math:`\phi` prepared by the circuits ``circuit_1`` and ``circuit_2``, respectively. **Reference:** [1] Havlíček, V., Córcoles, A. D., Temme, K., Harrow, A. W., Kandala, A., Chow, J. M., & Gambetta, J. M. (2019). Supervised learning with quantum-enhanced feature spaces. Nature, 567(7747), 209-212. `arXiv:1804.11326v2 [quant-ph] <https://arxiv.org/pdf/1804.11326.pdf>`_ """ def __init__( self, sampler: BaseSampler, options: Options | None = None, local: bool = False, ) -> None: r""" Args: sampler: Sampler primitive instance. options: Primitive backend runtime options used for circuit execution. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. local: If set to ``True``, the fidelity is averaged over single-qubit projectors .. math:: \hat{O} = \frac{1}{N}\sum_{i=1}^N|0_i\rangle\langle 0_i|, instead of the global projector :math:`|0\rangle\langle 0|^{\otimes n}`. This coincides with the standard (global) fidelity in the limit of the fidelity approaching 1. Might be used to increase the variance to improve trainability in algorithms such as :class:`~.time_evolvers.PVQD`. Raises: ValueError: If the sampler is not an instance of ``BaseSampler``. """ if not isinstance(sampler, BaseSampler): raise ValueError( f"The sampler should be an instance of BaseSampler, " f"but got {type(sampler)}" ) self._sampler: BaseSampler = sampler self._local = local self._default_options = Options() if options is not None: self._default_options.update_options(**options) super().__init__() def create_fidelity_circuit( self, circuit_1: QuantumCircuit, circuit_2: QuantumCircuit ) -> QuantumCircuit: """ Combines ``circuit_1`` and ``circuit_2`` to create the fidelity circuit following the compute-uncompute method. Args: circuit_1: (Parametrized) quantum circuit. circuit_2: (Parametrized) quantum circuit. Returns: The fidelity quantum circuit corresponding to circuit_1 and circuit_2. """ if len(circuit_1.clbits) > 0: circuit_1.remove_final_measurements() if len(circuit_2.clbits) > 0: circuit_2.remove_final_measurements() circuit = circuit_1.compose(circuit_2.inverse()) circuit.measure_all() return circuit def _run( self, circuits_1: QuantumCircuit | Sequence[QuantumCircuit], circuits_2: QuantumCircuit | Sequence[QuantumCircuit], values_1: Sequence[float] | Sequence[Sequence[float]] | None = None, values_2: Sequence[float] | Sequence[Sequence[float]] | None = None, **options, ) -> StateFidelityResult: r""" Computes the state overlap (fidelity) calculation between two (parametrized) circuits (first and second) for a specific set of parameter values (first and second) following the compute-uncompute method. Args: circuits_1: (Parametrized) quantum circuits preparing :math:`|\psi\rangle`. circuits_2: (Parametrized) quantum circuits preparing :math:`|\phi\rangle`. values_1: Numerical parameters to be bound to the first circuits. values_2: Numerical parameters to be bound to the second circuits. options: Primitive backend runtime options used for circuit execution. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Higher priority setting overrides lower priority setting. Returns: The result of the fidelity calculation. Raises: ValueError: At least one pair of circuits must be defined. AlgorithmError: If the sampler job is not completed successfully. """ circuits = self._construct_circuits(circuits_1, circuits_2) if len(circuits) == 0: raise ValueError( "At least one pair of circuits must be defined to calculate the state overlap." ) values = self._construct_value_list(circuits_1, circuits_2, values_1, values_2) # The priority of run options is as follows: # options in `evaluate` method > fidelity's default options > # primitive's default options. opts = copy(self._default_options) opts.update_options(**options) job = self._sampler.run(circuits=circuits, parameter_values=values, **opts.__dict__) try: result = job.result() except Exception as exc: raise AlgorithmError("Sampler job failed!") from exc if self._local: raw_fidelities = [ self._get_local_fidelity(prob_dist, circuit.num_qubits) for prob_dist, circuit in zip(result.quasi_dists, circuits) ] else: raw_fidelities = [ self._get_global_fidelity(prob_dist) for prob_dist in result.quasi_dists ] fidelities = self._truncate_fidelities(raw_fidelities) return StateFidelityResult( fidelities=fidelities, raw_fidelities=raw_fidelities, metadata=result.metadata, options=self._get_local_options(opts.__dict__), ) @property def options(self) -> Options: """Return the union of estimator options setting and fidelity default options, where, if the same field is set in both, the fidelity's default options override the primitive's default setting. Returns: The fidelity default + estimator options. """ return self._get_local_options(self._default_options.__dict__) def update_default_options(self, **options): """Update the fidelity's default options setting. Args: **options: The fields to update the default options. """ self._default_options.update_options(**options) def _get_local_options(self, options: Options) -> Options: """Return the union of the primitive's default setting, the fidelity default options, and the options in the ``run`` method. The order of priority is: options in ``run`` method > fidelity's default options > primitive's default setting. Args: options: The fields to update the options Returns: The fidelity default + estimator + run options. """ opts = copy(self._sampler.options) opts.update_options(**options) return opts def _get_global_fidelity(self, probability_distribution: dict[int, float]) -> float: """Process the probability distribution of a measurement to determine the global fidelity. Args: probability_distribution: Obtained from the measurement result Returns: The global fidelity. """ return probability_distribution.get(0, 0) def _get_local_fidelity( self, probability_distribution: dict[int, float], num_qubits: int ) -> float: """Process the probability distribution of a measurement to determine the local fidelity by averaging over single-qubit projectors. Args: probability_distribution: Obtained from the measurement result Returns: The local fidelity. """ fidelity = 0.0 for qubit in range(num_qubits): for bitstring, prob in probability_distribution.items(): # Check whether the bit representing the current qubit is 0 if not bitstring >> qubit & 1: fidelity += prob / num_qubits return fidelity
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Time evolution problem class.""" from __future__ import annotations from collections.abc import Mapping from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression from qiskit.opflow import PauliSumOp from ..list_or_dict import ListOrDict from ...quantum_info import Statevector from ...quantum_info.operators.base_operator import BaseOperator class TimeEvolutionProblem: """Time evolution problem class. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. Attributes: hamiltonian (BaseOperator | PauliSumOp): The Hamiltonian under which to evolve the system. initial_state (QuantumCircuit | Statevector | None): The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators (ListOrDict[BaseOperator | PauliSumOp] | None): Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold (float): Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param (Parameter | None): Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_map (dict[Parameter, complex] | None): Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. """ def __init__( self, hamiltonian: BaseOperator | PauliSumOp, time: float, initial_state: QuantumCircuit | Statevector | None = None, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, param_value_map: Mapping[Parameter, complex] | None = None, ): """ Args: hamiltonian: The Hamiltonian under which to evolve the system. time: Total time of evolution. initial_state: The quantum state to be evolved for methods like Trotterization. For variational time evolutions, where the evolution happens in an ansatz, this argument is not required. aux_operators: Optional list of auxiliary operators to be evaluated with the evolved ``initial_state`` and their expectation values returned. truncation_threshold: Defines a threshold under which values can be assumed to be 0. Used when ``aux_operators`` is provided. t_param: Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. param_value_map: Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. Raises: ValueError: If non-positive time of evolution is provided. """ self.t_param = t_param self.param_value_map = param_value_map self.hamiltonian = hamiltonian self.time = time if isinstance(initial_state, Statevector): circuit = QuantumCircuit(initial_state.num_qubits) circuit.prepare_state(initial_state.data) initial_state = circuit self.initial_state: QuantumCircuit | None = initial_state self.aux_operators = aux_operators self.truncation_threshold = truncation_threshold @property def time(self) -> float: """Returns time.""" return self._time @time.setter def time(self, time: float) -> None: """ Sets time and validates it. """ self._time = time def validate_params(self) -> None: """ Checks if all parameters present in the Hamiltonian are also present in the dictionary that maps them to values. Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ if isinstance(self.hamiltonian, PauliSumOp) and isinstance( self.hamiltonian.coeff, ParameterExpression ): raise ValueError("A global parametrized coefficient for PauliSumOp is not allowed.")
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for holding time evolution result.""" from __future__ import annotations import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit_algorithms.list_or_dict import ListOrDict from ..algorithm_result import AlgorithmResult class TimeEvolutionResult(AlgorithmResult): """ Class for holding time evolution result. Attributes: evolved_state (QuantumCircuit|Statevector): An evolved quantum state. aux_ops_evaluated (ListOrDict[tuple[complex, complex]] | None): Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables (ListOrDict[tuple[np.ndarray, np.ndarray]] | None): Optional list of observables for which expected on an evolved state are calculated at each timestep. These values are in fact lists of tuples formatted as (mean, standard deviation). times (np.array | None): Optional list of times at which each observable has been evaluated. """ def __init__( self, evolved_state: QuantumCircuit | Statevector, aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, observables: ListOrDict[tuple[np.ndarray, np.ndarray]] | None = None, times: np.ndarray | None = None, ): """ Args: evolved_state: An evolved quantum state. aux_ops_evaluated: Optional list of observables for which expected values on an evolved state are calculated. These values are in fact tuples formatted as (mean, standard deviation). observables: Optional list of observables for which expected values are calculated for each timestep. These values are in fact tuples formatted as (mean array, standard deviation array). times: Optional list of times at which each observable has been evaluated. """ self.evolved_state = evolved_state self.aux_ops_evaluated = aux_ops_evaluated self.observables = observables self.times = times
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Auxiliary functions for SciPy Time Evolvers""" from __future__ import annotations import logging from scipy.sparse import csr_matrix from scipy.sparse.linalg import expm_multiply import numpy as np from qiskit.quantum_info.states import Statevector from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from ..time_evolution_problem import TimeEvolutionProblem from ..time_evolution_result import TimeEvolutionResult from ...exceptions import AlgorithmError from ...list_or_dict import ListOrDict logger = logging.getLogger(__name__) def _create_observable_output( ops_ev_mean: np.ndarray, evolution_problem: TimeEvolutionProblem, ) -> tuple[ListOrDict[tuple[np.ndarray, np.ndarray]], np.ndarray]: """Creates the right output format for the evaluated auxiliary operators. Args: ops_ev_mean: Array containing the expectation value of each observable at each timestep. evolution_problem: Time Evolution Problem to create the output of. Returns: An output with the observables mean value at the appropriate times depending on whether the auxiliary operators in the time evolution problem are a `list` or a `dict`. """ aux_ops = evolution_problem.aux_operators time_array = np.linspace(0, evolution_problem.time, ops_ev_mean.shape[-1]) zero_array = np.zeros(ops_ev_mean.shape[-1]) # std=0 since it is an exact method operators_number = 0 if aux_ops is None else len(aux_ops) observable_evolution = [(ops_ev_mean[i], zero_array) for i in range(operators_number)] if isinstance(aux_ops, dict): observable_evolution = dict(zip(aux_ops.keys(), observable_evolution)) return observable_evolution, time_array def _create_obs_final( ops_ev_mean: np.ndarray, evolution_problem: TimeEvolutionProblem, ) -> ListOrDict[tuple[complex, complex]]: """Creates the right output format for the final value of the auxiliary operators. Args: ops_ev_mean: Array containing the expectation value of each observable at the final timestep. evolution_problem: Evolution problem to create the output of. Returns: An output with the observables mean value at the appropriate times depending on whether the auxiliary operators in the evolution problem are a `list` or a `dict`. """ aux_ops = evolution_problem.aux_operators aux_ops_evaluated: ListOrDict[tuple[complex, complex]] = [(op_ev, 0) for op_ev in ops_ev_mean] if isinstance(aux_ops, dict): aux_ops_evaluated = dict(zip(aux_ops.keys(), aux_ops_evaluated)) return aux_ops_evaluated def _evaluate_aux_ops( aux_ops: list[csr_matrix], state: np.ndarray, ) -> np.ndarray: """Evaluates the aux operators if they are provided and stores their value. Returns: Mean of the aux operators for a given state. """ op_means = np.array([np.real(state.conjugate().dot(op.dot(state))) for op in aux_ops]) return op_means def _operator_to_matrix(operator: BaseOperator | PauliSumOp): if isinstance(operator, PauliSumOp): op_matrix = operator.to_spmatrix() else: try: op_matrix = operator.to_matrix(sparse=True) except TypeError: logger.debug( "WARNING: operator of type `%s` does not support sparse matrices. " "Trying dense computation", type(operator), ) try: op_matrix = operator.to_matrix() except AttributeError as ex: raise AlgorithmError(f"Unsupported operator type `{type(operator)}`.") from ex return op_matrix def _build_scipy_operators( evolution_problem: TimeEvolutionProblem, num_timesteps: int, real_time: bool ) -> tuple[np.ndarray, list[csr_matrix], csr_matrix]: """Returns the matrices and parameters needed for time evolution in the appropriate format. Args: evolution_problem: The definition of the evolution problem. num_timesteps: Number of timesteps to be performed. real_time: If `True`, returned operators will correspond to real time evolution, Else, they will correspond to imaginary time evolution. Returns: A tuple with the initial state, the list of operators to evaluate and the operator to be exponentiated to perform one timestep. Raises: ValueError: If the Hamiltonian can not be converted into a sparse matrix or dense matrix. """ # Convert the initial state and Hamiltonian into sparse matrices. if isinstance(evolution_problem.initial_state, QuantumCircuit): state = Statevector(evolution_problem.initial_state).data else: state = evolution_problem.initial_state.data hamiltonian = _operator_to_matrix(operator=evolution_problem.hamiltonian) if isinstance(evolution_problem.aux_operators, list): aux_ops = [ _operator_to_matrix(operator=aux_op) for aux_op in evolution_problem.aux_operators ] elif isinstance(evolution_problem.aux_operators, dict): aux_ops = [ _operator_to_matrix(operator=aux_op) for aux_op in evolution_problem.aux_operators.values() ] else: aux_ops = [] timestep = evolution_problem.time / num_timesteps step_operator = -((1.0j) ** real_time) * timestep * hamiltonian return state, aux_ops, step_operator def _evolve( evolution_problem: TimeEvolutionProblem, num_timesteps: int, real_time: bool ) -> TimeEvolutionResult: r"""Performs either real or imaginary time evolution :math:`\exp(-i t H)|\Psi\rangle`. Args: evolution_problem: The definition of the evolution problem. num_timesteps: Number of timesteps to be performed. real_time: If `True`, returned operators will correspond to real time evolution, Else, they will correspond to imaginary time evolution. Returns: Evolution result which includes an evolved quantum state. Raises: ValueError: If the Hamiltonian is time dependent. ValueError: If the initial state is `None`. """ if num_timesteps <= 0: raise ValueError("Variable `num_timesteps` needs to be a positive integer.") if evolution_problem.t_param is not None: raise ValueError("Time dependent Hamiltonians are not supported.") if evolution_problem.initial_state is None: raise ValueError("Initial state is `None`") state, aux_ops, step_operator = _build_scipy_operators( evolution_problem=evolution_problem, num_timesteps=num_timesteps, real_time=real_time ) # Create empty arrays to store the time evolution of the aux operators. number_operators = ( 0 if evolution_problem.aux_operators is None else len(evolution_problem.aux_operators) ) ops_ev_mean = np.empty(shape=(number_operators, num_timesteps + 1), dtype=complex) renormalize = ( (lambda state: state) if real_time else (lambda state: state / np.linalg.norm(state)) ) # Perform the time evolution and stores the value of the operators at each timestep. for ts in range(num_timesteps): ops_ev_mean[:, ts] = _evaluate_aux_ops(aux_ops, state) state = expm_multiply(A=step_operator, B=state) state = renormalize(state) ops_ev_mean[:, num_timesteps] = _evaluate_aux_ops(aux_ops, state) observable_history, times = _create_observable_output(ops_ev_mean, evolution_problem) aux_ops_evaluated = _create_obs_final(ops_ev_mean[:, -1], evolution_problem) return TimeEvolutionResult( evolved_state=Statevector(state), aux_ops_evaluated=aux_ops_evaluated, observables=observable_history, times=times, )
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """An algorithm to implement a Trotterization real time-evolution.""" from __future__ import annotations from qiskit import QuantumCircuit from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit_algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit_algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit_algorithms.observables_evaluator import estimate_observables from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.circuit.parametertable import ParameterView from qiskit.primitives import BaseEstimator from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.synthesis import ProductFormula, LieTrotter class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ``ProductFormula`` provided. Examples: .. code-block:: python from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit_algorithms.time_evolvers import TrotterQRTE from qiskit.primitives import Estimator operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) # LieTrotter with 1 rep estimator = Estimator() trotter_qrte = TrotterQRTE(estimator=estimator) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ def __init__( self, product_formula: ProductFormula | None = None, estimator: BaseEstimator | None = None, num_timesteps: int = 1, ) -> None: """ Args: product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the Lie-Trotter first order product formula with a single repetition is used. ``reps`` should be 1 to obtain a number of time-steps equal to ``num_timesteps`` and an evaluation of :attr:`.TimeEvolutionProblem.aux_operators` at every time-step. If ``reps`` is larger than 1, the true number of time-steps will be ``num_timesteps * reps``. num_timesteps: The number of time-steps the full evolution time is devided into (repetitions of ``product_formula``) estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. """ self.product_formula = product_formula self.num_timesteps = num_timesteps self.estimator = estimator @property def product_formula(self) -> ProductFormula: """Returns a product formula.""" return self._product_formula @product_formula.setter def product_formula(self, product_formula: ProductFormula | None): """Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product formula with a single repetition.""" if product_formula is None: product_formula = LieTrotter() self._product_formula = product_formula @property def estimator(self) -> BaseEstimator | None: """ Returns an estimator. """ return self._estimator @estimator.setter def estimator(self, estimator: BaseEstimator) -> None: """ Sets an estimator. """ self._estimator = estimator @property def num_timesteps(self) -> int: """Returns the number of timesteps.""" return self._num_timesteps @num_timesteps.setter def num_timesteps(self, num_timesteps: int) -> None: """ Sets the number of time-steps. Raises: ValueError: If num_timesteps is not positive. """ if num_timesteps <= 0: raise ValueError( f"Number of time steps must be positive integer, {num_timesteps} provided" ) self._num_timesteps = num_timesteps @classmethod def supports_aux_operators(cls) -> bool: """ Whether computing the expectation value of auxiliary operators is supported. Returns: ``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be evaluated, ``False`` otherwise. """ return True def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: """ Evolves a quantum state for a given time using the Trotterization method based on a product formula provided. The result is provided in the form of a quantum circuit. If auxiliary operators are included in the ``evolution_problem``, they are evaluated on the ``init_state`` and on the evolved state at every step (``num_timesteps`` times) using an estimator primitive provided. Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, ``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE. Returns: Evolution result that includes an evolved state as a quantum circuit and, optionally, auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` (feature not currently supported). ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator provided to the algorithm. ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "The time evolution problem contained ``aux_operators`` but no estimator was " "provided. The algorithm continues without calculating these quantities. " ) # ensure the hamiltonian is a sparse pauli op hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp, SparsePauliOp)): raise ValueError( f"TrotterQRTE only accepts Pauli | PauliSumOp | SparsePauliOp, {type(hamiltonian)} " "provided." ) if isinstance(hamiltonian, PauliSumOp): hamiltonian = hamiltonian.primitive * hamiltonian.coeff elif isinstance(hamiltonian, Pauli): hamiltonian = SparsePauliOp(hamiltonian) t_param = evolution_problem.t_param free_parameters = hamiltonian.parameters if t_param is not None and free_parameters != ParameterView([t_param]): raise ValueError( f"Hamiltonian time parameters ({free_parameters}) do not match " f"evolution_problem.t_param ({t_param})." ) # make sure PauliEvolutionGate does not implement more than one Trotter step dt = evolution_problem.time / self.num_timesteps if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state else: raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.") evolved_state = QuantumCircuit(initial_state.num_qubits) evolved_state.append(initial_state, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables = [] observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) else: observables = None if t_param is None: # the evolution gate single_step_evolution_gate = PauliEvolutionGate( hamiltonian, dt, synthesis=self.product_formula ) for n in range(self.num_timesteps): # if hamiltonian is time-dependent, bind new time-value at every step to construct # evolution for next step if t_param is not None: time_value = (n + 1) * dt bound_hamiltonian = hamiltonian.assign_parameters([time_value]) single_step_evolution_gate = PauliEvolutionGate( bound_hamiltonian, dt, synthesis=self.product_formula, ) evolved_state.append(single_step_evolution_gate, evolved_state.qubits) if evolution_problem.aux_operators is not None: observables.append( estimate_observables( self.estimator, evolved_state, evolution_problem.aux_operators, None, evolution_problem.truncation_threshold, ) ) evaluated_aux_ops = None if evolution_problem.aux_operators is not None: evaluated_aux_ops = observables[-1] return TimeEvolutionResult(evolved_state, evaluated_aux_ops, observables)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Imaginary Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import ImaginaryVariationalPrinciple, ImaginaryMcLachlanPrinciple from .var_qte import VarQTE from ..imaginary_time_evolver import ImaginaryTimeEvolver class VarQITE(VarQTE, ImaginaryTimeEvolver): """Variational Quantum Imaginary Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQITE from qiskit_algorithms.time_evolvers.variational import ImaginaryMcLachlanPrinciple from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = ImaginaryMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qite = VarQITE(ansatz, init_param_values, var_principle) evolution_result = var_qite.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qite = VarQITE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qite.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: ImaginaryVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for the ansatz. variational_principle: Variational Principle to be used. Defaults to ``ImaginaryMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = ImaginaryMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Variational Quantum Real Time Evolution algorithm.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Type, Callable import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import BaseEstimator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .variational_principles import RealVariationalPrinciple, RealMcLachlanPrinciple from .var_qte import VarQTE from ..real_time_evolver import RealTimeEvolver class VarQRTE(VarQTE, RealTimeEvolver): """Variational Quantum Real Time Evolution algorithm. .. code-block::python import numpy as np from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit.circuit.library import EfficientSU2 from qiskit_algorithms.time_evolvers.variational import RealMcLachlanPrinciple from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.primitives import Estimator observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) ansatz = EfficientSU2(observable.num_qubits, reps=1) init_param_values = np.ones(len(ansatz.parameters)) * np.pi/2 var_principle = RealMcLachlanPrinciple() time = 1 # without evaluating auxiliary operators evolution_problem = TimeEvolutionProblem(observable, time) var_qrte = VarQRTE(ansatz, init_param_values, var_principle) evolution_result = var_qrte.evolve(evolution_problem) # evaluating auxiliary operators aux_ops = [Pauli("XX"), Pauli("YZ")] evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) var_qrte = VarQRTE(ansatz, init_param_values, var_principle, Estimator()) evolution_result = var_qrte.evolve(evolution_problem) """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: RealVariationalPrinciple | None = None, estimator: BaseEstimator | None = None, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. Defaults to ``RealMcLachlanPrinciple``. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. num_timesteps: The number of timesteps to take. If ``None``, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ if variational_principle is None: variational_principle = RealMcLachlanPrinciple() super().__init__( ansatz, initial_parameters, variational_principle, estimator, ode_solver, lse_solver=lse_solver, num_timesteps=num_timesteps, imag_part_tol=imag_part_tol, num_instability_tol=num_instability_tol, )
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """The Variational Quantum Time Evolution Interface""" from __future__ import annotations from abc import ABC from collections.abc import Mapping, Callable, Sequence from typing import Type import numpy as np from scipy.integrate import OdeSolver from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp from qiskit.primitives import BaseEstimator from qiskit.quantum_info.operators.base_operator import BaseOperator from .solvers.ode.forward_euler_solver import ForwardEulerSolver from .solvers.ode.ode_function_factory import OdeFunctionFactory from .solvers.ode.var_qte_ode_solver import VarQTEOdeSolver from .solvers.var_qte_linear_solver import VarQTELinearSolver from .variational_principles.variational_principle import VariationalPrinciple from .var_qte_result import VarQTEResult from ..time_evolution_problem import TimeEvolutionProblem from ...observables_evaluator import estimate_observables class VarQTE(ABC): """Variational Quantum Time Evolution. Algorithms that use variational principles to compute a time evolution for a given Hermitian operator (Hamiltonian) and a quantum state prepared by a parameterized quantum circuit. Attributes: ansatz (QuantumCircuit): Ansatz to be used for variational time evolution. initial_parameters (Mapping[Parameter, float] | Sequence[float]): Initial parameter values for an ansatz. variational_principle (VariationalPrinciple): Variational Principle to be used. estimator (BaseEstimator): An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. ode_solver(Type[OdeSolver] | str): ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver (Callable[[np.ndarray, np.ndarray], np.ndarray] | None): Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. num_timesteps (int | None): The number of timesteps to take. If None, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol (float): Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol (float): The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. References: [1] Benjamin, Simon C. et al. (2019). Theory of variational quantum simulation. `<https://doi.org/10.22331/q-2019-10-07-191>`_ """ def __init__( self, ansatz: QuantumCircuit, initial_parameters: Mapping[Parameter, float] | Sequence[float], variational_principle: VariationalPrinciple, estimator: BaseEstimator, ode_solver: Type[OdeSolver] | str = ForwardEulerSolver, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, num_timesteps: int | None = None, imag_part_tol: float = 1e-7, num_instability_tol: float = 1e-7, ) -> None: r""" Args: ansatz: Ansatz to be used for variational time evolution. initial_parameters: Initial parameter values for an ansatz. variational_principle: Variational Principle to be used. estimator: An estimator primitive used for calculating expectation values of TimeEvolutionProblem.aux_operators. ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a string indicating a valid method offered by SciPy. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. num_timesteps: The number of timesteps to take. If None, it is automatically selected to achieve a timestep of approximately 0.01. Only relevant in case of the ``ForwardEulerSolver``. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. num_instability_tol: The amount of negative value that is allowed to be rounded up to 0 for quantities that are expected to be non-negative. """ super().__init__() self.ansatz = ansatz self.initial_parameters = initial_parameters self.variational_principle = variational_principle self.estimator = estimator self.num_timesteps = num_timesteps self.lse_solver = lse_solver self.ode_solver = ode_solver self.imag_part_tol = imag_part_tol self.num_instability_tol = num_instability_tol # OdeFunction abstraction kept for potential extensions - unclear at the moment; # currently hidden from the user self._ode_function_factory = OdeFunctionFactory() def evolve(self, evolution_problem: TimeEvolutionProblem) -> VarQTEResult: """Apply Variational Quantum Time Evolution to the given operator. Args: evolution_problem: Instance defining an evolution problem. Returns: Result of the evolution which includes a quantum circuit with bound parameters as an evolved state and, if provided, observables evaluated on the evolved state. Raises: ValueError: If ``initial_state`` is included in the ``evolution_problem``. """ self._validate_aux_ops(evolution_problem) if evolution_problem.initial_state is not None: raise ValueError( "An initial_state was provided to the TimeEvolutionProblem but this is not " "supported by VarQTE. Please remove this state from the problem definition " "and set VarQTE.initial_parameters with the corresponding initial parameter " "values instead." ) init_state_param_dict = self._create_init_state_param_dict( self.initial_parameters, self.ansatz.parameters ) # unwrap PauliSumOp (in the future this will be deprecated) if isinstance(evolution_problem.hamiltonian, PauliSumOp): hamiltonian = ( evolution_problem.hamiltonian.primitive * evolution_problem.hamiltonian.coeff ) else: hamiltonian = evolution_problem.hamiltonian evolved_state, param_values, time_points = self._evolve( init_state_param_dict, hamiltonian, evolution_problem.time, evolution_problem.t_param, ) observables = [] if evolution_problem.aux_operators is not None: for values in param_values: # cannot batch evaluation because estimate_observables # only accepts single circuits evol_state = self.ansatz.assign_parameters( dict(zip(init_state_param_dict.keys(), values)) ) observable = estimate_observables( self.estimator, evol_state, evolution_problem.aux_operators, ) observables.append(observable) # TODO: deprecate returning evaluated_aux_ops. # As these are the observables for the last time step. evaluated_aux_ops = observables[-1] if len(observables) > 0 else None return VarQTEResult( evolved_state, evaluated_aux_ops, observables, time_points, param_values ) def _evolve( self, init_state_param_dict: Mapping[Parameter, float], hamiltonian: BaseOperator, time: float, t_param: Parameter | None = None, ) -> tuple[QuantumCircuit | None, Sequence[Sequence[float]], Sequence[float]]: r""" Helper method for performing time evolution. Works both for imaginary and real case. Args: init_state_param_dict: Parameter dictionary with initial values for a given parametrized state/ansatz. hamiltonian: Operator used for Variational Quantum Time Evolution (VarQTE). time: Total time of evolution. t_param: Time parameter in case of a time-dependent Hamiltonian. Returns: Result of the evolution which is a quantum circuit with bound parameters as an evolved state. """ init_state_parameters = list(init_state_param_dict.keys()) init_state_parameter_values = list(init_state_param_dict.values()) linear_solver = VarQTELinearSolver( self.variational_principle, hamiltonian, self.ansatz, init_state_parameters, t_param, self.lse_solver, self.imag_part_tol, ) # Convert the operator that holds the Hamiltonian and ansatz into a NaturalGradient operator ode_function = self._ode_function_factory._build( linear_solver, init_state_param_dict, t_param ) ode_solver = VarQTEOdeSolver( init_state_parameter_values, ode_function, self.ode_solver, self.num_timesteps ) final_param_values, param_values, time_points = ode_solver.run(time) param_dict_from_ode = dict(zip(init_state_parameters, final_param_values)) return self.ansatz.assign_parameters(param_dict_from_ode), param_values, time_points @staticmethod def _create_init_state_param_dict( param_values: Mapping[Parameter, float] | Sequence[float], init_state_parameters: Sequence[Parameter], ) -> Mapping[Parameter, float]: r""" If ``param_values`` is a dictionary, it looks for parameters present in an initial state (an ansatz) in a ``param_values``. Based on that, it creates a new dictionary containing only parameters present in an initial state and their respective values. If ``param_values`` is a list of values, it creates a new dictionary containing parameters present in an initial state and their respective values. Args: param_values: Dictionary which relates parameter values to the parameters or a list of values. init_state_parameters: Parameters present in a quantum state. Returns: Dictionary that maps parameters of an initial state to some values. Raises: ValueError: If the dictionary with parameter values provided does not include all parameters present in the initial state or if the list of values provided is not the same length as the list of parameters. TypeError: If an unsupported type of ``param_values`` provided. """ if isinstance(param_values, Mapping): init_state_parameter_values: Sequence[float] = [] for param in init_state_parameters: if param in param_values.keys(): init_state_parameter_values.append(param_values[param]) else: raise ValueError( f"The dictionary with parameter values provided does not " f"include all parameters present in the initial state." f"Parameters present in the state: {init_state_parameters}, " f"parameters in the dictionary: " f"{list(param_values.keys())}." ) elif isinstance(param_values, (Sequence, np.ndarray)): if len(init_state_parameters) != len(param_values): raise ValueError( f"Initial state has {len(init_state_parameters)} parameters and the" f" list of values has {len(param_values)} elements. They should be" f" equal in length." ) init_state_parameter_values = param_values else: raise TypeError(f"Unsupported type of param_values provided: {type(param_values)}.") init_state_param_dict = dict(zip(init_state_parameters, init_state_parameter_values)) return init_state_param_dict def _validate_aux_ops(self, evolution_problem: TimeEvolutionProblem) -> None: if evolution_problem.aux_operators is not None and self.estimator is None: raise ValueError( "aux_operators were provided for evaluations but no ``estimator`` was provided." )
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for solving linear equations for Quantum Time Evolution.""" from __future__ import annotations from collections.abc import Mapping, Sequence, Callable import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from ..variational_principles import VariationalPrinciple class VarQTELinearSolver: """Class for solving linear equations for Quantum Time Evolution.""" def __init__( self, var_principle: VariationalPrinciple, hamiltonian: BaseOperator, ansatz: QuantumCircuit, gradient_params: Sequence[Parameter] | None = None, t_param: Parameter | None = None, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, imag_part_tol: float = 1e-7, ) -> None: """ Args: var_principle: Variational Principle to be used. hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. t_param: Time parameter in case of a time-dependent Hamiltonian. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. Raises: TypeError: If t_param is provided and Hamiltonian is not of type SparsePauliOp. """ self._var_principle = var_principle self._hamiltonian = hamiltonian self._ansatz = ansatz self._gradient_params = gradient_params self._bind_params = gradient_params self._time_param = t_param self.lse_solver = lse_solver self._imag_part_tol = imag_part_tol if self._time_param is not None and not isinstance(self._hamiltonian, SparsePauliOp): raise TypeError( f"A time parameter {t_param} has been specified, so a time-dependent " f"hamiltonian is expected. The operator provided is of type {type(self._hamiltonian)}, " f"which might not support parametrization. " f"Please provide the parametrized hamiltonian as a SparsePauliOp." ) @property def lse_solver(self) -> Callable[[np.ndarray, np.ndarray], np.ndarray]: """Returns an LSE solver callable.""" return self._lse_solver @lse_solver.setter def lse_solver(self, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None) -> None: """Sets an LSE solver. Uses a ``np.linalg.lstsq`` callable if ``None`` provided.""" if lse_solver is None: lse_solver = lambda a, b: np.linalg.lstsq(a, b, rcond=1e-2)[0] self._lse_solver = lse_solver def solve_lse( self, param_dict: Mapping[Parameter, float], time_value: float | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Solve the system of linear equations underlying McLachlan's variational principle for the calculation without error bounds. Args: param_dict: Dictionary which relates parameter values to the parameters in the ansatz. time_value: Time value that will be bound to ``t_param``. It is required if ``t_param`` is not ``None``. Returns: Solution to the LSE, A from Ax=b, b from Ax=b. Raises: ValueError: If no time value is provided for time dependent hamiltonians. """ param_values = list(param_dict.values()) metric_tensor_lse_lhs = self._var_principle.metric_tensor(self._ansatz, param_values) hamiltonian = self._hamiltonian if self._time_param is not None: if time_value is not None: hamiltonian = hamiltonian.assign_parameters([time_value]) else: raise ValueError( "Providing a time_value is required for time-dependent hamiltonians, " f"but got time_value = {time_value}. " "Please provide a time_value to the solve_lse method." ) evolution_grad_lse_rhs = self._var_principle.evolution_gradient( hamiltonian, self._ansatz, param_values, self._gradient_params ) x = self._lse_solver(metric_tensor_lse_lhs, evolution_grad_lse_rhs) return np.real(x), metric_tensor_lse_lhs, evolution_grad_lse_rhs
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for an Imaginary McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info.operators.base_operator import BaseOperator from .imaginary_variational_principle import ImaginaryVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class ImaginaryMcLachlanPrinciple(ImaginaryVariationalPrinciple): """Class for an Imaginary McLachlan's Variational Principle. It aims to minimize the distance between both sides of the Wick-rotated Schrödinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The imaginary variant means that we consider imaginary time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: evolution_grad_lse_rhs = ( self.gradient.run([ansatz], [hamiltonian], [param_values], [gradient_params]) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc return -0.5 * evolution_grad_lse_rhs @staticmethod def _validate_grad_settings(gradient): if ( gradient is not None and hasattr(gradient, "_derivative_type") and gradient._derivative_type != DerivativeType.REAL ): warnings.warn( "A gradient instance with a setting for calculating imaginary part of " "the gradient was provided. This variational principle requires the" "real part. The setting to real was changed automatically." ) gradient._derivative_type = DerivativeType.REAL
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for a Real McLachlan's Variational Principle.""" from __future__ import annotations import warnings from collections.abc import Sequence import numpy as np from numpy import real from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from .real_variational_principle import RealVariationalPrinciple from ....exceptions import AlgorithmError from ....gradients import ( BaseEstimatorGradient, BaseQGT, DerivativeType, LinCombQGT, LinCombEstimatorGradient, ) class RealMcLachlanPrinciple(RealVariationalPrinciple): """Class for a Real McLachlan's Variational Principle. It aims to minimize the distance between both sides of the Schrödinger equation with a quantum state given as a parametrized trial state. The principle leads to a system of linear equations handled by a linear solver. The real variant means that we consider real time dynamics. """ def __init__( self, qgt: BaseQGT | None = None, gradient: BaseEstimatorGradient | None = None, ) -> None: """ Args: qgt: Instance of a the GQT class used to compute the QFI. If ``None`` provided, ``LinCombQGT`` is used. gradient: Instance of a class used to compute the state gradient. If ``None`` provided, ``LinCombEstimatorGradient`` is used. Raises: AlgorithmError: If the gradient instance does not contain an estimator. """ self._validate_grad_settings(gradient) if gradient is not None: try: estimator = gradient._estimator except Exception as exc: raise AlgorithmError( "The provided gradient instance does not contain an estimator primitive." ) from exc else: estimator = Estimator() gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) if qgt is None: qgt = LinCombQGT(estimator) super().__init__(qgt, gradient) def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. Raises: AlgorithmError: If a gradient job fails. """ try: estimator_job = self.gradient._estimator.run([ansatz], [hamiltonian], [param_values]) energy = estimator_job.result().values[0] except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc modified_hamiltonian = self._construct_modified_hamiltonian(hamiltonian, real(energy)) try: evolution_grad = ( 0.5 * self.gradient.run( [ansatz], [modified_hamiltonian], parameters=[gradient_params], parameter_values=[param_values], ) .result() .gradients[0] ) except Exception as exc: raise AlgorithmError("The gradient primitive job failed!") from exc # The BaseEstimatorGradient class returns the gradient of the opposite sign than we expect # here (i.e. with a minus sign), hence the correction that cancels it to recover the # real McLachlan's principle equations that do not have a minus sign. evolution_grad = (-1) * evolution_grad return evolution_grad @staticmethod def _construct_modified_hamiltonian(hamiltonian: BaseOperator, energy: float) -> BaseOperator: """ Modifies a Hamiltonian according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. energy: The energy correction value. Returns: A modified Hamiltonian. """ energy_term = SparsePauliOp.from_list( hamiltonian.to_list() + [("I" * hamiltonian.num_qubits, -energy)] ) return energy_term @staticmethod def _validate_grad_settings(gradient): if gradient is not None: if not hasattr(gradient, "_derivative_type"): raise ValueError( "The gradient instance provided does not support calculating imaginary part. " "Please choose a different gradient class." ) if gradient._derivative_type != DerivativeType.IMAG: warnings.warn( "A gradient instance with a setting for calculating real part of the" "gradient was provided. This variational principle requires the" "imaginary part. The setting to imaginary was changed automatically." ) gradient._derivative_type = DerivativeType.IMAG
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Class for a Variational Principle.""" from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Sequence import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info.operators.base_operator import BaseOperator from ....exceptions import AlgorithmError from ....gradients import BaseEstimatorGradient, BaseQGT, DerivativeType class VariationalPrinciple(ABC): """A Variational Principle class. It determines the time propagation of parameters in a quantum state provided as a parametrized quantum circuit (ansatz). Attributes: qgt (BaseQGT): Instance of a class used to compute the GQT. gradient (BaseEstimatorGradient): Instance of a class used to compute the state gradient. """ def __init__( self, qgt: BaseQGT, gradient: BaseEstimatorGradient, ) -> None: """ Args: qgt: Instance of a class used to compute the GQT. gradient: Instance of a class used to compute the state gradient. """ self.qgt = qgt self.gradient = gradient def metric_tensor( self, ansatz: QuantumCircuit, param_values: Sequence[float] ) -> Sequence[float]: """ Calculates a metric tensor according to the rules of this variational principle. Args: ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. Returns: Metric tensor. Raises: AlgorithmError: If a QFI job fails. """ self.qgt.derivative_type = DerivativeType.REAL try: metric_tensor = self.qgt.run([ansatz], [param_values], [None]).result().qgts[0] except Exception as exc: raise AlgorithmError("The QFI primitive job failed!") from exc return metric_tensor @abstractmethod def evolution_gradient( self, hamiltonian: BaseOperator, ansatz: QuantumCircuit, param_values: Sequence[float], gradient_params: Sequence[Parameter] | None = None, ) -> np.ndarray: """ Calculates an evolution gradient according to the rules of this variational principle. Args: hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. param_values: Values of parameters to be bound. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. Returns: An evolution gradient. """ pass
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the quantum amplitude estimation algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, idata, data, unpack from qiskit import QuantumRegister, QuantumCircuit, BasicAer from qiskit.circuit.library import QFT, GroverOperator from qiskit.utils import QuantumInstance from qiskit_algorithms import ( AmplitudeEstimation, MaximumLikelihoodAmplitudeEstimation, IterativeAmplitudeEstimation, FasterAmplitudeEstimation, EstimationProblem, ) from qiskit.quantum_info import Operator, Statevector from qiskit.primitives import Sampler class BernoulliStateIn(QuantumCircuit): """A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>.""" def __init__(self, probability): super().__init__(1) angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(angle, 0) class BernoulliGrover(QuantumCircuit): """The Grover operator corresponding to the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1, global_phase=np.pi) self.angle = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self.angle, 0) def power(self, power, matrix_power=False): if matrix_power: return super().power(power, True) powered = QuantumCircuit(1) powered.ry(power * 2 * self.angle, 0) return powered class SineIntegral(QuantumCircuit): r"""Construct the A operator to approximate the integral \int_0^1 \sin^2(x) d x with a specified number of qubits. """ def __init__(self, num_qubits): qr_state = QuantumRegister(num_qubits, "state") qr_objective = QuantumRegister(1, "obj") super().__init__(qr_state, qr_objective) # prepare 1/sqrt{2^n} sum_x |x>_n self.h(qr_state) # apply the sine/cosine term self.ry(2 * 1 / 2 / 2**num_qubits, qr_objective[0]) for i, qubit in enumerate(qr_state): self.cry(2 * 2**i / 2**num_qubits, qubit, qr_objective[0]) @ddt class TestBernoulli(QiskitAlgorithmsTestCase): """Tests based on the Bernoulli A operator. This class tests * the estimation result * the constructed circuits """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=2, seed_transpiler=2, ) self._sampler = Sampler(options={"seed": 2}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=2, seed_transpiler=2, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 2}) self._sampler_shots = sampler_shots @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.2}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_statevector(self, prob, qae, expect): """statevector test""" problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector result = qae.estimate(problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}], [0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}], [0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}], [0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}], [0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}], [0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}], [0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.199}], [0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}], ] ) @unpack def test_sampler(self, prob, qae, expect): """sampler test""" qae.sampler = self._sampler problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.193888}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.199606}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.119037}, ], ] ) @unpack def test_qasm(self, prob, shots, qae, expect): """qasm test""" with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.198783}], [0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}], [ 0.2, 100, MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]), {"estimation": 0.200308}, ], [0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}], [0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}], [ 0.12, 100, FasterAmplitudeEstimation(0.01, 3, rescale=False), {"estimation": 0.120017}, ], ] ) @unpack def test_sampler_with_shots(self, prob, shots, qae, expect): """sampler with shots test""" qae.sampler = self._sampler_shots(shots) problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @data(True, False) def test_qae_circuit(self, efficient_circuit): """Test circuits resulting from canonical amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for m in [2, 5]: qae = AmplitudeEstimation(m) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit qr_eval = QuantumRegister(m, "a") qr_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(qr_eval, qr_objective) # initial Hadamard gates for i in range(m): circuit.h(qr_eval[i]) # A operator circuit.ry(angle, qr_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) for power in range(m): circuit.cry(2 * 2**power * angle, qr_eval[power], qr_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for power in range(m): circuit.compose( grover_op.power(2**power).control(), qubits=[qr_eval[power], qr_objective[0]], inplace=True, ) # fourier transform iqft = QFT(m, do_swaps=False).inverse().reverse_bits() circuit.append(iqft.to_instruction(), qr_eval) actual_circuit = qae.construct_circuit(problem, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_iqae_circuits(self, efficient_circuit): """Test circuits resulting from iterative amplitude estimation. Build the circuit manually and from the algorithm and compare the resulting unitaries. """ prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = IterativeAmplitudeEstimation(0.01, 0.05) angle = 2 * np.arcsin(np.sqrt(prob)) # manually set up the inefficient AE circuit q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * k * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(k): circuit.compose(grover_op, inplace=True) actual_circuit = qae.construct_circuit(problem, k, measurement=False) self.assertEqual(Operator(circuit), Operator(actual_circuit)) @data(True, False) def test_mlae_circuits(self, efficient_circuit): """Test the circuits constructed for MLAE""" prob = 0.5 problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0]) for k in [2, 5]: qae = MaximumLikelihoodAmplitudeEstimation(k) angle = 2 * np.arcsin(np.sqrt(prob)) # compute all the circuits used for MLAE circuits = [] # 0th power q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) circuit.ry(angle, q_objective) circuits += [circuit] # powers of 2 for power in range(k): q_objective = QuantumRegister(1, "q") circuit = QuantumCircuit(q_objective) # A operator circuit.ry(angle, q_objective) # Q^(2^j) operator if efficient_circuit: qae.grover_operator = BernoulliGrover(prob) circuit.ry(2 * 2**power * angle, q_objective[0]) else: oracle = QuantumCircuit(1) oracle.z(0) state_preparation = QuantumCircuit(1) state_preparation.ry(angle, 0) grover_op = GroverOperator(oracle, state_preparation) for _ in range(2**power): circuit.compose(grover_op, inplace=True) circuits += [circuit] actual_circuits = qae.construct_circuits(problem, measurement=False) for actual, expected in zip(actual_circuits, circuits): self.assertEqual(Operator(actual), Operator(expected)) @ddt class TestSineIntegral(QiskitAlgorithmsTestCase): """Tests based on the A operator to integrate sin^2(x). This class tests * the estimation result * the confidence intervals """ def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self._statevector = QuantumInstance( backend=BasicAer.get_backend("statevector_simulator"), seed_simulator=123, seed_transpiler=41, ) self._sampler = Sampler(options={"seed": 123}) def qasm(shots=100): with self.assertWarns(DeprecationWarning): qi = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=7192, seed_transpiler=90000, ) return qi self._qasm = qasm def sampler_shots(shots=100): return Sampler(options={"shots": shots, "seed": 7192}) self._sampler_shots = sampler_shots @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.270290}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.272675}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.272082}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.272082}], ] ) @unpack def test_statevector(self, n, qae, expect): """Statevector end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # result = qae.run(self._statevector) result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2702}], [4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.2725}], [3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2721}], [3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.2792}], ] ) @unpack def test_sampler(self, n, qae, expect): """sampler end-to-end test""" # construct factories for A and Q # qae.state_preparation = SineIntegral(n) qae.sampler = self._sampler estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 100, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.281196}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.256878}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.271790}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.274168}], ] ) @unpack def test_qasm(self, n, shots, qae, expect): """QASM simulator end-to-end test.""" estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [4, 1000, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2636}], [3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.2904}], [3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.2706}], [3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.2764}], ] ) @unpack def test_sampler_with_shots(self, n, shots, qae, expect): """Sampler with shots end-to-end test.""" # construct factories for A and Q qae.sampler = self._sampler_shots(shots) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) result = qae.estimate(estimation_problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" ) @idata( [ [ AmplitudeEstimation(3), "mle", { "likelihood_ratio": (0.2494734, 0.3003771), "fisher": (0.2486176, 0.2999286), "observed_fisher": (0.2484562, 0.3000900), }, ], [ MaximumLikelihoodAmplitudeEstimation(3), "estimation", { "likelihood_ratio": (0.2598794, 0.2798536), "fisher": (0.2584889, 0.2797018), "observed_fisher": (0.2659279, 0.2722627), }, ], ] ) @unpack def test_confidence_intervals(self, qae, key, expect): """End-to-end test for all confidence intervals.""" n = 3 estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._statevector # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() methods = ["lr", "fi", "oi"] # short for likelihood_ratio, fisher, observed_fisher alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector for alpha, method in zip(alphas, methods): confint = qae.compute_confidence_interval(result, alpha, method) # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], getattr(result, key)) # qasm simulator shots = 100 alpha = 0.01 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) for method, expected_confint in expect.items(): confint = qae.compute_confidence_interval(result, alpha, method) np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= getattr(result, key) <= confint[1]) def test_iqae_confidence_intervals(self): """End-to-end test for the IQAE confidence interval.""" n = 3 expected_confint = (0.1984050, 0.3511015) estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) with self.assertWarns(DeprecationWarning): qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector) # statevector simulator result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() confint = result.confidence_interval # confidence interval based on statevector should be empty, as we are sure of the result self.assertAlmostEqual(confint[1] - confint[0], 0.0) self.assertAlmostEqual(confint[0], result.estimation) # qasm simulator shots = 100 with self.assertWarns(DeprecationWarning): qae.quantum_instance = self._qasm(shots) result = qae.estimate(estimation_problem) confint = result.confidence_interval np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= result.estimation <= confint[1]) class TestAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for canonical AE.""" def test_warns_if_good_state_set(self): """Check AE warns if is_good_state is set.""" circuit = QuantumCircuit(1) problem = EstimationProblem(circuit, objective_qubits=[0], is_good_state=lambda x: True) qae = AmplitudeEstimation(num_eval_qubits=1, sampler=Sampler()) with self.assertWarns(Warning): _ = qae.estimate(problem) @ddt class TestFasterAmplitudeEstimation(QiskitAlgorithmsTestCase): """Specific tests for Faster AE.""" def setUp(self): super().setUp() self._sampler = Sampler(options={"seed": 2}) def test_rescaling(self): """Test the rescaling.""" amplitude = 0.8 scaling = 0.25 circuit = QuantumCircuit(1) circuit.ry(2 * np.arcsin(amplitude), 0) problem = EstimationProblem(circuit, objective_qubits=[0]) rescaled = problem.rescale(scaling) rescaled_amplitude = Statevector.from_instruction(rescaled.state_preparation).data[3] self.assertAlmostEqual(scaling * amplitude, rescaled_amplitude) def test_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_sampler_run_without_rescaling(self): """Run Faster AE without rescaling if the amplitude is in [0, 1/4].""" # construct estimation problem prob = 0.11 a_op = QuantumCircuit(1) a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0) problem = EstimationProblem(a_op, objective_qubits=[0]) # construct algo without rescaling fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, sampler=self._sampler) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, prob, places=2) # assert no rescaling was used theta = np.mean(result.theta_intervals[-1]) value_without_scaling = np.sin(theta) ** 2 self.assertAlmostEqual(result.estimation, value_without_scaling) def test_rescaling_with_custom_grover_raises(self): """Test that the rescaling option fails if a custom Grover operator is used.""" prob = 0.8 a_op = BernoulliStateIn(prob) q_op = BernoulliGrover(prob) problem = EstimationProblem(a_op, objective_qubits=[0], grover_operator=q_op) # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.1, 1, quantum_instance=backend) # run the algo with self.assertWarns(Warning): _ = fae.estimate(problem) @data(("statevector_simulator", 0.2), ("qasm_simulator", 0.199440)) @unpack def test_good_state(self, backend_str, expect): """Test with a good state function.""" def is_good_state(bitstr): return bitstr[1] == "1" # construct the estimation problem where the second qubit is ignored a_op = QuantumCircuit(2) a_op.ry(2 * np.arcsin(np.sqrt(0.2)), 0) # oracle only affects first qubit oracle = QuantumCircuit(2) oracle.z(0) # reflect only on first qubit q_op = GroverOperator(oracle, a_op, reflection_qubits=[0]) # but we measure both qubits (hence both are objective qubits) problem = EstimationProblem( a_op, objective_qubits=[0, 1], grover_operator=q_op, is_good_state=is_good_state ) # construct algo with self.assertWarns(DeprecationWarning): backend = QuantumInstance( BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2 ) # cannot use rescaling with a custom grover operator with self.assertWarns(DeprecationWarning): fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend) # run the algo result = fae.estimate(problem) # assert the result is correct self.assertAlmostEqual(result.estimation, expect, places=5) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" import unittest from typing import Tuple, Union from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit_algorithms import eval_observables from qiskit import BasicAer, QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, X, Z, I, ExpectationFactory, OperatorBase, ExpectationBase, StateFn, ) from qiskit.utils import QuantumInstance, algorithm_globals @ddt class TestAuxOpsEvaluator(QiskitAlgorithmsTestCase): """Tests evaluator of auxiliary operators for algorithms.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed with self.assertWarns(DeprecationWarning): self.h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) self.threshold = 1e-8 self.backend_names = ["statevector_simulator", "qasm_simulator"] def get_exact_expectation(self, ansatz: QuantumCircuit, observables: ListOrDict[OperatorBase]): """ Calculates the exact expectation to be used as an expected result for unit tests. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables # the exact value is a list of (mean, variance) where we expect 0 variance exact = [ (Statevector(ansatz).expectation_value(observable), 0) for observable in observables_list ] if isinstance(observables, dict): return dict(zip(observables.keys(), exact)) return exact def _run_test( self, expected_result: ListOrDict[Tuple[complex, complex]], quantum_state: Union[QuantumCircuit, Statevector], decimal: int, expectation: ExpectationBase, observables: ListOrDict[OperatorBase], quantum_instance: Union[QuantumInstance, Backend], ): with self.assertWarns(DeprecationWarning): result = eval_observables( quantum_instance, quantum_state, observables, expectation, self.threshold ) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) np.testing.assert_array_almost_equal( list(result.values()), list(expected_result.values()), decimal=decimal ) else: np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) @data( [ PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), PauliSumOp.from_list([("II", 2.0)]), ], [ PauliSumOp.from_list([("ZZ", 2.0)]), ], { "op1": PauliSumOp.from_list([("II", 2.0)]), "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), }, { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, ) def test_eval_observables(self, observables: ListOrDict[OperatorBase]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) expected_result = self.get_exact_expectation(bound_ansatz, observables) for backend_name in self.backend_names: shots = 4096 if backend_name == "qasm_simulator" else 1 decimal = ( 1 if backend_name == "qasm_simulator" else 6 ) # to accommodate for qasm being imperfect with self.subTest(msg=f"Test {backend_name} backend."): backend = BasicAer.get_backend(backend_name) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=self.seed, seed_transpiler=self.seed, ) expectation = ExpectationFactory.build( operator=self.h2_op, backend=quantum_instance, ) with self.subTest(msg="Test QuantumCircuit."): self._run_test( expected_result, bound_ansatz, decimal, expectation, observables, quantum_instance, ) with self.subTest(msg="Test QuantumCircuit with Backend."): self._run_test( expected_result, bound_ansatz, decimal, expectation, observables, backend, ) with self.subTest(msg="Test Statevector."): statevector = Statevector(bound_ansatz) self._run_test( expected_result, statevector, decimal, expectation, observables, quantum_instance, ) with self.assertWarns(DeprecationWarning): with self.subTest(msg="Test StateFn."): statefn = StateFn(bound_ansatz) self._run_test( expected_result, statefn, decimal, expectation, observables, quantum_instance, ) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Providers that support BackendV1 interface""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_algorithms import VQE, Grover, AmplificationProblem from qiskit.opflow import X, Z, I from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import TwoLocal, EfficientSU2 from qiskit.utils.mitigation import CompleteMeasFitter class TestBackendV1(QiskitAlgorithmsTestCase): """test BackendV1 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = self._provider.get_backend("fake_qasm_simulator") self.seed = 50 def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") with self.assertWarns(DeprecationWarning): h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) qasm_simulator = QuantumInstance( self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed ) with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_vigo"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_vigo") backend._configuration.max_experiments = 1 with self.assertWarns(DeprecationWarning): qi = QuantumInstance(backend, seed_simulator=12, seed_transpiler=32) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_measurement_error_mitigation_with_vqe(self): """measurement error mitigation test with vqe""" try: from qiskit.providers.aer import noise except ImportError as ex: self.skipTest(f"Package doesn't appear to be installed. Error: '{str(ex)}'") return algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) backend = self._qasm with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, ) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Providers that support BackendV2 interface""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendSimple from qiskit.utils import QuantumInstance from qiskit_algorithms import VQE, Grover, AmplificationProblem from qiskit.opflow import X, Z, I from qiskit_algorithms.optimizers import SPSA from qiskit.circuit.library import TwoLocal class TestBackendV2(QiskitAlgorithmsTestCase): """test BackendV2 interface""" def setUp(self): super().setUp() self._provider = FakeProvider() self._qasm = FakeBackendSimple() self.seed = 50 def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") with self.assertWarns(DeprecationWarning): h2_op = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) qasm_simulator = QuantumInstance( self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed ) with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, max_evals_grouped=1, quantum_instance=qasm_simulator, ) result = vqe.compute_minimum_eigenvalue(operator=h2_op) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_yorktown") backend._configuration.max_experiments = 1 with self.assertWarns(DeprecationWarning): qi = QuantumInstance( self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 ) with self.assertWarns(DeprecationWarning): grover = Grover(quantum_instance=qi) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Grover's algorithm.""" import itertools import unittest from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import data, ddt, idata, unpack from qiskit import BasicAer, QuantumCircuit from qiskit_algorithms import AmplificationProblem, Grover from qiskit.circuit.library import GroverOperator, PhaseOracle from qiskit.primitives import Sampler from qiskit.quantum_info import Operator, Statevector from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.utils.optionals import HAS_TWEEDLEDUM @ddt class TestAmplificationProblem(QiskitAlgorithmsTestCase): """Test the amplification problem.""" def setUp(self): super().setUp() oracle = QuantumCircuit(2) oracle.cz(0, 1) self._expected_grover_op = GroverOperator(oracle=oracle) @data("oracle_only", "oracle_and_stateprep") def test_groverop_getter(self, kind): """Test the default construction of the Grover operator.""" oracle = QuantumCircuit(2) oracle.cz(0, 1) if kind == "oracle_only": problem = AmplificationProblem(oracle, is_good_state=["11"]) expected = GroverOperator(oracle) else: stateprep = QuantumCircuit(2) stateprep.ry(0.2, [0, 1]) problem = AmplificationProblem( oracle, state_preparation=stateprep, is_good_state=["11"] ) expected = GroverOperator(oracle, stateprep) self.assertEqual(Operator(expected), Operator(problem.grover_operator)) @data("list_str", "list_int", "statevector", "callable") def test_is_good_state(self, kind): """Test is_good_state works on different input types.""" if kind == "list_str": is_good_state = ["01", "11"] elif kind == "list_int": is_good_state = [1] # means bitstr[1] == '1' elif kind == "statevector": is_good_state = Statevector(np.array([0, 1, 0, 1]) / np.sqrt(2)) else: def is_good_state(bitstr): # same as ``bitstr in ['01', '11']`` return bitstr[1] == "1" possible_states = [ "".join(list(map(str, item))) for item in itertools.product([0, 1], repeat=2) ] oracle = QuantumCircuit(2) problem = AmplificationProblem(oracle, is_good_state=is_good_state) expected = [state in ["01", "11"] for state in possible_states] actual = [problem.is_good_state(state) for state in possible_states] self.assertListEqual(expected, actual) @ddt class TestGrover(QiskitAlgorithmsTestCase): """Test for the functionality of Grover""" def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): self.statevector = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 ) self.qasm = QuantumInstance( BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 ) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_implicit_phase_oracle_is_good_state(self, use_sampler): """Test implicit default for is_good_state with PhaseOracle.""" grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["shots", False], [[1, 2, 3], None, 2])) @unpack def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None])) @unpack def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) with self.assertRaisesRegex( TypeError, "An is_good_state function is required with the provided oracle" ): if not use_sampler: with self.assertWarns(DeprecationWarning): grover.amplify(problem) else: grover.amplify(problem) @data("ideal", "shots", False) def test_iterator(self, use_sampler): """Test running the algorithm on an iterator.""" # step-function iterator def iterator(): wait, value, count = 3, 1, 0 while True: yield value count += 1 if count % wait == 0: value += 1 grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) def test_max_num_iterations(self, use_sampler): """Test the iteration stops when the maximum number of iterations is reached.""" def zero(): while True: yield 0 grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @data("ideal", "shots", False) def test_max_power(self, use_sampler): """Test the iteration stops when the maximum power is reached.""" lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) def test_run_circuit_oracle(self, use_sampler): """Test execution with a quantum circuit oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_state_vector_oracle(self, use_sampler): """Test execution with a state vector oracle""" mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) def test_run_custom_grover_operator(self, use_sampler): """Test execution with a grover operator oracle""" oracle = QuantumCircuit(2) oracle.cz(0, 1) grover_op = GroverOperator(oracle) problem = AmplificationProblem( oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) def test_optimal_num_iterations(self): """Test optimal_num_iterations""" num_qubits = 7 for num_solutions in range(1, 2**num_qubits): amplitude = np.sqrt(num_solutions / 2**num_qubits) expected = round(np.arccos(amplitude) / (2 * np.arcsin(amplitude))) actual = Grover.optimal_num_iterations(num_solutions, num_qubits) self.assertEqual(actual, expected) def test_construct_circuit(self): """Test construct_circuit""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = Grover() constructed = grover.construct_circuit(problem, 2, measurement=False) grover_op = GroverOperator(oracle) expected = QuantumCircuit(2) expected.h([0, 1]) expected.compose(grover_op.power(2), inplace=True) self.assertTrue(Operator(constructed).equiv(Operator(expected))) @data("ideal", "shots", False) def test_circuit_result(self, use_sampler): """Test circuit_result""" oracle = QuantumCircuit(2) oracle.cz(0, 1) # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): keys, values = zip(*sorted(dist.items())) if i in (0, 3): self.assertTupleEqual(keys, ("11",)) np.testing.assert_allclose(values, [1], atol=0.2) else: self.assertTupleEqual(keys, ("00", "01", "10", "11")) np.testing.assert_allclose(values, [0.25, 0.25, 0.25, 0.25], atol=0.2) else: expected_results = [ {"11": 1024}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"00": 238, "01": 253, "10": 263, "11": 270}, {"11": 1024}, ] self.assertEqual(result.circuit_results, expected_results) @data("ideal", "shots", False) def test_max_probability(self, use_sampler): """Test max_probability""" oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @data("ideal", "shots", False) def test_oracle_evaluation(self, use_sampler): """Test oracle_evaluation for PhaseOracle""" oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) if not use_sampler: with self.assertWarns(DeprecationWarning): result = grover.amplify(problem) else: result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) def test_sampler_setter(self): """Test sampler setter""" grover = Grover() grover.sampler = self._sampler self.assertEqual(grover.sampler, self._sampler) def _prepare_grover( self, use_sampler, iterations=None, growth_rate=None, sample_from_iterations=False ): """Prepare Grover instance for test""" if use_sampler == "ideal": grover = Grover( sampler=self._sampler, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) elif use_sampler == "shots": grover = Grover( sampler=self._sampler_with_shots, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) else: with self.assertWarns(DeprecationWarning): grover = Grover( quantum_instance=self.qasm, iterations=iterations, growth_rate=growth_rate, sample_from_iterations=sample_from_iterations, ) return grover if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Measurement Error Mitigation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np import rustworkx as rx from qiskit import QuantumCircuit, execute from qiskit.quantum_info import Pauli from qiskit.exceptions import QiskitError from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_algorithms import VQE, QAOA from qiskit.opflow import I, X, Z, PauliSumOp from qiskit_algorithms.optimizers import SPSA, COBYLA from qiskit.circuit.library import EfficientSU2 from qiskit.utils.mitigation import CompleteMeasFitter, TensoredMeasFitter from qiskit.utils.measurement_error_mitigation import build_measurement_error_mitigation_circuits from qiskit.utils import optionals if optionals.HAS_AER: # pylint: disable=no-name-in-module from qiskit import Aer from qiskit.providers.aer import noise if optionals.HAS_IGNIS: # pylint: disable=no-name-in-module from qiskit.ignis.mitigation.measurement import ( CompleteMeasFitter as CompleteMeasFitter_IG, TensoredMeasFitter as TensoredMeasFitter_IG, ) @ddt class TestMeasurementErrorMitigation(QiskitAlgorithmsTestCase): """Test measurement error mitigation.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @data( ("CompleteMeasFitter", None, False), ("TensoredMeasFitter", None, False), ("TensoredMeasFitter", [[0, 1]], True), ("TensoredMeasFitter", [[1], [0]], False), ) @unpack def test_measurement_error_mitigation_with_diff_qubit_order( self, fitter_str, mit_pattern, fails, ): """measurement error mitigation with different qubit order""" algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=1679, seed_transpiler=167, shots=1000, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, cals_matrix_refresh_period=0, mit_pattern=mit_pattern, ) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure(0, 0) qc1.measure(1, 1) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.cx(0, 1) qc2.measure(1, 0) qc2.measure(0, 1) with self.assertWarns(DeprecationWarning): if fails: self.assertRaisesRegex( QiskitError, "Each element in the mit pattern should have length 1.", quantum_instance.execute, [qc1, qc2], ) else: quantum_instance.execute([qc1, qc2]) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() # failure case qc3 = QuantumCircuit(3, 3) qc3.h(2) qc3.cx(1, 2) qc3.measure(2, 1) qc3.measure(1, 2) with self.assertWarns(DeprecationWarning): self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @data(("CompleteMeasFitter", None), ("TensoredMeasFitter", [[0], [1]])) def test_measurement_error_mitigation_with_vqe(self, config): """measurement error mitigation test with vqe""" fitter_str, mit_pattern = config algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, mit_pattern=mit_pattern, ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarns(DeprecationWarning): h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] with self.assertWarns(DeprecationWarning): return PauliSumOp.from_list(opflow_list), shift @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_measurement_error_mitigation_qaoa(self): """measurement error mitigation test with QAOA""" algorithm_globals.random_seed = 167 backend = Aer.get_backend("aer_simulator") w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) initial_point = np.asarray([0.0, 0.0]) # Compute first without noise with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) with self.assertWarns(DeprecationWarning): qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, initial_point=initial_point, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) ref_eigenvalue = result.eigenvalue.real # compute with noise # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, noise_model=noise_model, measurement_error_mitigation_cls=CompleteMeasFitter, shots=10000, ) with self.assertWarns(DeprecationWarning): qaoa = QAOA( optimizer=COBYLA(maxiter=3), quantum_instance=quantum_instance, initial_point=initial_point, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertAlmostEqual(result.eigenvalue.real, ref_eigenvalue, delta=0.05) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") @data("CompleteMeasFitter", "TensoredMeasFitter") def test_measurement_error_mitigation_with_diff_qubit_order_ignis(self, fitter_str): """measurement error mitigation with different qubit order""" algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=1679, seed_transpiler=167, shots=1000, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, cals_matrix_refresh_period=0, ) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure(0, 0) qc1.measure(1, 1) qc2 = QuantumCircuit(2, 2) qc2.h(0) qc2.cx(0, 1) qc2.measure(1, 0) qc2.measure(0, 1) if fitter_cls == TensoredMeasFitter_IG: with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): self.assertRaisesRegex( QiskitError, "TensoredMeasFitter doesn't support subset_fitter.", quantum_instance.execute, [qc1, qc2], ) else: # this should run smoothly with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): quantum_instance.execute([qc1, qc2]) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() # failure case qc3 = QuantumCircuit(3, 3) qc3.h(2) qc3.cx(1, 2) qc3.measure(2, 1) qc3.measure(1, 2) self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") @data(("CompleteMeasFitter", None), ("TensoredMeasFitter", [[0], [1]])) def test_measurement_error_mitigation_with_vqe_ignis(self, config): """measurement error mitigation test with vqe""" fitter_str, mit_pattern = config algorithm_globals.random_seed = 0 # build noise model noise_model = noise.NoiseModel() read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) fitter_cls = ( CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( backend=backend, seed_simulator=167, seed_transpiler=167, noise_model=noise_model, measurement_error_mitigation_cls=fitter_cls, mit_pattern=mit_pattern, ) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) + 0.39793742484318045 * (I ^ Z) - 0.39793742484318045 * (Z ^ I) - 0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 * (X ^ X) ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) with self.assertWarnsRegex(DeprecationWarning): vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @unittest.skipUnless(optionals.HAS_IGNIS, "qiskit-ignis is required to run this test") def test_calibration_results(self): """check that results counts are the same with/without error mitigation""" algorithm_globals.random_seed = 1679 np.random.seed(algorithm_globals.random_seed) qc = QuantumCircuit(1) qc.x(0) qc_meas = qc.copy() qc_meas.measure_all() backend = Aer.get_backend("aer_simulator") counts_array = [None, None] for idx, is_use_mitigation in enumerate([True, False]): with self.assertWarns(DeprecationWarning): if is_use_mitigation: quantum_instance = QuantumInstance( backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, measurement_error_mitigation_cls=CompleteMeasFitter_IG, ) with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() else: quantum_instance = QuantumInstance( backend, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, ) counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() self.assertEqual( counts_array[0], counts_array[1], msg="Counts different with/without fitter." ) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_circuit_modified(self): """tests that circuits don't get modified on QI execute with error mitigation as per issue #7449 """ algorithm_globals.random_seed = 1679 np.random.seed(algorithm_globals.random_seed) circuit = QuantumCircuit(1) circuit.x(0) circuit.measure_all() with self.assertWarns(DeprecationWarning): qi = QuantumInstance( Aer.get_backend("aer_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, shots=1024, measurement_error_mitigation_cls=CompleteMeasFitter, ) # The error happens on transpiled circuits since "execute" was changing the input array # Non transpiled circuits didn't have a problem because a new transpiled array was created # internally. circuits_ref = qi.transpile(circuit) # always returns a new array circuits_input = circuits_ref.copy() with self.assertWarns(DeprecationWarning): _ = qi.execute(circuits_input, had_transpiled=True) self.assertEqual(circuits_ref, circuits_input, msg="Transpiled circuit array modified.") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_tensor_subset_fitter(self): """Test the subset fitter method of the tensor fitter.""" # Construct a noise model where readout has errors of different strengths. noise_model = noise.NoiseModel() # big error read_err0 = noise.errors.readout_error.ReadoutError([[0.90, 0.10], [0.25, 0.75]]) # ideal read_err1 = noise.errors.readout_error.ReadoutError([[1.00, 0.00], [0.00, 1.00]]) # small error read_err2 = noise.errors.readout_error.ReadoutError([[0.98, 0.02], [0.03, 0.97]]) noise_model.add_readout_error(read_err0, (0,)) noise_model.add_readout_error(read_err1, (1,)) noise_model.add_readout_error(read_err2, (2,)) mit_pattern = [[idx] for idx in range(3)] backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=123) with self.assertWarns(DeprecationWarning): mit_circuits = build_measurement_error_mitigation_circuits( [0, 1, 2], TensoredMeasFitter, backend, backend_config={}, compile_config={}, mit_pattern=mit_pattern, ) result = execute(mit_circuits[0], backend, noise_model=noise_model).result() fitter = TensoredMeasFitter(result, mit_pattern=mit_pattern) cal_matrices = fitter.cal_matrices # Check that permutations and permuted subsets match. for subset in [[1, 0], [1, 2], [0, 2], [2, 0, 1]]: with self.subTest(subset=subset): with self.assertWarns(DeprecationWarning): new_fitter = fitter.subset_fitter(subset) for idx, qubit in enumerate(subset): self.assertTrue(np.allclose(new_fitter.cal_matrices[idx], cal_matrices[qubit])) self.assertRaisesRegex( QiskitError, "Qubit 3 is not in the mit pattern", fitter.subset_fitter, [0, 2, 3], ) # Test that we properly correct a circuit with permuted measurements. circuit = QuantumCircuit(3, 3) circuit.x(range(3)) circuit.measure(1, 0) circuit.measure(2, 1) circuit.measure(0, 2) result = execute( circuit, backend, noise_model=noise_model, shots=1000, seed_simulator=0 ).result() with self.subTest(subset=subset): with self.assertWarns(DeprecationWarning): new_result = fitter.subset_fitter([1, 2, 0]).filter.apply(result) # The noisy result should have a poor 111 state, the mit. result should be good. self.assertTrue(result.get_counts()["111"] < 800) self.assertTrue(new_result.get_counts()["111"] > 990) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" from __future__ import annotations import unittest from typing import Tuple from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit_algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit_algorithms import estimate_observables from qiskit.primitives import Estimator from qiskit.quantum_info import Statevector, SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.utils import algorithm_globals @ddt class TestObservablesEvaluator(QiskitAlgorithmsTestCase): """Tests evaluator of auxiliary operators for algorithms.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.threshold = 1e-8 def get_exact_expectation( self, ansatz: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp] ): """ Calculates the exact expectation to be used as an expected result for unit tests. """ if isinstance(observables, dict): observables_list = list(observables.values()) else: observables_list = observables # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and # 0 shots exact = [ (Statevector(ansatz).expectation_value(observable), {}) for observable in observables_list ] if isinstance(observables, dict): return dict(zip(observables.keys(), exact)) return exact def _run_test( self, expected_result: ListOrDict[Tuple[complex, complex]], quantum_state: QuantumCircuit, decimal: int, observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): result = estimate_observables(estimator, quantum_state, observables, None, self.threshold) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) means = [element[0] for element in result.values()] expected_means = [element[0] for element in expected_result.values()] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result.values()] expected_vars_and_shots = [element[1] for element in expected_result.values()] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) else: means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) @data( [ PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), PauliSumOp.from_list([("II", 2.0)]), ], [ PauliSumOp.from_list([("ZZ", 2.0)]), ], { "op1": PauliSumOp.from_list([("II", 2.0)]), "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), }, { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, [], {}, ) def test_estimate_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) states = bound_ansatz expected_result = self.get_exact_expectation(bound_ansatz, observables) estimator = Estimator() decimal = 6 self._run_test( expected_result, states, decimal, observables, estimator, ) def test_estimate_observables_zero_op(self): """Tests if a zero operator is handled correctly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] result = estimate_observables(estimator, state, observables, None, self.threshold) expected_result = [(0.015607318055509564, {}), (0.0, {})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) def test_estimate_observables_shots(self): """Tests that variances and shots are returned properly.""" ansatz = EfficientSU2(2) parameters = np.array( [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], dtype=float, ) bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator(options={"shots": 2048}) with self.assertWarns(DeprecationWarning): observables = [PauliSumOp.from_list([("ZZ", 2.0)])] result = estimate_observables(estimator, state, observables, None, self.threshold) exact_result = self.get_exact_expectation(bound_ansatz, observables) expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) vars_and_shots = [element[1] for element in result] expected_vars_and_shots = [element[1] for element in expected_result] for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance"), expected.pop("variance"), 2) self.assertEqual(computed.pop("shots"), expected.pop("shots")) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test phase estimation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from qiskit.circuit.library import ZGate, XGate, HGate, IGate from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector, Operator from qiskit.synthesis import MatrixExponential, SuzukiTrotter from qiskit.primitives import Sampler from qiskit_algorithms import PhaseEstimationScale from qiskit_algorithms.phase_estimators import ( PhaseEstimation, HamiltonianPhaseEstimation, IterativePhaseEstimation, ) import qiskit from qiskit import QuantumCircuit from qiskit.opflow import ( H, X, Y, Z, I, StateFn, PauliTrotterEvolution, MatrixEvolution, PauliSumOp, ) from qiskit.test import slow_test @ddt class TestHamiltonianPhaseEstimation(QiskitAlgorithmsTestCase): """Tests for obtaining eigenvalues from phase estimation""" def hamiltonian_pe( self, hamiltonian, state_preparation=None, num_evaluation_qubits=6, backend=None, evolution=None, bound=None, ): """Run HamiltonianPhaseEstimation and return result with all phases.""" if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = HamiltonianPhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance ) result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) return result @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 4)) def test_pauli_sum_1(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Z state_preparation = StateFn(H.to_circuit()) result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.162, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.125, delta=0.001) self.assertAlmostEqual(phases[1], 1.125, delta=0.001) @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 3)) def test_pauli_sum_2(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Y + Z state_preparation = None result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.1, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.484, delta=0.001) self.assertAlmostEqual(phases[1], 1.484, delta=0.001) def test_single_pauli_op(self): """Two eigenvalues from Pauli sum with X, Y, Z""" hamiltonian = Z state_preparation = None with self.assertWarns(DeprecationWarning): result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=None) eigv = result.most_likely_eigenvalue with self.subTest("First eigenvalue"): self.assertAlmostEqual(eigv, 1.0, delta=0.001) with self.assertWarns(DeprecationWarning): state_preparation = StateFn(X.to_circuit()) result = self.hamiltonian_pe(hamiltonian, state_preparation, bound=1.05) eigv = result.most_likely_eigenvalue with self.subTest("Second eigenvalue"): self.assertAlmostEqual(eigv, -0.98, delta=0.01) @slow_test def test_H2_hamiltonian(self): """Test H2 hamiltonian""" with self.assertWarns(DeprecationWarning): hamiltonian = ( (-1.0523732457728587 * (I ^ I)) + (0.3979374248431802 * (I ^ Z)) + (-0.3979374248431802 * (Z ^ I)) + (-0.011280104256235324 * (Z ^ Z)) + (0.18093119978423147 * (X ^ X)) ) state_preparation = StateFn((I ^ H).to_circuit()) evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4) with self.assertWarns(DeprecationWarning): result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001) with self.subTest("Most likely phase"): self.assertAlmostEqual(result.phase, 0.5937, delta=0.001) with self.subTest("All eigenvalues"): phase_dict = result.filter_phases(0.1) phases = list(phase_dict.keys()) self.assertAlmostEqual(phases[0], -0.8979, delta=0.001) self.assertAlmostEqual(phases[1], -1.8551, delta=0.001) self.assertAlmostEqual(phases[2], -1.2376, delta=0.001) def test_matrix_evolution(self): """1Q Hamiltonian with MatrixEvolution""" with self.assertWarns(DeprecationWarning): hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I) state_preparation = None result = self.hamiltonian_pe( hamiltonian, state_preparation, evolution=MatrixEvolution() ) phase_dict = result.filter_phases(0.2, as_float=True) phases = list(phase_dict.keys()) self.assertAlmostEqual(phases[0], 1.490, delta=0.001) self.assertAlmostEqual(phases[1], -0.090, delta=0.001) def _setup_from_bound(self, evolution, op_class): with self.assertWarns(DeprecationWarning): hamiltonian = 0.5 * X + Y + Z state_preparation = None bound = 1.2 * sum(abs(hamiltonian.coeff * coeff) for coeff in hamiltonian.coeffs) if op_class == "MatrixOp": hamiltonian = hamiltonian.to_matrix_op() backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) result = phase_est.estimate( hamiltonian=hamiltonian, bound=bound, evolution=evolution, state_preparation=state_preparation, ) return result def test_from_bound(self): """HamiltonianPhaseEstimation with bound""" with self.assertWarns(DeprecationWarning): for op_class in ("SummedOp", "MatrixOp"): result = self._setup_from_bound(MatrixEvolution(), op_class) cutoff = 0.01 phases = result.filter_phases(cutoff) with self.subTest(f"test phases has the correct length: {op_class}"): self.assertEqual(len(phases), 2) with self.subTest(f"test scaled phases are correct: {op_class}"): self.assertEqual(list(phases.keys()), [1.5, -1.5]) phases = result.filter_phases(cutoff, scaled=False) with self.subTest(f"test unscaled phases are correct: {op_class}"): self.assertEqual(list(phases.keys()), [0.25, 0.75]) def test_trotter_from_bound(self): """HamiltonianPhaseEstimation with bound and Trotterization""" with self.assertWarns(DeprecationWarning): result = self._setup_from_bound( PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp" ) phase_dict = result.filter_phases(0.1) phases = list(phase_dict.keys()) with self.subTest("test phases has the correct length"): self.assertEqual(len(phases), 2) with self.subTest("test phases has correct values"): self.assertAlmostEqual(phases[0], 1.5, delta=0.001) self.assertAlmostEqual(phases[1], -1.5, delta=0.001) # sampler tests def hamiltonian_pe_sampler( self, hamiltonian, state_preparation=None, num_evaluation_qubits=6, evolution=None, bound=None, uses_opflow=True, ): """Run HamiltonianPhaseEstimation and return result with all phases.""" sampler = Sampler() phase_est = HamiltonianPhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, sampler=sampler ) if uses_opflow: with self.assertWarns(DeprecationWarning): result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) else: result = phase_est.estimate( hamiltonian=hamiltonian, state_preparation=state_preparation, evolution=evolution, bound=bound, ) return result @data(MatrixExponential(), SuzukiTrotter(reps=4)) def test_pauli_sum_1_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)])) state_preparation = QuantumCircuit(1).compose(HGate()) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.162, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.125, delta=0.001) self.assertAlmostEqual(phases[1], 1.125, delta=0.001) @data(MatrixExponential(), SuzukiTrotter(reps=3)) def test_pauli_sum_2_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)])) state_preparation = None result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.1, as_float=True) phases = list(phase_dict.keys()) phases.sort() self.assertAlmostEqual(phases[0], -1.484, delta=0.001) self.assertAlmostEqual(phases[1], 1.484, delta=0.001) def test_single_pauli_op_sampler(self): """Two eigenvalues from Pauli sum with X, Y, Z""" hamiltonian = SparsePauliOp(Pauli("Z")) state_preparation = None result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, evolution=None, uses_opflow=False ) eigv = result.most_likely_eigenvalue with self.subTest("First eigenvalue"): self.assertAlmostEqual(eigv, 1.0, delta=0.001) state_preparation = QuantumCircuit(1).compose(XGate()) result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, bound=1.05, uses_opflow=False ) eigv = result.most_likely_eigenvalue with self.subTest("Second eigenvalue"): self.assertAlmostEqual(eigv, -0.98, delta=0.01) @data( Statevector(QuantumCircuit(2).compose(IGate()).compose(HGate())), QuantumCircuit(2).compose(IGate()).compose(HGate()), ) def test_H2_hamiltonian_sampler(self, state_preparation): """Test H2 hamiltonian""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp( SparsePauliOp.from_list( [ ("II", -1.0523732457728587), ("IZ", 0.3979374248431802), ("ZI", -0.3979374248431802), ("ZZ", -0.011280104256235324), ("XX", 0.18093119978423147), ] ) ) evo = SuzukiTrotter(reps=4) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001) with self.subTest("Most likely phase"): self.assertAlmostEqual(result.phase, 0.5937, delta=0.001) with self.subTest("All eigenvalues"): phase_dict = result.filter_phases(0.1) phases = sorted(phase_dict.keys()) self.assertAlmostEqual(phases[0], -1.8551, delta=0.001) self.assertAlmostEqual(phases[1], -1.2376, delta=0.001) self.assertAlmostEqual(phases[2], -0.8979, delta=0.001) def test_matrix_evolution_sampler(self): """1Q Hamiltonian with MatrixEvolution""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)])) state_preparation = None result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, evolution=MatrixExponential() ) phase_dict = result.filter_phases(0.2, as_float=True) phases = sorted(phase_dict.keys()) self.assertAlmostEqual(phases[0], -0.090, delta=0.001) self.assertAlmostEqual(phases[1], 1.490, delta=0.001) @ddt class TestPhaseEstimation(QiskitAlgorithmsTestCase): """Evolution tests.""" def one_phase( self, unitary_circuit, state_preparation=None, backend_type=None, phase_estimator=None, num_iterations=6, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return the estimated phase as a value in :math:`[0,1)`. """ if backend_type is None: backend_type = "qasm_simulator" backend = qiskit.BasicAer.get_backend(backend_type) if phase_estimator is None: phase_estimator = IterativePhaseEstimation with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) elif phase_estimator == PhaseEstimation: p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) else: raise ValueError("Unrecognized phase_estimator") result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) phase = result.phase return phase @data( (X.to_circuit(), 0.5, "statevector_simulator", IterativePhaseEstimation), (X.to_circuit(), 0.5, "qasm_simulator", IterativePhaseEstimation), (None, 0.0, "qasm_simulator", IterativePhaseEstimation), (X.to_circuit(), 0.5, "qasm_simulator", PhaseEstimation), (None, 0.0, "qasm_simulator", PhaseEstimation), (X.to_circuit(), 0.5, "statevector_simulator", PhaseEstimation), ) @unpack def test_qpe_Z(self, state_preparation, expected_phase, backend_type, phase_estimator): """eigenproblem Z, |0> and |1>""" unitary_circuit = Z.to_circuit() with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, backend_type=backend_type, phase_estimator=phase_estimator, ) self.assertEqual(phase, expected_phase) @data( (H.to_circuit(), 0.0, IterativePhaseEstimation), ((H @ X).to_circuit(), 0.5, IterativePhaseEstimation), (H.to_circuit(), 0.0, PhaseEstimation), ((H @ X).to_circuit(), 0.5, PhaseEstimation), ) @unpack def test_qpe_X_plus_minus(self, state_preparation, expected_phase, phase_estimator): """eigenproblem X, (|+>, |->)""" unitary_circuit = X.to_circuit() with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, phase_estimator=phase_estimator ) self.assertEqual(phase, expected_phase) @data( (X.to_circuit(), 0.125, IterativePhaseEstimation), (I.to_circuit(), 0.875, IterativePhaseEstimation), (X.to_circuit(), 0.125, PhaseEstimation), (I.to_circuit(), 0.875, PhaseEstimation), ) @unpack def test_qpe_RZ(self, state_preparation, expected_phase, phase_estimator): """eigenproblem RZ, (|0>, |1>)""" alpha = np.pi / 2 unitary_circuit = QuantumCircuit(1) unitary_circuit.rz(alpha, 0) with self.assertWarns(DeprecationWarning): phase = self.one_phase( unitary_circuit, state_preparation, phase_estimator=phase_estimator ) self.assertEqual(phase, expected_phase) def test_check_num_iterations(self): """test check for num_iterations greater than zero""" unitary_circuit = X.to_circuit() state_preparation = None with self.assertRaises(ValueError): self.one_phase(unitary_circuit, state_preparation, num_iterations=-1) def phase_estimation( self, unitary_circuit, state_preparation=None, num_evaluation_qubits=6, backend=None, construct_circuit=False, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return all results """ if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") with self.assertWarns(DeprecationWarning): qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) with self.assertWarns(DeprecationWarning): phase_est = PhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi ) if construct_circuit: pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) else: result = phase_est.estimate( unitary=unitary_circuit, state_preparation=state_preparation ) return result @data(True, False) def test_qpe_Zplus(self, construct_circuit): """superposition eigenproblem Z, |+>""" unitary_circuit = Z.to_circuit() state_preparation = H.to_circuit() # prepare |+> with self.assertWarns(DeprecationWarning): result = self.phase_estimation( unitary_circuit, state_preparation, backend=qiskit.BasicAer.get_backend("statevector_simulator"), construct_circuit=construct_circuit, ) phases = result.filter_phases(1e-15, as_float=True) with self.subTest("test phases has correct values"): self.assertEqual(list(phases.keys()), [0.0, 0.5]) with self.subTest("test phases has correct probabilities"): np.testing.assert_allclose(list(phases.values()), [0.5, 0.5]) with self.subTest("test bitstring representation"): phases = result.filter_phases(1e-15, as_float=False) self.assertEqual(list(phases.keys()), ["000000", "100000"]) # sampler tests def one_phase_sampler( self, unitary_circuit, state_preparation=None, phase_estimator=None, num_iterations=6, shots=None, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return the estimated phase as a value in :math:`[0,1)`. """ if shots is not None: options = {"shots": shots} else: options = {} sampler = Sampler(options=options) if phase_estimator is None: phase_estimator = IterativePhaseEstimation if phase_estimator == IterativePhaseEstimation: p_est = IterativePhaseEstimation(num_iterations=num_iterations, sampler=sampler) elif phase_estimator == PhaseEstimation: p_est = PhaseEstimation(num_evaluation_qubits=6, sampler=sampler) else: raise ValueError("Unrecognized phase_estimator") result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) phase = result.phase return phase @data( (QuantumCircuit(1).compose(XGate()), 0.5, None, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, 1000, IterativePhaseEstimation), (None, 0.0, 1000, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, 1000, PhaseEstimation), (None, 0.0, 1000, PhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.5, None, PhaseEstimation), ) @unpack def test_qpe_Z_sampler(self, state_preparation, expected_phase, shots, phase_estimator): """eigenproblem Z, |0> and |1>""" unitary_circuit = QuantumCircuit(1).compose(ZGate()) phase = self.one_phase_sampler( unitary_circuit, state_preparation=state_preparation, phase_estimator=phase_estimator, shots=shots, ) self.assertEqual(phase, expected_phase) @data( (QuantumCircuit(1).compose(HGate()), 0.0, IterativePhaseEstimation), (QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, IterativePhaseEstimation), (QuantumCircuit(1).compose(HGate()), 0.0, PhaseEstimation), (QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, PhaseEstimation), ) @unpack def test_qpe_X_plus_minus_sampler(self, state_preparation, expected_phase, phase_estimator): """eigenproblem X, (|+>, |->)""" unitary_circuit = QuantumCircuit(1).compose(XGate()) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) @data( (QuantumCircuit(1).compose(XGate()), 0.125, IterativePhaseEstimation), (QuantumCircuit(1).compose(IGate()), 0.875, IterativePhaseEstimation), (QuantumCircuit(1).compose(XGate()), 0.125, PhaseEstimation), (QuantumCircuit(1).compose(IGate()), 0.875, PhaseEstimation), ) @unpack def test_qpe_RZ_sampler(self, state_preparation, expected_phase, phase_estimator): """eigenproblem RZ, (|0>, |1>)""" alpha = np.pi / 2 unitary_circuit = QuantumCircuit(1) unitary_circuit.rz(alpha, 0) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) @data( ((X ^ X).to_circuit(), 0.25, IterativePhaseEstimation), ((I ^ X).to_circuit(), 0.125, IterativePhaseEstimation), ((X ^ X).to_circuit(), 0.25, PhaseEstimation), ((I ^ X).to_circuit(), 0.125, PhaseEstimation), ) @unpack def test_qpe_two_qubit_unitary(self, state_preparation, expected_phase, phase_estimator): """two qubit unitary T ^ T""" unitary_circuit = QuantumCircuit(2) unitary_circuit.t(0) unitary_circuit.t(1) phase = self.one_phase_sampler( unitary_circuit, state_preparation, phase_estimator, ) self.assertEqual(phase, expected_phase) def test_check_num_iterations_sampler(self): """test check for num_iterations greater than zero""" unitary_circuit = QuantumCircuit(1).compose(XGate()) state_preparation = None with self.assertRaises(ValueError): self.one_phase_sampler(unitary_circuit, state_preparation, num_iterations=-1) def test_phase_estimation_scale_from_operator(self): """test that PhaseEstimationScale from_pauli_sum works with Operator""" circ = QuantumCircuit(2) op = Operator(circ) scale = PhaseEstimationScale.from_pauli_sum(op) self.assertEqual(scale._bound, 4.0) def phase_estimation_sampler( self, unitary_circuit, sampler: Sampler, state_preparation=None, num_evaluation_qubits=6, construct_circuit=False, ): """Run phase estimation with operator, eigenvalue pair `unitary_circuit`, `state_preparation`. Return all results """ phase_est = PhaseEstimation(num_evaluation_qubits=num_evaluation_qubits, sampler=sampler) if construct_circuit: pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) else: result = phase_est.estimate( unitary=unitary_circuit, state_preparation=state_preparation ) return result @data(True, False) def test_qpe_Zplus_sampler(self, construct_circuit): """superposition eigenproblem Z, |+>""" unitary_circuit = QuantumCircuit(1).compose(ZGate()) state_preparation = QuantumCircuit(1).compose(HGate()) # prepare |+> sampler = Sampler() result = self.phase_estimation_sampler( unitary_circuit, sampler, state_preparation, construct_circuit=construct_circuit, ) phases = result.filter_phases(1e-15, as_float=True) with self.subTest("test phases has correct values"): self.assertEqual(list(phases.keys()), [0.0, 0.5]) with self.subTest("test phases has correct probabilities"): np.testing.assert_allclose(list(phases.values()), [0.5, 0.5]) with self.subTest("test bitstring representation"): phases = result.filter_phases(1e-15, as_float=False) self.assertEqual(list(phases.keys()), ["000000", "100000"]) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Skip Qobj Validation""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.exceptions import QiskitError def _compare_dict(dict1, dict2): equal = True for key1, value1 in dict1.items(): if key1 not in dict2: equal = False break if value1 != dict2[key1]: equal = False break return equal class TestSkipQobjValidation(QiskitAlgorithmsTestCase): """Test Skip Qobj Validation""" def setUp(self): super().setUp() self.random_seed = 10598 # ┌───┐ ░ ┌─┐ ░ # q0_0: ┤ H ├──■───░─┤M├─░──── # └───┘┌─┴─┐ ░ └╥┘ ░ ┌─┐ # q0_1: ─────┤ X ├─░──╫──░─┤M├ # └───┘ ░ ║ ░ └╥┘ # c0: 2/══════════════╩═════╩═ # 0 1 qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.barrier(qr) qc.measure(qr[1], cr[1]) self.qc = qc self.backend = BasicAer.get_backend("qasm_simulator") def test_wo_backend_options(self): """without backend options test""" with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, ) # run without backend_options and without noise res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation)) def test_w_backend_options(self): """with backend options test""" # run with backend_options with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]}, ) res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation)) def test_w_noise(self): """with noise test""" # build noise model # Asymmetric readout error on qubit-0 only try: from qiskit.providers.aer.noise import NoiseModel from qiskit import Aer self.backend = Aer.get_backend("qasm_simulator") except ImportError as ex: self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return probs_given0 = [0.9, 0.1] probs_given1 = [0.3, 0.7] noise_model = NoiseModel() noise_model.add_readout_error([probs_given0, probs_given1], [0]) with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, seed_simulator=self.random_seed, shots=1024, noise_model=noise_model, ) res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc) quantum_instance.skip_qobj_validation = True res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) with self.assertWarns(DeprecationWarning): # BasicAer should fail: with self.assertRaises(QiskitError): _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model) with self.assertRaises(QiskitError): quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator")) quantum_instance.set_config(noise_model=noise_model) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import qiskit from qiskit.circuit.library import TwoLocal from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.opflow import Z, I from volta.vqd import VQD from volta.utils import classical_solver class TestVQDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="swap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] message = ( "VQD with SWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))" ) self.assertAlmostEqual(want, got, decimal_place, message) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] message = "VQD with SWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))" self.assertAlmostEqual(want, got, decimal_place, message) class TestVQDDSWAP(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() # backend = BasicAer.get_backend("qasm_simulator") backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="dswap", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with DSWAP not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class TestVQDAmplitude(unittest.TestCase): def setUp(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000, seed_simulator=42, seed_transpiler=42, ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1) self.Algo = VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="amplitude", ) self.Algo.run(verbose=0) self.eigenvalues, _ = classical_solver(hamiltonian) def test_energies_0(self): decimal_place = 1 want = self.eigenvalues[0] got = self.Algo.energies[0] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the ground state of 1/2*((Z^I) + (Z^Z))", ) def test_energies_1(self): decimal_place = 1 want = self.eigenvalues[1] got = self.Algo.energies[1] self.assertAlmostEqual( want, got, decimal_place, "VQD with Excitation Amplitude not working for the first excited state of 1/2*((Z^I) + (Z^Z))", ) class VQDRaiseError(unittest.TestCase): def test_not_implemented_overlapping_method(self): optimizer = qiskit.algorithms.optimizers.COBYLA() backend = QuantumInstance( backend=BasicAer.get_backend("qasm_simulator"), shots=50000 ) hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2) with self.assertRaises(NotImplementedError): VQD( hamiltonian=hamiltonian, ansatz=ansatz, n_excited_states=1, beta=1.0, optimizer=optimizer, backend=backend, overlap_method="test", ), if __name__ == "__main__": unittest.main(argv=[""], verbosity=2, exit=False)
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test TrotterQRTE.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from scipy.linalg import expm from numpy.testing import assert_raises from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @ddt class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed @data( ( None, Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data ) @data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t"))) @unpack def test_trotter_qrte_trotter(self, operator, t_param): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" if not t_param is None: operator = SparsePauliOp(operator.paulis, np.array([t_param, 1])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] initial_state = QuantumCircuit(1) time = 3 num_timesteps = 2 evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param ) estimator = Estimator() expected_psi, expected_observables_result = self._get_expected_trotter_qrte( operator, time, num_timesteps, initial_state, aux_ops, t_param, ) expected_evolved_state = Statevector(expected_psi) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_evolved_state.data, ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [ (expected_observables_result[-1][0], {"variance": 0, "shots": 0}), (expected_observables_result[-1][1], {"variance": 0, "shots": 0}), ] means = [element[0] for element in aux_ops_result] expected_means = [element[0] for element in expected_aux_ops_result] np.testing.assert_array_almost_equal(means, expected_means) vars_and_shots = [element[1] for element in aux_ops_result] expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] observables_result = evolution_result.observables expected_observables_result = [ [(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result ] means = [sub_element[0] for element in observables_result for sub_element in element] expected_means = [ sub_element[0] for element in expected_observables_result for sub_element in element ] np.testing.assert_array_almost_equal(means, expected_means) for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2) self.assertEqual(computed.pop("shots", 0), expected["shots"]) @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data ) @data( (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data, ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @data(([Pauli("X"), Pauli("Y")], None)) @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) @data( (X, QuantumCircuit(1)), (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), ( SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])), QuantumCircuit(1), ), ) @unpack def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): """Test TrotterQRTE with raising errors for evolution problem content.""" self._run_error_test(initial_state, operator, None, None, None, None) @staticmethod def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param, param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) @staticmethod def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param): """Compute reference values for Trotter evolution via exact matrix exponentiation.""" dt = time / num_timesteps observables = [obs.to_matrix() for obs in observables] psi = Statevector(init_state).data if t_param is None: ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()] observable_results = [] observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]) for n in range(num_timesteps): if t_param is not None: time_value = (n + 1) * dt bound = operator.assign_parameters([time_value]) ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()] for op in ops: psi = expm(-1j * op * dt).dot(psi) observable_results.append( [np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables] ) return psi, observable_results if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test Estimator Gradients""" import unittest import numpy as np from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit_algorithms.gradients import ( FiniteDiffEstimatorGradient, LinCombEstimatorGradient, ParamShiftEstimatorGradient, SPSAEstimatorGradient, ReverseEstimatorGradient, DerivativeType, ) from qiskit.circuit import Parameter from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.circuit.library.standard_gates import RXXGate, RYYGate, RZXGate, RZZGate from qiskit.primitives import Estimator from qiskit.quantum_info import Operator, SparsePauliOp, Pauli from qiskit.quantum_info.random import random_pauli_list from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator gradient_factories = [ lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="central"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="forward"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="backward"), ParamShiftEstimatorGradient, LinCombEstimatorGradient, lambda estimator: ReverseEstimatorGradient(), # does not take an estimator! ] @ddt class TestEstimatorGradient(QiskitTestCase): """Test Estimator Gradient""" @data(*gradient_factories) def test_gradient_operators(self, grad): """Test the estimator gradient for different operators""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) correct_result = -1 / np.sqrt(2) param = [np.pi / 4] value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) op = SparsePauliOp.from_list([("Z", 1)]) value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) op = Operator.from_label("Z") value = gradient.run([qc], [op], [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) @data(*gradient_factories) def test_single_circuit_observable(self, grad): """Test the estimator gradient for a single circuit and observable""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) correct_result = -1 / np.sqrt(2) param = [np.pi / 4] value = gradient.run(qc, op, [param]).result().gradients[0] self.assertAlmostEqual(value[0], correct_result, 3) @data(*gradient_factories) def test_gradient_p(self, grad): """Test the estimator gradient for p""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) param_list = [[np.pi / 4], [0], [np.pi / 2]] correct_results = [[-1 / np.sqrt(2)], [0], [-1]] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] for j, value in enumerate(gradients): self.assertAlmostEqual(value, correct_results[i][j], 3) @data(*gradient_factories) def test_gradient_u(self, grad): """Test the estimator gradient for u""" estimator = Estimator() a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(1) qc.h(0) qc.u(a, b, c, 0) qc.h(0) gradient = grad(estimator) op = SparsePauliOp.from_list([("Z", 1)]) param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]] correct_results = [[-0.70710678, 0.0, 0.0], [-0.35355339, -0.85355339, -0.85355339]] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] for j, value in enumerate(gradients): self.assertAlmostEqual(value, correct_results[i][j], 3) @data(*gradient_factories) def test_gradient_efficient_su2(self, grad): """Test the estimator gradient for EfficientSU2""" estimator = Estimator() qc = EfficientSU2(2, reps=1) op = SparsePauliOp.from_list([("ZI", 1)]) gradient = grad(estimator) param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_results = [ [ -0.35355339, -0.70710678, 0, 0.35355339, 0, -0.70710678, 0, 0, ], [0, 0, 0, 1, 0, 0, 0, 0], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_2qubit_gate(self, grad): """Test the estimator gradient for 2 qubit gates""" estimator = Estimator() for gate in [RXXGate, RYYGate, RZZGate, RZXGate]: param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [-0.70710678], [-1], ] op = SparsePauliOp.from_list([("ZI", 1)]) for i, param in enumerate(param_list): a = Parameter("a") qc = QuantumCircuit(2) gradient = grad(estimator) if gate is RZZGate: qc.h([0, 1]) qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) qc.h([0, 1]) else: qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_parameter_coefficient(self, grad): """Test the estimator gradient for parameter variables with coefficients""" estimator = Estimator() qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1) qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1) qc.p(2 * qc.parameters[0] + 1, 0) qc.rxx(qc.parameters[0] + 2, 0, 1) gradient = grad(estimator) param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]] correct_results = [ [-0.7266653, -0.4905135, -0.0068606, -0.9228880], [-3.5972095, 0.10237173, -0.3117748, 0], ] op = SparsePauliOp.from_list([("ZI", 1)]) for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_parameters(self, grad): """Test the estimator gradient for parameters""" estimator = Estimator() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rx(b, 0) gradient = grad(estimator) param_list = [[np.pi / 4, np.pi / 2]] correct_results = [ [-0.70710678], ] op = SparsePauliOp.from_list([("Z", 1)]) for i, param in enumerate(param_list): gradients = gradient.run([qc], [op], [param], parameters=[[a]]).result().gradients[0] np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]] correct_results = [ [-0.35355339, 0.61237244, -0.61237244], [-0.61237244, 0.61237244, -0.35355339], [-0.35355339, -0.61237244], [-0.61237244, -0.35355339], ] param = [[a, b, c], [c, b, a], [a, c], [c, a]] op = SparsePauliOp.from_list([("Z", 1)]) for i, p in enumerate(param): gradient = grad(estimator) gradients = ( gradient.run([qc], [op], param_list, parameters=[p]).result().gradients[0] ) np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3) @data(*gradient_factories) def test_gradient_multi_arguments(self, grad): """Test the estimator gradient for multiple arguments""" estimator = Estimator() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc2 = QuantumCircuit(1) qc2.rx(b, 0) gradient = grad(estimator) param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [-0.70710678], [-1], ] op = SparsePauliOp.from_list([("Z", 1)]) gradients = gradient.run([qc, qc2], [op] * 2, param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) c = Parameter("c") qc3 = QuantumCircuit(1) qc3.rx(c, 0) qc3.ry(a, 0) param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]] correct_results2 = [ [-0.70710678], [-0.5], [-0.5, -0.5], ] gradients2 = ( gradient.run([qc, qc3, qc3], [op] * 3, param_list2, parameters=[[a], [c], None]) .result() .gradients ) np.testing.assert_allclose(gradients2[0], correct_results2[0], atol=1e-3) np.testing.assert_allclose(gradients2[1], correct_results2[1], atol=1e-3) np.testing.assert_allclose(gradients2[2], correct_results2[2], atol=1e-3) @data(*gradient_factories) def test_gradient_validation(self, grad): """Test estimator gradient's validation""" estimator = Estimator() a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) gradient = grad(estimator) param_list = [[np.pi / 4], [np.pi / 2]] op = SparsePauliOp.from_list([("Z", 1)]) with self.assertRaises(ValueError): gradient.run([qc], [op], param_list) with self.assertRaises(ValueError): gradient.run([qc, qc], [op, op], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc, qc], [op], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc], [op], [[np.pi / 4, np.pi / 4]]) def test_spsa_gradient(self): """Test the SPSA estimator gradient""" estimator = Estimator() with self.assertRaises(ValueError): _ = SPSAEstimatorGradient(estimator, epsilon=-0.1) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(2) qc.rx(b, 0) qc.rx(a, 1) param_list = [[1, 1]] correct_results = [[-0.84147098, 0.84147098]] op = SparsePauliOp.from_list([("ZI", 1)]) gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) gradients = gradient.run([qc], [op], param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) # multi parameters with self.subTest(msg="Multiple parameters"): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) param_list2 = [[1, 1], [1, 1], [3, 3]] gradients2 = ( gradient.run([qc] * 3, [op] * 3, param_list2, parameters=[None, [b], None]) .result() .gradients ) correct_results2 = [[-0.84147098, 0.84147098], [0.84147098], [-0.14112001, 0.14112001]] for grad, correct in zip(gradients2, correct_results2): np.testing.assert_allclose(grad, correct, atol=1e-3) # batch size with self.subTest(msg="Batch size"): correct_results = [[-0.84147098, 0.1682942]] gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, batch_size=5, seed=123) gradients = gradient.run([qc], [op], param_list).result().gradients np.testing.assert_allclose(gradients, correct_results, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) op = SparsePauliOp.from_list([("Z", 1)]) param_list3 = [[np.pi / 4, np.pi / 2, np.pi / 3]] param = [[a, b, c], [c, b, a], [a, c], [c, a]] expected = [ [-0.3535525, 0.3535525, 0.3535525], [0.3535525, 0.3535525, -0.3535525], [-0.3535525, 0.3535525], [0.3535525, -0.3535525], ] for i, p in enumerate(param): gradient = SPSAEstimatorGradient(estimator, epsilon=1e-6, seed=123) gradients = ( gradient.run([qc], [op], param_list3, parameters=[p]).result().gradients[0] ) np.testing.assert_allclose(gradients, expected[i], atol=1e-3) @data(ParamShiftEstimatorGradient, LinCombEstimatorGradient) def test_gradient_random_parameters(self, grad): """Test param shift and lin comb w/ random parameters""" rng = np.random.default_rng(123) qc = RealAmplitudes(num_qubits=3, reps=1) params = qc.parameters qc.rx(3.0 * params[0] + params[1].sin(), 0) qc.ry(params[0].exp() + 2 * params[1], 1) qc.rz(params[0] * params[1] - params[2], 2) qc.p(2 * params[0] + 1, 0) qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1) qc.sx(2) qc.rxx(params[0].sin(), 1, 2) qc.ryy(params[1].cos(), 2, 0) qc.rzz(params[2] * 2, 0, 1) qc.crx(params[0].exp(), 1, 2) qc.cry(params[1].arctan(), 2, 0) qc.crz(params[2] * -2, 0, 1) qc.dcx(0, 1) qc.csdg(0, 1) qc.toffoli(0, 1, 2) qc.iswap(0, 2) qc.swap(1, 2) qc.global_phase = params[0] * params[1] + params[2].cos().exp() size = 10 op = SparsePauliOp(random_pauli_list(num_qubits=qc.num_qubits, size=size, seed=rng)) op.coeffs = rng.normal(0, 10, size) estimator = Estimator() findiff = FiniteDiffEstimatorGradient(estimator, 1e-6) gradient = grad(estimator) num_tries = 10 param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist() np.testing.assert_allclose( findiff.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients, gradient.run([qc] * num_tries, [op] * num_tries, param_values).result().gradients, rtol=1e-4, ) @data((DerivativeType.IMAG, -1.0), (DerivativeType.COMPLEX, -1.0j)) @unpack def test_complex_gradient(self, derivative_type, expected_gradient_value): """Tests if the ``LinCombEstimatorGradient`` has the correct value.""" estimator = Estimator() lcu = LinCombEstimatorGradient(estimator, derivative_type=derivative_type) reverse = ReverseEstimatorGradient(derivative_type=derivative_type) for gradient in [lcu, reverse]: with self.subTest(gradient=gradient): c = QuantumCircuit(1) c.rz(Parameter("p"), 0) result = gradient.run([c], [Pauli("I")], [[0.0]]).result() self.assertAlmostEqual(result.gradients[0][0], expected_gradient_value) @data( FiniteDiffEstimatorGradient, ParamShiftEstimatorGradient, LinCombEstimatorGradient, SPSAEstimatorGradient, ) def test_options(self, grad): """Test estimator gradient's run options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) op = SparsePauliOp.from_list([("Z", 1)]) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6) else: gradient = grad(estimator) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient init"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("gradient update"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) gradient.update_default_options(shots=100) options = gradient.options result = gradient.run([qc], [op], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient run"): if grad is FiniteDiffEstimatorGradient or grad is SPSAEstimatorGradient: gradient = grad(estimator, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(estimator, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [op], [[1]], shots=300).result() self.assertEqual(result.options.get("shots"), 300) # Only default + estimator options. Not run. self.assertEqual(options.get("shots"), 200) @data( FiniteDiffEstimatorGradient, ParamShiftEstimatorGradient, LinCombEstimatorGradient, SPSAEstimatorGradient, ) def test_operations_preserved(self, gradient_cls): """Test non-parameterized instructions are preserved and not unrolled.""" x = Parameter("x") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled values = [np.pi / 2] expect = -1 / (2 * np.sqrt(2)) observable = SparsePauliOp(["XX"]) ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) if gradient_cls in [SPSAEstimatorGradient, FiniteDiffEstimatorGradient]: gradient = gradient_cls(estimator, epsilon=0.01) else: gradient = gradient_cls(estimator) job = gradient.run([circuit], [observable], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): self.assertAlmostEqual(result.gradients[0].item(), expect, places=5) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QFI.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import LinCombQGT, ReverseQGT, QFI, DerivativeType from qiskit.circuit import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase @ddt class TestQFI(QiskitTestCase): """Test QFI""" def setUp(self): super().setUp() self.estimator = Estimator() self.lcu_qgt = LinCombQGT(self.estimator, derivative_type=DerivativeType.REAL) self.reverse_qgt = ReverseQGT(derivative_type=DerivativeType.REAL) def test_qfi(self): """Test if the quantum fisher information calculation is correct for a simple test case. QFI = [[1, 0], [0, 1]] - [[0, 0], [0, cos^2(a)]] """ # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0.1], [np.pi, 0.1], [np.pi / 2, 0.1]] correct_values = [[[1, 0], [0, 0.5]], [[1, 0], [0, 0]], [[1, 0], [0, 1]]] qfi = QFI(self.lcu_qgt) for i, param in enumerate(param_list): qfis = qfi.run([qc], [param]).result().qfis np.testing.assert_allclose(qfis[0], correct_values[i], atol=1e-3) def test_qfi_phase_fix(self): """Test the phase-fix argument in the QFI calculation""" # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param = [np.pi / 4, 0.1] # test for different values correct_values = [[1, 0], [0, 1]] qgt = LinCombQGT(self.estimator, phase_fix=False) qfi = QFI(qgt) qfis = qfi.run([qc], [param]).result().qfis np.testing.assert_allclose(qfis[0], correct_values, atol=1e-3) @data("lcu", "reverse") def test_qfi_maxcut(self, qgt_kind): """Test the QFI for a simple MaxCut problem. This is interesting because it contains the same parameters in different gates. """ # create maxcut circuit for the hamiltonian # H = (I ^ I ^ Z ^ Z) + (I ^ Z ^ I ^ Z) + (Z ^ I ^ I ^ Z) + (I ^ Z ^ Z ^ I) x = ParameterVector("x", 2) ansatz = QuantumCircuit(4) # initial hadamard layer ansatz.h(ansatz.qubits) # e^{iZZ} layers def expiz(qubit0, qubit1): ansatz.cx(qubit0, qubit1) ansatz.rz(2 * x[0], qubit1) ansatz.cx(qubit0, qubit1) expiz(2, 1) expiz(3, 0) expiz(2, 0) expiz(1, 0) # mixer layer with RX gates for i in range(ansatz.num_qubits): ansatz.rx(2 * x[1], i) reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) param = [0.4, 0.69] qgt = self.lcu_qgt if qgt_kind == "lcu" else self.reverse_qgt qfi = QFI(qgt) qfi_result = qfi.run([ansatz], [param]).result().qfis np.testing.assert_array_almost_equal(qfi_result[0], reference, decimal=3) def test_options(self): """Test QFI's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qgt = LinCombQGT(estimator=self.estimator, options={"shots": 100}) with self.subTest("QGT"): qfi = QFI(qgt=qgt) options = qfi.options result = qfi.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QFI init"): qfi = QFI(qgt=qgt, options={"shots": 200}) result = qfi.run([qc], [[1]]).result() options = qfi.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QFI update"): qfi = QFI(qgt, options={"shots": 200}) qfi.update_default_options(shots=100) options = qfi.options result = qfi.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QFI run"): qfi = QFI(qgt=qgt, options={"shots": 200}) result = qfi.run([qc], [[0]], shots=300).result() options = qfi.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test QGT.""" import unittest from ddt import ddt, data import numpy as np from qiskit import QuantumCircuit from qiskit_algorithms.gradients import DerivativeType, LinCombQGT, ReverseQGT from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase from .logging_primitives import LoggingEstimator @ddt class TestQGT(QiskitTestCase): """Test QGT""" def setUp(self): super().setUp() self.estimator = Estimator() @data(LinCombQGT, ReverseQGT) def test_qgt_derivative_type(self, qgt_type): """Test QGT derivative_type""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 0.5]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_phase_fix(self, qgt_type): """Test the phase-fix argument in a QGT calculation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, phase_fix=False) # create the circuit a, b = Parameter("a"), Parameter("b") qc = QuantumCircuit(1) qc.h(0) qc.rz(a, 0) qc.rx(b, 0) param_list = [[np.pi / 4, 0], [np.pi / 2, np.pi / 4]] correct_values = [ np.array([[1, 0.707106781j], [-0.707106781j, 1]]) / 4, np.array([[1, 1j], [-1j, 1]]) / 4, ] # test real derivative with self.subTest("Test phase fix with DerivativeType.REAL"): qgt.derivative_type = DerivativeType.REAL for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].real, atol=1e-3) # test imaginary derivative with self.subTest("Test phase fix with DerivativeType.IMAG"): qgt.derivative_type = DerivativeType.IMAG for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i].imag, atol=1e-3) # test real + imaginary derivative with self.subTest("Test phase fix with DerivativeType.COMPLEX"): qgt.derivative_type = DerivativeType.COMPLEX for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_coefficients(self, qgt_type): """Test the derivative option of QGT""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[2] + qc.parameters[3].sin(), 1) # test imaginary derivative param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] correct_values = ( np.array( [ [ [5.707309, 4.2924833, 1.5295868, 0.1938604], [4.2924833, 4.9142136, 0.75, 0.8838835], [1.5295868, 0.75, 3.4430195, 0.0758252], [0.1938604, 0.8838835, 0.0758252, 1.1357233], ], [ [1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 10.0, -0.0], [0.0, 0.0, -0.0, 1.0], ], ] ) / 4 ) for i, param in enumerate(param_list): qgt_result = qgt.run([qc], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_parameters(self, qgt_type): """Test the QGT with specified parameters""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) param_values = [np.pi / 4, np.pi / 4] qgt_result = qgt.run([qc], [param_values], [[a]]).result().qgts np.testing.assert_allclose(qgt_result[0], [[1 / 4]], atol=1e-3) with self.subTest("Test with different parameter orders"): c = Parameter("c") qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.rz(b, 0) qc2.rx(c, 0) param_values = [np.pi / 4, np.pi / 4, np.pi / 4] params = [[a, b, c], [c, b, a], [a, c], [b, a]] expected = [ np.array( [ [0.25, 0.0, 0.1767767], [0.0, 0.125, -0.08838835], [0.1767767, -0.08838835, 0.1875], ] ), np.array( [ [0.1875, -0.08838835, 0.1767767], [-0.08838835, 0.125, 0.0], [0.1767767, 0.0, 0.25], ] ), np.array([[0.25, 0.1767767], [0.1767767, 0.1875]]), np.array([[0.125, 0.0], [0.0, 0.25]]), ] for i, param in enumerate(params): qgt_result = qgt.run([qc2], [param_values], [param]).result().qgts np.testing.assert_allclose(qgt_result[0], expected[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_multi_arguments(self, qgt_type): """Test the QGT for multiple arguments""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args, derivative_type=DerivativeType.REAL) a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.ry(b, 0) qc2 = QuantumCircuit(1) qc2.rx(a, 0) qc2.ry(b, 0) param_list = [[np.pi / 4], [np.pi / 2]] correct_values = [[[1 / 4]], [[1 / 4, 0], [0, 0]]] param_list = [[np.pi / 4, np.pi / 4], [np.pi / 2, np.pi / 2]] qgt_results = qgt.run([qc, qc2], param_list, [[a], None]).result().qgts for i, _ in enumerate(param_list): np.testing.assert_allclose(qgt_results[i], correct_values[i], atol=1e-3) @data(LinCombQGT, ReverseQGT) def test_qgt_validation(self, qgt_type): """Test estimator QGT's validation""" args = () if qgt_type == ReverseQGT else (self.estimator,) qgt = qgt_type(*args) a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) parameter_values = [[np.pi / 4]] with self.subTest("assert number of circuits does not match"): with self.assertRaises(ValueError): qgt.run([qc, qc], parameter_values) with self.subTest("assert number of parameter values does not match"): with self.assertRaises(ValueError): qgt.run([qc], [[np.pi / 4], [np.pi / 2]]) with self.subTest("assert number of parameters does not match"): with self.assertRaises(ValueError): qgt.run([qc], parameter_values, parameters=[[a], [a]]) def test_options(self): """Test QGT's options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) estimator = Estimator(options={"shots": 100}) with self.subTest("estimator"): qgt = LinCombQGT(estimator) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT init"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[1]]).result() options = qgt.options self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("QGT update"): qgt = LinCombQGT(estimator, options={"shots": 200}) qgt.update_default_options(shots=100) options = qgt.options result = qgt.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("QGT run"): qgt = LinCombQGT(estimator, options={"shots": 200}) result = qgt.run([qc], [[0]], shots=300).result() options = qgt.options self.assertEqual(result.options.get("shots"), 300) self.assertEqual(options.get("shots"), 200) def test_operations_preserved(self): """Test non-parameterized instructions are preserved and not unrolled.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(2) circuit.initialize([0.5, 0.5, 0.5, 0.5]) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.ry(y, 0) values = [np.pi / 2, np.pi] expect = np.diag([0.25, 0.5]) / 4 ops = [] def operations_callback(op): ops.append(op) estimator = LoggingEstimator(operations_callback=operations_callback) qgt = LinCombQGT(estimator, derivative_type=DerivativeType.REAL) job = qgt.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): np.testing.assert_allclose(result.qgts[0], expect, atol=1e-5) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # ============================================================================= """Test Sampler Gradients""" import unittest from typing import List import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit_algorithms.gradients import ( FiniteDiffSamplerGradient, LinCombSamplerGradient, ParamShiftSamplerGradient, SPSASamplerGradient, ) from qiskit.circuit import Parameter from qiskit.circuit.library import EfficientSU2, RealAmplitudes from qiskit.circuit.library.standard_gates import RXXGate from qiskit.primitives import Sampler from qiskit.result import QuasiDistribution from qiskit.test import QiskitTestCase from .logging_primitives import LoggingSampler gradient_factories = [ lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="backward"), ParamShiftSamplerGradient, LinCombSamplerGradient, ] @ddt class TestSamplerGradient(QiskitTestCase): """Test Sampler Gradient""" @data(*gradient_factories) def test_single_circuit(self, grad): """Test the sampler gradient for a single circuit""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_p(self, grad): """Test the sampler gradient for p""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.h(0) qc.p(a, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [0], [np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: 0, 1: 0}], [{0: -0.499999, 1: 0.499999}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_u(self, grad): """Test the sampler gradient for u""" sampler = Sampler() a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(1) qc.h(0) qc.u(a, b, c, 0) qc.h(0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, 0, 0], [np.pi / 4, np.pi / 4, np.pi / 4]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}, {0: 0, 1: 0}, {0: 0, 1: 0}], [{0: -0.176777, 1: 0.176777}, {0: -0.426777, 1: 0.426777}, {0: -0.426777, 1: 0.426777}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_efficient_su2(self, grad): """Test the sampler gradient for EfficientSU2""" sampler = Sampler() qc = EfficientSU2(2, reps=1) qc.measure_all() gradient = grad(sampler) param_list = [ [np.pi / 4 for param in qc.parameters], [np.pi / 2 for param in qc.parameters], ] expected = [ [ { 0: -0.11963834764831836, 1: -0.05713834764831845, 2: -0.21875000000000003, 3: 0.39552669529663675, }, { 0: -0.32230339059327373, 1: -0.031250000000000014, 2: 0.2339150429449554, 3: 0.11963834764831843, }, { 0: 0.012944173824159189, 1: -0.01294417382415923, 2: 0.07544417382415919, 3: -0.07544417382415919, }, { 0: 0.2080266952966367, 1: -0.03125000000000002, 2: -0.11963834764831842, 3: -0.057138347648318405, }, { 0: -0.11963834764831838, 1: 0.11963834764831838, 2: -0.21875000000000003, 3: 0.21875, }, { 0: -0.2781092167691146, 1: -0.0754441738241592, 2: 0.27810921676911443, 3: 0.07544417382415924, }, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], [ { 0: -4.163336342344337e-17, 1: 2.7755575615628914e-17, 2: -4.163336342344337e-17, 3: 0.0, }, {0: 0.0, 1: -1.3877787807814457e-17, 2: 4.163336342344337e-17, 3: 0.0}, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, { 0: 0.24999999999999994, 1: 0.24999999999999994, 2: -0.24999999999999994, 3: -0.24999999999999994, }, { 0: -4.163336342344337e-17, 1: 4.163336342344337e-17, 2: -4.163336342344337e-17, 3: 5.551115123125783e-17, }, { 0: -0.24999999999999994, 1: 0.24999999999999994, 2: 0.24999999999999994, 3: -0.24999999999999994, }, {0: 0.0, 1: 2.7755575615628914e-17, 2: 0.0, 3: 2.7755575615628914e-17}, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0}, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(expected[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_2qubit_gate(self, grad): """Test the sampler gradient for 2 qubit gates""" sampler = Sampler() for gate in [RXXGate]: param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0, 2: 0, 3: 0.5 / np.sqrt(2)}], [{0: -0.5, 1: 0, 2: 0, 3: 0.5}], ] for i, param in enumerate(param_list): a = Parameter("a") qc = QuantumCircuit(2) qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], []) qc.measure_all() gradient = grad(sampler) gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameter_coefficient(self, grad): """Test the sampler gradient for parameter variables with coefficients""" sampler = Sampler() qc = RealAmplitudes(num_qubits=2, reps=1) qc.rz(qc.parameters[0].exp() + 2 * qc.parameters[1], 0) qc.rx(3.0 * qc.parameters[0] + qc.parameters[1].sin(), 1) qc.u(qc.parameters[0], qc.parameters[1], qc.parameters[3], 1) qc.p(2 * qc.parameters[0] + 1, 0) qc.rxx(qc.parameters[0] + 2, 0, 1) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4 for _ in qc.parameters], [np.pi / 2 for _ in qc.parameters]] correct_results = [ [ { 0: 0.30014831912265927, 1: -0.6634809704357856, 2: 0.343589357193753, 3: 0.019743294119373426, }, { 0: 0.16470607453981906, 1: -0.40996282450610577, 2: 0.08791803062881773, 3: 0.15733871933746948, }, { 0: 0.27036068339663866, 1: -0.273790986018701, 2: 0.12752010079553433, 3: -0.12408979817347202, }, { 0: -0.2098616294167757, 1: -0.2515823946449894, 2: 0.21929102305386305, 3: 0.24215300100790207, }, ], [ { 0: -1.844810060881004, 1: 0.04620532700836027, 2: 1.6367366426074323, 3: 0.16186809126521057, }, { 0: 0.07296073407769421, 1: -0.021774869186331716, 2: 0.02177486918633173, 3: -0.07296073407769456, }, { 0: -0.07794369186049102, 1: -0.07794369186049122, 2: 0.07794369186049117, 3: 0.07794369186049112, }, { 0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, }, ], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_parameters(self, grad): """Test the sampler gradient for parameters""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4, np.pi / 2]] expected = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], ] for i, param in enumerate(param_list): gradients = gradient.run([qc], [param], parameters=[[a]]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): c = Parameter("c") qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_values = [[np.pi / 4, np.pi / 2, np.pi / 3]] params = [[a, b, c], [c, b, a], [a, c], [c, a]] expected = [ [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: 0.3061861668168149, 1: -0.3061861668167012}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], [ {0: -0.17677666583387008, 1: 0.17677666583378482}, {0: -0.3061861668168149, 1: 0.30618616681678645}, ], [ {0: -0.3061861668168149, 1: 0.30618616681678645}, {0: -0.17677666583387008, 1: 0.17677666583378482}, ], ] for i, p in enumerate(params): gradients = gradient.run([qc], param_values, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(expected[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_multi_arguments(self, grad): """Test the sampler gradient for multiple arguments""" sampler = Sampler() a = Parameter("a") b = Parameter("b") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() qc2 = QuantumCircuit(1) qc2.rx(b, 0) qc2.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.499999, 1: 0.499999}], ] gradients = gradient.run([qc, qc2], param_list).result().gradients for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameters with self.subTest(msg="Different parameters"): c = Parameter("c") qc3 = QuantumCircuit(1) qc3.rx(c, 0) qc3.ry(a, 0) qc3.measure_all() param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]] gradients = ( gradient.run([qc, qc3, qc3], param_list2, parameters=[[a], [c], None]) .result() .gradients ) correct_results = [ [{0: -0.5 / np.sqrt(2), 1: 0.5 / np.sqrt(2)}], [{0: -0.25, 1: 0.25}], [{0: -0.25, 1: 0.25}, {0: -0.25, 1: 0.25}], ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(*gradient_factories) def test_gradient_validation(self, grad): """Test sampler gradient's validation""" sampler = Sampler() a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() gradient = grad(sampler) param_list = [[np.pi / 4], [np.pi / 2]] with self.assertRaises(ValueError): gradient.run([qc], param_list) with self.assertRaises(ValueError): gradient.run([qc, qc], param_list, parameters=[[a]]) with self.assertRaises(ValueError): gradient.run([qc], [[np.pi / 4, np.pi / 4]]) def test_spsa_gradient(self): """Test the SPSA sampler gradient""" sampler = Sampler() with self.assertRaises(ValueError): _ = SPSASamplerGradient(sampler, epsilon=-0.1) a = Parameter("a") b = Parameter("b") c = Parameter("c") qc = QuantumCircuit(2) qc.rx(b, 0) qc.rx(a, 1) qc.measure_all() param_list = [[1, 2]] correct_results = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) for i, param in enumerate(param_list): gradients = gradient.run([qc], [param]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=2) array2 = _quasi2array(correct_results[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # multi parameters with self.subTest(msg="Multiple parameters"): param_list2 = [[1, 2], [1, 2], [3, 4]] correct_results2 = [ [ {0: 0.2273244, 1: -0.6480598, 2: 0.2273244, 3: 0.1934111}, {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.2273244, 1: 0.6480598, 2: -0.2273244, 3: -0.1934111}, ], [ {0: -0.0141129, 1: -0.0564471, 2: -0.3642884, 3: 0.4348484}, {0: 0.0141129, 1: 0.0564471, 2: 0.3642884, 3: -0.4348484}, ], ] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = ( gradient.run([qc] * 3, param_list2, parameters=[None, [b], None]).result().gradients ) for i, result in enumerate(gradients): array1 = _quasi2array(result, num_qubits=2) array2 = _quasi2array(correct_results2[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # batch size with self.subTest(msg="Batch size"): param_list = [[1, 1]] gradient = SPSASamplerGradient(sampler, epsilon=1e-6, batch_size=4, seed=123) gradients = gradient.run([qc], param_list).result().gradients correct_results3 = [ [ { 0: -0.1620149622932887, 1: -0.25872053011771756, 2: 0.3723827084675668, 3: 0.04835278392088804, }, { 0: -0.1620149622932887, 1: 0.3723827084675668, 2: -0.25872053011771756, 3: 0.04835278392088804, }, ] ] for i, q_dists in enumerate(gradients): array1 = _quasi2array(q_dists, num_qubits=2) array2 = _quasi2array(correct_results3[i], num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-3) # parameter order with self.subTest(msg="The order of gradients"): qc = QuantumCircuit(1) qc.rx(a, 0) qc.rz(b, 0) qc.rx(c, 0) qc.measure_all() param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]] param = [[a, b, c], [c, b, a], [a, c], [c, a]] correct_results = [ [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], [ {0: -0.17677624757590138, 1: 0.17677624757590138}, {0: 0.17677624757590138, 1: -0.17677624757590138}, ], [ {0: 0.17677624757590138, 1: -0.17677624757590138}, {0: -0.17677624757590138, 1: 0.17677624757590138}, ], ] for i, p in enumerate(param): gradient = SPSASamplerGradient(sampler, epsilon=1e-6, seed=123) gradients = gradient.run([qc], param_list, parameters=[p]).result().gradients[0] array1 = _quasi2array(gradients, num_qubits=1) array2 = _quasi2array(correct_results[i], num_qubits=1) np.testing.assert_allclose(array1, array2, atol=1e-3) @data(ParamShiftSamplerGradient, LinCombSamplerGradient) def test_gradient_random_parameters(self, grad): """Test param shift and lin comb w/ random parameters""" rng = np.random.default_rng(123) qc = RealAmplitudes(num_qubits=3, reps=1) params = qc.parameters qc.rx(3.0 * params[0] + params[1].sin(), 0) qc.ry(params[0].exp() + 2 * params[1], 1) qc.rz(params[0] * params[1] - params[2], 2) qc.p(2 * params[0] + 1, 0) qc.u(params[0].sin(), params[1] - 2, params[2] * params[3], 1) qc.sx(2) qc.rxx(params[0].sin(), 1, 2) qc.ryy(params[1].cos(), 2, 0) qc.rzz(params[2] * 2, 0, 1) qc.crx(params[0].exp(), 1, 2) qc.cry(params[1].arctan(), 2, 0) qc.crz(params[2] * -2, 0, 1) qc.dcx(0, 1) qc.csdg(0, 1) qc.toffoli(0, 1, 2) qc.iswap(0, 2) qc.swap(1, 2) qc.global_phase = params[0] * params[1] + params[2].cos().exp() qc.measure_all() sampler = Sampler() findiff = FiniteDiffSamplerGradient(sampler, 1e-6) gradient = grad(sampler) num_qubits = qc.num_qubits num_tries = 10 param_values = rng.normal(0, 2, (num_tries, qc.num_parameters)).tolist() result1 = findiff.run([qc] * num_tries, param_values).result().gradients result2 = gradient.run([qc] * num_tries, param_values).result().gradients self.assertEqual(len(result1), len(result2)) for res1, res2 in zip(result1, result2): array1 = _quasi2array(res1, num_qubits) array2 = _quasi2array(res2, num_qubits) np.testing.assert_allclose(array1, array2, rtol=1e-4) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_options(self, grad): """Test sampler gradient's run options""" a = Parameter("a") qc = QuantumCircuit(1) qc.rx(a, 0) qc.measure_all() sampler = Sampler(options={"shots": 100}) with self.subTest("sampler"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6) else: gradient = grad(sampler) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient init"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 200) self.assertEqual(options.get("shots"), 200) with self.subTest("gradient update"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) gradient.update_default_options(shots=100) options = gradient.options result = gradient.run([qc], [[1]]).result() self.assertEqual(result.options.get("shots"), 100) self.assertEqual(options.get("shots"), 100) with self.subTest("gradient run"): if grad is FiniteDiffSamplerGradient or grad is SPSASamplerGradient: gradient = grad(sampler, epsilon=1e-6, options={"shots": 200}) else: gradient = grad(sampler, options={"shots": 200}) options = gradient.options result = gradient.run([qc], [[1]], shots=300).result() self.assertEqual(result.options.get("shots"), 300) # Only default + sampler options. Not run. self.assertEqual(options.get("shots"), 200) @data( FiniteDiffSamplerGradient, ParamShiftSamplerGradient, LinCombSamplerGradient, SPSASamplerGradient, ) def test_operations_preserved(self, gradient_cls): """Test non-parameterized instructions are preserved and not unrolled.""" x = Parameter("x") circuit = QuantumCircuit(2) circuit.initialize(np.array([1, 1, 0, 0]) / np.sqrt(2)) # this should remain as initialize circuit.crx(x, 0, 1) # this should get unrolled circuit.measure_all() values = [np.pi / 2] expect = [{0: 0, 1: -0.25, 2: 0, 3: 0.25}] ops = [] def operations_callback(op): ops.append(op) sampler = LoggingSampler(operations_callback=operations_callback) if gradient_cls in [SPSASamplerGradient, FiniteDiffSamplerGradient]: gradient = gradient_cls(sampler, epsilon=0.01) else: gradient = gradient_cls(sampler) job = gradient.run([circuit], [values]) result = job.result() with self.subTest(msg="assert initialize is preserved"): self.assertTrue(all("initialize" in ops_i[0].keys() for ops_i in ops)) with self.subTest(msg="assert result is correct"): array1 = _quasi2array(result.gradients[0], num_qubits=2) array2 = _quasi2array(expect, num_qubits=2) np.testing.assert_allclose(array1, array2, atol=1e-5) def _quasi2array(quasis: List[QuasiDistribution], num_qubits: int) -> np.ndarray: ret = np.zeros((len(quasis), 2**num_qubits)) for i, quasi in enumerate(quasis): ret[i, list(quasi.keys())] = list(quasi.values()) return ret if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm.""" import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np import rustworkx as rx from ddt import ddt, idata, unpack from scipy.optimize import minimize as scipy_minimize from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = SparsePauliOp.from_list( [ ("IIIX", 1), ("IIXI", 1), ("IXII", 1), ("XIII", 1), ] ) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] return SparsePauliOp.from_list(lst), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the QAOA algorithm with opflow.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import ddt, idata, unpack import rustworkx as rx from qiskit import QuantumCircuit from qiskit_algorithms.minimum_eigensolvers import QAOA from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli from qiskit.result import QuasiDistribution from qiskit.primitives import Sampler from qiskit.utils import algorithm_globals I = PauliSumOp.from_list([("I", 1)]) X = PauliSumOp.from_list([("X", 1)]) W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) P1 = 1 M1 = (I ^ I ^ I ^ X) + (I ^ I ^ X ^ I) + (I ^ X ^ I ^ I) + (X ^ I ^ I ^ I) S1 = {"0101", "1010"} W2 = np.array( [ [0.0, 8.0, -9.0, 0.0], [8.0, 0.0, 7.0, 9.0], [-9.0, 7.0, 0.0, -8.0], [0.0, 9.0, -8.0, 0.0], ] ) P2 = 1 M2 = None S2 = {"1011", "0100"} CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0] @ddt class TestQAOA(QiskitAlgorithmsTestCase): """Test QAOA with MaxCut.""" def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed self.sampler = Sampler() @idata( [ [W1, P1, M1, S1], [W2, P2, M2, S2], ] ) @unpack def test_qaoa(self, w, reps, mixer, solutions): """QAOA test""" self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @idata( [ [W1, P1, S1], [W2, P2, S2], ] ) @unpack def test_qaoa_qc_mixer(self, w, prob, solutions): """QAOA test with a mixer as a parameterized circuit""" self.log.debug( "Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s", prob, w, ) optimizer = COBYLA() qubit_op, _ = self._get_operator(w) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) def test_qaoa_qc_mixer_many_parameters(self): """QAOA test with a mixer as a parameterized circuit with the num of parameters > 1.""" optimizer = COBYLA() qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) for i in range(num_qubits): theta = Parameter("θ" + str(i)) mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, S1) def test_qaoa_qc_mixer_no_parameters(self): """QAOA test with a mixer as a parameterized circuit with zero parameters.""" qubit_op, _ = self._get_operator(W1) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) # just arbitrary circuit mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) def test_change_operator_size(self): """QAOA change operator size test""" qubit_op, _ = self._get_operator( np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): self.assertIn(graph_solution, {"0101", "1010"}) qubit_op, _ = self._get_operator( np.array( [ [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0], ] ) ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): self.assertIn(graph_solution, {"010101", "101010"}) @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]]) @unpack def test_qaoa_initial_point(self, w, solutions, init_pt): """Check first parameter value used is initial point as expected""" qubit_op, _ = self._get_operator(w) first_pt = [] def cb_callback(eval_count, parameters, mean, metadata): nonlocal first_pt if eval_count == 1: first_pt = list(parameters) qaoa = QAOA( self.sampler, COBYLA(), initial_point=init_pt, callback=cb_callback, ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest("Initial Point"): # If None the preferred random initial point of QAOA variational form if init_pt is None: self.assertLess(result.eigenvalue, -0.97) else: self.assertListEqual(init_pt, first_pt) with self.subTest("Solution"): self.assertIn(graph_solution, solutions) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) self.assertLess(result.eigenvalue, -0.97) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) qubit_op, _ = self._get_operator(w) qaoa = QAOA( self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(qubit_op) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): """Generate Hamiltonian for the max-cut problem of a graph. Args: weight_matrix (numpy.ndarray) : adjacency matrix. Returns: PauliSumOp: operator for the Hamiltonian float: a constant shift for the obj function. """ num_nodes = weight_matrix.shape[0] pauli_list = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] with self.assertWarns(DeprecationWarning): return PauliSumOp.from_list(opflow_list), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. Args: x : binary string as numpy array. Returns: a graph solution as string. """ return "".join([str(int(i)) for i in 1 - x]) def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: Quasi-distribution. Returns: Binary string as numpy.ndarray of ints. """ values = list(state_vector.values()) n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the variational quantum eigensolver algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from scipy.optimize import minimize as scipy_minimize from ddt import data, ddt from qiskit import QuantumCircuit from qiskit_algorithms import AlgorithmError from qiskit_algorithms.gradients import ParamShiftEstimatorGradient from qiskit_algorithms.minimum_eigensolvers import VQE from qiskit_algorithms.optimizers import ( CG, COBYLA, GradientDescent, L_BFGS_B, OptimizerResult, P_BFGS, QNSPSA, SLSQP, SPSA, TNC, ) from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes, TwoLocal from qiskit.opflow import PauliSumOp, TwoQubitReduction from qiskit.quantum_info import SparsePauliOp, Operator, Pauli from qiskit.primitives import Estimator, Sampler from qiskit.utils import algorithm_globals # pylint: disable=invalid-name def _mock_optimizer(fun, x0, jac=None, bounds=None, inputs=None) -> OptimizerResult: """A mock of a callable that can be used as minimizer in the VQE.""" result = OptimizerResult() result.x = np.zeros_like(x0) result.fun = fun(result.x) result.nit = 0 if inputs is not None: inputs.update({"fun": fun, "x0": x0, "jac": jac, "bounds": bounds}) return result @ddt class TestVQE(QiskitAlgorithmsTestCase): """Test VQE""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed self.h2_op = SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") @data(L_BFGS_B(), COBYLA()) def test_basic_aer_statevector(self, estimator): """Test VQE using reference Estimator.""" vqe = VQE(Estimator(), self.ryrz_wavefunction, estimator) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) with self.subTest(msg="test optimal_value"): self.assertAlmostEqual(result.optimal_value, self.h2_energy) with self.subTest(msg="test dimension of optimal point"): self.assertEqual(len(result.optimal_point), 16) with self.subTest(msg="assert cost_function_evals is set"): self.assertIsNotNone(result.cost_function_evals) with self.subTest(msg="assert optimizer_time is set"): self.assertIsNotNone(result.optimizer_time) with self.subTest(msg="assert optimizer_result is set"): self.assertIsNotNone(result.optimizer_result) with self.subTest(msg="assert optimizer_result."): self.assertAlmostEqual(result.optimizer_result.fun, self.h2_energy, places=5) with self.subTest(msg="assert return ansatz is set"): estimator = Estimator() job = estimator.run(result.optimal_circuit, self.h2_op, result.optimal_point) np.testing.assert_array_almost_equal(job.result().values, result.eigenvalue, 6) def test_invalid_initial_point(self): """Test the proper error is raised when the initial point has the wrong size.""" ansatz = self.ryrz_wavefunction initial_point = np.array([1]) vqe = VQE( Estimator(), ansatz, SLSQP(), initial_point=initial_point, ) with self.assertRaises(ValueError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_ansatz_resize(self): """Test the ansatz is properly resized if it's a blueprint circuit.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, SLSQP()) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_invalid_ansatz_size(self): """Test an error is raised if the ansatz has the wrong number of qubits.""" ansatz = QuantumCircuit(1) ansatz.compose(RealAmplitudes(1, reps=2)) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_missing_ansatz_params(self): """Test specifying an ansatz with no parameters raises an error.""" ansatz = QuantumCircuit(self.h2_op.num_qubits) vqe = VQE(Estimator(), ansatz, SLSQP()) with self.assertRaises(AlgorithmError): vqe.compute_minimum_eigenvalue(operator=self.h2_op) def test_max_evals_grouped(self): """Test with SLSQP with max_evals_grouped.""" optimizer = SLSQP(maxiter=50, max_evals_grouped=5) vqe = VQE( Estimator(), self.ryrz_wavefunction, optimizer, ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( CG(), L_BFGS_B(), P_BFGS(), SLSQP(), TNC(), ) def test_with_gradient(self, optimizer): """Test VQE using gradient primitive.""" estimator = Estimator() vqe = VQE( estimator, self.ry_wavefunction, optimizer, gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_gradient_passed(self): """Test the gradient is properly passed into the optimizer.""" inputs = {} estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), partial(_mock_optimizer, inputs=inputs), gradient=ParamShiftEstimatorGradient(estimator), ) _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertIsNotNone(inputs["jac"]) def test_gradient_run(self): """Test using the gradient to calculate the minimum.""" estimator = Estimator() vqe = VQE( estimator, RealAmplitudes(), GradientDescent(maxiter=200, learning_rate=0.1), gradient=ParamShiftEstimatorGradient(estimator), ) result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), ("IIIZ", 0.17218393261915552), ("IIZZ", -0.22575349222402472), ("IZZI", 0.1721839326191556), ("ZZII", -0.22575349222402466), ("IIZI", 0.1209126326177663), ("IZZZ", 0.16892753870087912), ("IXZX", -0.045232799946057854), ("ZXIX", 0.045232799946057854), ("IXIX", 0.045232799946057854), ("ZXZX", -0.045232799946057854), ("ZZIZ", 0.16614543256382414), ("IZIZ", 0.16614543256382414), ("ZZZZ", 0.17464343068300453), ("ZIZI", 0.1209126326177663), ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) vqe = VQE( Estimator(), self.ry_wavefunction, SPSA(maxiter=300, last_avg=5), ) result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_callback(self): """Test the callback on VQE.""" history = {"eval_count": [], "parameters": [], "mean": [], "metadata": []} def store_intermediate_result(eval_count, parameters, mean, metadata): history["eval_count"].append(eval_count) history["parameters"].append(parameters) history["mean"].append(mean) history["metadata"].append(metadata) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction estimator = Estimator() vqe = VQE( estimator, wavefunction, optimizer, callback=store_intermediate_result, ) vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(metadata, dict) for metadata in history["metadata"])) for params in history["parameters"]: self.assertTrue(all(isinstance(param, float) for param in params)) def test_reuse(self): """Test re-using a VQE algorithm instance.""" ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe = VQE(Estimator(), ansatz, SLSQP(maxiter=300)) with self.subTest(msg="assert VQE works once all info is available"): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = Operator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg="assert vqe works on re-use."): result = vqe.compute_minimum_eigenvalue(operator=operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) def test_vqe_optimizer_reuse(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" vqe = VQE( Estimator(), self.ryrz_wavefunction, SLSQP(), ) def run_check(): result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) run_check() with self.subTest("Optimizer re-use."): run_check() with self.subTest("Optimizer replace."): vqe.optimizer = L_BFGS_B() run_check() def test_default_batch_evaluation_on_spsa(self): """Test the default batching works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) spsa = SPSA(maxiter=5) vqe = VQE(wrapped_estimator, ansatz, spsa) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 1 calibration + 5 loss + 1 return loss expected_estimator_runs = 1 + 5 + 1 with self.subTest(msg="check callcount"): self.assertEqual(callcount["estimator"], expected_estimator_runs) with self.subTest(msg="check reset to original max evals grouped"): self.assertIsNone(spsa._max_evals_grouped) def test_batch_evaluate_with_qnspsa(self): """Test batch evaluating with QNSPSA works.""" ansatz = TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz") wrapped_sampler = Sampler() inner_sampler = Sampler() wrapped_estimator = Estimator() inner_estimator = Estimator() callcount = {"sampler": 0, "estimator": 0} def wrapped_estimator_run(*args, **kwargs): kwargs["callcount"]["estimator"] += 1 return inner_estimator.run(*args, **kwargs) def wrapped_sampler_run(*args, **kwargs): kwargs["callcount"]["sampler"] += 1 return inner_sampler.run(*args, **kwargs) wrapped_estimator.run = partial(wrapped_estimator_run, callcount=callcount) wrapped_sampler.run = partial(wrapped_sampler_run, callcount=callcount) fidelity = ComputeUncompute(wrapped_sampler) def fidelity_callable(left, right): batchsize = np.asarray(left).shape[0] job = fidelity.run(batchsize * [ansatz], batchsize * [ansatz], left, right) return job.result().fidelities qnspsa = QNSPSA(fidelity_callable, maxiter=5) qnspsa.set_max_evals_grouped(100) vqe = VQE( wrapped_estimator, ansatz, qnspsa, ) _ = vqe.compute_minimum_eigenvalue(Pauli("ZZ")) # 5 (fidelity) expected_sampler_runs = 5 # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 blocking) + 1 return loss expected_estimator_runs = 1 + 1 + 1 + 5 * 2 + 1 self.assertEqual(callcount["sampler"], expected_sampler_runs) self.assertEqual(callcount["estimator"], expected_estimator_runs) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" vqe = VQE( Estimator(), self.ryrz_wavefunction, partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 10}), ) result = vqe.compute_minimum_eigenvalue(self.h2_op) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=2) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) vqe = VQE(Estimator(), ansatz, _mock_optimizer) result = vqe.compute_minimum_eigenvalue(SparsePauliOp("Z")) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty list."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0], 2.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[1][0], 0.0, places=6) self.assertAlmostEqual(result.aux_operators_evaluated[2][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated[0][1], dict) self.assertIsInstance(result.aux_operators_evaluated[1][1], dict) self.assertIsInstance(result.aux_operators_evaluated[2][1], dict) def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" vqe = VQE(Estimator(), self.ry_wavefunction, SLSQP(maxiter=300)) with self.subTest("Test with an empty dictionary."): result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated["aux_op1"][0], 2.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["aux_op2"][0], 0.0, places=5) self.assertAlmostEqual(result.aux_operators_evaluated["zero_operator"][0], 0.0) # metadata self.assertIsInstance(result.aux_operators_evaluated["aux_op1"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["aux_op2"][1], dict) self.assertIsInstance(result.aux_operators_evaluated["zero_operator"][1], dict) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of scikit-quant optimizers.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy from qiskit import BasicAer from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.exceptions import MissingOptionalLibraryError from qiskit.opflow import PauliSumOp from qiskit_algorithms import VQE from qiskit_algorithms.optimizers import BOBYQA, SNOBFIT, IMFIL @ddt class TestOptimizers(QiskitAlgorithmsTestCase): """Test scikit-quant optimizers.""" def setUp(self): """Set the problem.""" super().setUp() algorithm_globals.random_seed = 50 with self.assertWarns(DeprecationWarning): self.qubit_op = PauliSumOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) def _optimize(self, optimizer): """launch vqe""" with self.assertWarns(DeprecationWarning): qe = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) with self.assertWarns(DeprecationWarning): vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe) result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1) def test_bobyqa(self): """BOBYQA optimizer test.""" try: optimizer = BOBYQA(maxiter=150) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) @unittest.skipIf( tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0), "scikit's SnobFit currently incompatible with NumPy 1.24.0.", ) def test_snobfit(self): """SNOBFIT optimizer test.""" try: optimizer = SNOBFIT(maxiter=100, maxfail=100, maxmp=20) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) @unittest.skipIf( tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0), "scikit's SnobFit currently incompatible with NumPy 1.24.0.", ) @data((None,), ([(-1, 1), (None, None)],)) @unpack def test_snobfit_missing_bounds(self, bounds): """SNOBFIT optimizer test with missing bounds.""" try: optimizer = SNOBFIT() with self.assertRaises(ValueError): optimizer.minimize( fun=lambda _: 1, # using dummy function (never called) x0=[0.1, 0.1], # dummy initial point bounds=bounds, ) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) def test_imfil(self): """IMFIL test.""" try: optimizer = IMFIL(maxiter=100) self._optimize(optimizer) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test of NFT optimizer""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import BasicAer from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import PauliSumOp from qiskit_algorithms.optimizers import NFT from qiskit_algorithms import VQE class TestOptimizerNFT(QiskitAlgorithmsTestCase): """Test NFT optimizer using RY with VQE""" def setUp(self): super().setUp() algorithm_globals.random_seed = 50 with self.assertWarns(DeprecationWarning): self.qubit_op = PauliSumOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) def test_nft(self): """Test NFT optimizer by using it""" with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=RealAmplitudes(), optimizer=NFT(), quantum_instance=QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ), ) result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) self.assertAlmostEqual(result.eigenvalue.real, -1.857275, places=6) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for PVQD.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np from ddt import data, ddt, unpack from qiskit import QiskitError from qiskit_algorithms.time_evolvers import TimeEvolutionProblem from qiskit_algorithms.optimizers import L_BFGS_B, SPSA, GradientDescent, OptimizerResult from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_algorithms.time_evolvers.pvqd import PVQD from qiskit.circuit import Gate, Parameter, QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import PauliSumOp from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.test import QiskitTestCase from qiskit.utils import algorithm_globals # pylint: disable=unused-argument, invalid-name def gradient_supplied(fun, x0, jac, info): """A mock optimizer that checks whether the gradient is supported or not.""" result = OptimizerResult() result.x = x0 result.fun = 0 info["has_gradient"] = jac is not None return result class WhatAmI(Gate): """A custom opaque gate that can be inverted but not decomposed.""" def __init__(self, angle): super().__init__(name="whatami", num_qubits=2, params=[angle]) def inverse(self): return WhatAmI(-self.params[0]) @ddt class TestPVQD(QiskitAlgorithmsTestCase): """Tests for the pVQD algorithm.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.observable = Pauli("ZZ") self.ansatz = EfficientSU2(2, reps=1) self.initial_parameters = np.zeros(self.ansatz.num_parameters) algorithm_globals.random_seed = 123 @data(("ising", True, 2), ("pauli", False, None), ("pauli_sum_op", True, 2)) @unpack def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): """Test a simple evolution.""" time = 0.02 if hamiltonian_type == "ising": hamiltonian = self.hamiltonian elif hamiltonian_type == "pauli_sum_op": with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(self.hamiltonian) else: # hamiltonian_type == "pauli": hamiltonian = Pauli("XX") # parse input arguments if gradient: optimizer = GradientDescent(maxiter=1) else: optimizer = L_BFGS_B(maxiter=1) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) # run pVQD keeping track of the energy and the magnetization pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=optimizer, num_timesteps=num_timesteps, ) problem = TimeEvolutionProblem( hamiltonian, time, aux_operators=[hamiltonian, self.observable] ) result = pvqd.evolve(problem) self.assertTrue(len(result.fidelities) == 3) self.assertTrue(np.all(result.times == [0.0, 0.01, 0.02])) self.assertTrue(np.asarray(result.observables).shape == (3, 2)) num_parameters = self.ansatz.num_parameters self.assertTrue( len(result.parameters) == 3 and np.all([len(params) == num_parameters for params in result.parameters]) ) def test_step(self): """Test calling the step method directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(maxiter=100), ) # perform optimization for a timestep of 0, then the optimal parameters are the current # ones and the fidelity is 1 theta_next, fidelity = pvqd.step( self.hamiltonian, self.ansatz, self.initial_parameters, dt=0.0, initial_guess=np.zeros_like(self.initial_parameters), ) self.assertTrue(np.allclose(theta_next, self.initial_parameters)) self.assertAlmostEqual(fidelity, 1) def test_get_loss(self): """Test getting the loss function directly.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, use_parameter_shift=False, ) theta = np.ones(self.ansatz.num_parameters) loss, gradient = pvqd.get_loss( self.hamiltonian, self.ansatz, dt=0.0, current_parameters=theta ) displacement = np.arange(self.ansatz.num_parameters) with self.subTest(msg="check gradient is None"): self.assertIsNone(gradient) with self.subTest(msg="check loss works"): self.assertGreater(loss(displacement), 0) self.assertAlmostEqual(loss(np.zeros_like(theta)), 0) def test_invalid_num_timestep(self): """Test raises if the num_timestep is not positive.""" sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=L_BFGS_B(), num_timesteps=0, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.01, aux_operators=[self.hamiltonian, self.observable] ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) def test_initial_guess_and_observables(self): """Test doing no optimizations stays at initial guess.""" initial_guess = np.zeros(self.ansatz.num_parameters) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, estimator, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), num_timesteps=10, initial_guess=initial_guess, ) problem = TimeEvolutionProblem( self.hamiltonian, time=0.1, aux_operators=[self.hamiltonian, self.observable] ) result = pvqd.evolve(problem) observables = result.aux_ops_evaluated self.assertEqual(observables[0], 0.1) # expected energy self.assertEqual(observables[1], 1) # expected magnetization def test_zero_parameters(self): """Test passing an ansatz with zero parameters raises an error.""" problem = TimeEvolutionProblem(self.hamiltonian, time=0.02) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, QuantumCircuit(2), np.array([]), optimizer=SPSA(maxiter=10, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(QiskitError): _ = pvqd.evolve(problem) def test_initial_state_raises(self): """Test passing an initial state raises an error for now.""" initial_state = QuantumCircuit(2) initial_state.x(0) problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, initial_state=initial_state, ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(NotImplementedError): _ = pvqd.evolve(problem) def test_aux_ops_raises(self): """Test passing auxiliary operators with no estimator raises an error.""" problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, aux_operators=[self.hamiltonian, self.observable] ) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity_primitive, self.ansatz, self.initial_parameters, optimizer=SPSA(maxiter=0, learning_rate=0.1, perturbation=0.01), ) with self.assertRaises(ValueError): _ = pvqd.evolve(problem) class TestPVQDUtils(QiskitTestCase): """Test some utility functions for PVQD.""" def setUp(self): super().setUp() self.hamiltonian = 0.1 * SparsePauliOp([Pauli("ZZ"), Pauli("IX"), Pauli("XI")]) self.ansatz = EfficientSU2(2, reps=1) def test_gradient_supported(self): """Test the gradient support is correctly determined.""" # gradient supported here wrapped = EfficientSU2(2) # a circuit wrapped into a big instruction plain = wrapped.decompose() # a plain circuit with already supported instructions # gradients not supported on the following circuits x = Parameter("x") duplicated = QuantumCircuit(2) duplicated.rx(x, 0) duplicated.rx(x, 1) needs_chainrule = QuantumCircuit(2) needs_chainrule.rx(2 * x, 0) custom_gate = WhatAmI(x) unsupported = QuantumCircuit(2) unsupported.append(custom_gate, [0, 1]) tests = [ (wrapped, True), # tuple: (circuit, gradient support) (plain, True), (duplicated, False), (needs_chainrule, False), (unsupported, False), ] # used to store the info if a gradient callable is passed into the # optimizer of not info = {"has_gradient": None} optimizer = partial(gradient_supplied, info=info) sampler = Sampler() estimator = Estimator() fidelity_primitive = ComputeUncompute(sampler) pvqd = PVQD( fidelity=fidelity_primitive, ansatz=None, initial_parameters=np.array([]), estimator=estimator, optimizer=optimizer, ) problem = TimeEvolutionProblem(self.hamiltonian, time=0.01) for circuit, expected_support in tests: with self.subTest(circuit=circuit, expected_support=expected_support): pvqd.ansatz = circuit pvqd.initial_parameters = np.zeros(circuit.num_parameters) _ = pvqd.evolve(problem) self.assertEqual(info["has_gradient"], expected_support) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test evolver problem class.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt from numpy.testing import assert_raises from qiskit import QuantumCircuit from qiskit_algorithms import TimeEvolutionProblem from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @ddt class TestTimeEvolutionProblem(QiskitAlgorithmsTestCase): """Test evolver problem class.""" def test_init_default(self): """Tests that all default fields are initialized correctly.""" hamiltonian = Y time = 2.5 initial_state = One evo_problem = TimeEvolutionProblem(hamiltonian, time, initial_state) expected_hamiltonian = Y expected_time = 2.5 expected_initial_state = One expected_aux_operators = None expected_t_param = None expected_param_value_dict = None self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(evo_problem.initial_state, expected_initial_state) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) @data(QuantumCircuit(1), Statevector([1, 0])) def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") with self.assertWarns(DeprecationWarning): hamiltonian = t_parameter * Z + Y time = 2 aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} evo_problem = TimeEvolutionProblem( hamiltonian, time, initial_state, aux_operators, t_param=t_parameter, param_value_map=param_value_dict, ) with self.assertWarns(DeprecationWarning): expected_hamiltonian = Y + t_parameter * Z expected_time = 2 expected_type = QuantumCircuit expected_aux_operators = [X, Y] expected_t_param = t_parameter expected_param_value_dict = {t_parameter: 3.2} with self.assertWarns(DeprecationWarning): self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) def test_validate_params(self): """Tests expected errors are thrown on parameters mismatch.""" param_x = Parameter("x") with self.subTest(msg="Parameter missing in dict."): with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test TrotterQRTE.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from scipy.linalg import expm from numpy.testing import assert_raises from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @ddt class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed @data( ( None, Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data ) @data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t"))) @unpack def test_trotter_qrte_trotter(self, operator, t_param): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" if not t_param is None: operator = SparsePauliOp(operator.paulis, np.array([t_param, 1])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] initial_state = QuantumCircuit(1) time = 3 num_timesteps = 2 evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param ) estimator = Estimator() expected_psi, expected_observables_result = self._get_expected_trotter_qrte( operator, time, num_timesteps, initial_state, aux_ops, t_param, ) expected_evolved_state = Statevector(expected_psi) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_evolved_state.data, ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [ (expected_observables_result[-1][0], {"variance": 0, "shots": 0}), (expected_observables_result[-1][1], {"variance": 0, "shots": 0}), ] means = [element[0] for element in aux_ops_result] expected_means = [element[0] for element in expected_aux_ops_result] np.testing.assert_array_almost_equal(means, expected_means) vars_and_shots = [element[1] for element in aux_ops_result] expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] observables_result = evolution_result.observables expected_observables_result = [ [(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result ] means = [sub_element[0] for element in observables_result for sub_element in element] expected_means = [ sub_element[0] for element in expected_observables_result for sub_element in element ] np.testing.assert_array_almost_equal(means, expected_means) for computed, expected in zip(vars_and_shots, expected_vars_and_shots): self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2) self.assertEqual(computed.pop("shots", 0), expected["shots"]) @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data ) @data( (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data, ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @data(([Pauli("X"), Pauli("Y")], None)) @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) @data( (X, QuantumCircuit(1)), (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), ( SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])), QuantumCircuit(1), ), ) @unpack def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): """Test TrotterQRTE with raising errors for evolution problem content.""" self._run_error_test(initial_state, operator, None, None, None, None) @staticmethod def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, aux_ops, t_param=t_param, param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) @staticmethod def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param): """Compute reference values for Trotter evolution via exact matrix exponentiation.""" dt = time / num_timesteps observables = [obs.to_matrix() for obs in observables] psi = Statevector(init_state).data if t_param is None: ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()] observable_results = [] observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]) for n in range(num_timesteps): if t_param is not None: time_value = (n + 1) * dt bound = operator.assign_parameters([time_value]) ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()] for op in ops: psi = expm(-1j * op * dt).dot(psi) observable_results.append( [np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables] ) return psi, observable_results if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Classical Imaginary Evolver.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit.quantum_info.states.statevector import Statevector from qiskit.quantum_info import SparsePauliOp from qiskit import QuantumCircuit from qiskit_algorithms import SciPyImaginaryEvolver from qiskit.opflow import PauliSumOp @ddt class TestSciPyImaginaryEvolver(QiskitAlgorithmsTestCase): """Test SciPy Imaginary Evolver.""" def create_hamiltonian_lattice(self, num_sites: int) -> SparsePauliOp: """Creates an Ising Hamiltonian on a lattice.""" j_const = 0.1 g_const = -1.0 zz_op = ["I" * i + "ZZ" + "I" * (num_sites - i - 2) for i in range(num_sites - 1)] x_op = ["I" * i + "X" + "I" * (num_sites - i - 1) for i in range(num_sites)] return SparsePauliOp(zz_op) * j_const + SparsePauliOp(x_op) * g_const @data( (Statevector.from_label("0"), 100, SparsePauliOp("X"), Statevector.from_label("-")), (Statevector.from_label("0"), 100, SparsePauliOp("-X"), Statevector.from_label("+")), ) @unpack def test_evolve( self, initial_state: Statevector, tau: float, hamiltonian: SparsePauliOp, expected_state: Statevector, ): """Initializes a classical imaginary evolver and evolves a state to find the ground state. It compares the solution with the first eigenstate of the hamiltonian. """ expected_state_matrix = expected_state.data evolution_problem = TimeEvolutionProblem(hamiltonian, tau, initial_state) classic_evolver = SciPyImaginaryEvolver(num_timesteps=300) result = classic_evolver.evolve(evolution_problem) with self.subTest("Amplitudes"): np.testing.assert_allclose( np.absolute(result.evolved_state.data), np.absolute(expected_state_matrix), atol=1e-10, rtol=0, ) with self.subTest("Phases"): np.testing.assert_allclose( np.angle(result.evolved_state.data), np.angle(expected_state_matrix), atol=1e-10, rtol=0, ) @data( ( Statevector.from_label("0" * 5), SparsePauliOp.from_sparse_list([("X", [i], 1) for i in range(5)], num_qubits=5), 5, ), (Statevector.from_label("0"), SparsePauliOp("X"), 1), ) @unpack def test_observables( self, initial_state: Statevector, hamiltonian: SparsePauliOp, nqubits: int ): """Tests if the observables are properly evaluated at each timestep.""" time_ev = 5.0 observables = {"Energy": hamiltonian, "Z": SparsePauliOp("Z" * nqubits)} evolution_problem = TimeEvolutionProblem( hamiltonian, time_ev, initial_state, aux_operators=observables ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=300) result = classic_evolver.evolve(evolution_problem) z_mean, z_std = result.observables["Z"] time_vector = result.times expected_z = 1 / (np.cosh(time_vector) ** 2 + np.sinh(time_vector) ** 2) expected_z_std = np.zeros_like(expected_z) np.testing.assert_allclose(z_mean, expected_z**nqubits, atol=1e-10, rtol=0) np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0) def test_quantum_circuit_initial_state(self): """Tests if the system can be evolved with a quantum circuit as an initial state.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, range(1, 3)) evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=qc ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) result = classic_evolver.evolve(evolution_problem) self.assertEqual(result.evolved_state, Statevector(qc)) def test_paulisumop_hamiltonian(self): """Tests if the hamiltonian can be a PauliSumOp""" with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp.from_list( [ ("XI", 1), ("IX", 1), ] ) observable = PauliSumOp.from_list([("ZZ", 1)]) evolution_problem = TimeEvolutionProblem( hamiltonian=hamiltonian, time=1.0, initial_state=Statevector.from_label("00"), aux_operators={"ZZ": observable}, ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) result = classic_evolver.evolve(evolution_problem) expected = 1 / (np.cosh(1.0) ** 2 + np.sinh(1.0) ** 2) np.testing.assert_almost_equal(result.aux_ops_evaluated["ZZ"][0], expected**2) def test_error_time_dependency(self): """Tests if an error is raised for a time dependent Hamiltonian.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=Statevector.from_label("0" * 3), t_param=0, ) classic_evolver = SciPyImaginaryEvolver(num_timesteps=5) with self.assertRaises(ValueError): classic_evolver.evolve(evolution_problem) def test_no_time_steps(self): """Tests if the evolver handles some edge cases related to the number of timesteps.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X"), time=1.0, initial_state=Statevector.from_label("0"), aux_operators={"Energy": SparsePauliOp("X")}, ) with self.subTest("0 timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyImaginaryEvolver(num_timesteps=0) classic_evolver.evolve(evolution_problem) with self.subTest("1 timestep"): classic_evolver = SciPyImaginaryEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_equal(result.times, np.array([0.0, 1.0])) with self.subTest("Negative timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyImaginaryEvolver(num_timesteps=-5) classic_evolver.evolve(evolution_problem) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Classical Real Evolver.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit_algorithms import SciPyRealEvolver, TimeEvolutionProblem from qiskit.quantum_info import Statevector, SparsePauliOp def zero(n): """Auxiliary function to create an initial state on n qubits.""" qr = QuantumRegister(n) qc = QuantumCircuit(qr) return Statevector(qc) def one(n): """Auxiliary function to create an initial state on n qubits.""" qr = QuantumRegister(n) qc = QuantumCircuit(qr) qc.x(qr) return Statevector(qc) @ddt class TestClassicalRealEvolver(QiskitAlgorithmsTestCase): """Test Classical Real Evolver.""" @data( (one(1), np.pi / 2, SparsePauliOp("X"), -1.0j * zero(1)), ( one(1).expand(zero(1)), np.pi / 2, SparsePauliOp(["XX", "YY"], [0.5, 0.5]), -1.0j * zero(1).expand(one(1)), ), ( one(1).expand(zero(1)), np.pi / 4, SparsePauliOp(["XX", "YY"], [0.5, 0.5]), ((one(1).expand(zero(1)) - 1.0j * zero(1).expand(one(1)))) / np.sqrt(2), ), (zero(12), np.pi / 2, SparsePauliOp("X" * 12), -1.0j * (one(12))), ) @unpack def test_evolve( self, initial_state: Statevector, time_ev: float, hamiltonian: SparsePauliOp, expected_state: Statevector, ): """Initializes a classical real evolver and evolves a state.""" evolution_problem = TimeEvolutionProblem(hamiltonian, time_ev, initial_state) classic_evolver = SciPyRealEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_allclose( result.evolved_state.data, expected_state.data, atol=1e-10, rtol=0, ) def test_observables(self): """Tests if the observables are properly evaluated at each timestep.""" initial_state = zero(1) time_ev = 10.0 hamiltonian = SparsePauliOp("X") observables = {"Energy": SparsePauliOp("X"), "Z": SparsePauliOp("Z")} evolution_problem = TimeEvolutionProblem( hamiltonian, time_ev, initial_state, aux_operators=observables ) classic_evolver = SciPyRealEvolver(num_timesteps=10) result = classic_evolver.evolve(evolution_problem) z_mean, z_std = result.observables["Z"] timesteps = z_mean.shape[0] time_vector = np.linspace(0, time_ev, timesteps) expected_z = 1 - 2 * (np.sin(time_vector)) ** 2 expected_z_std = np.zeros_like(expected_z) np.testing.assert_allclose(z_mean, expected_z, atol=1e-10, rtol=0) np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0) np.testing.assert_equal(time_vector, result.times) def test_quantum_circuit_initial_state(self): """Tests if the system can be evolved with a quantum circuit as an initial state.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, range(1, 3)) evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=2 * np.pi, initial_state=qc ) classic_evolver = SciPyRealEvolver(num_timesteps=500) result = classic_evolver.evolve(evolution_problem) np.testing.assert_almost_equal( result.evolved_state.data, np.array([1, 0, 0, 0, 0, 0, 0, 1]) / np.sqrt(2), decimal=10, ) def test_error_time_dependency(self): """Tests if an error is raised for time dependent hamiltonian.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=zero(3), t_param=0 ) classic_evolver = SciPyRealEvolver(num_timesteps=5) with self.assertRaises(ValueError): classic_evolver.evolve(evolution_problem) def test_no_time_steps(self): """Tests if the evolver handles some edge cases related to the number of timesteps.""" evolution_problem = TimeEvolutionProblem( hamiltonian=SparsePauliOp("X"), time=1.0, initial_state=zero(1), aux_operators={"Energy": SparsePauliOp("X")}, ) with self.subTest("0 timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyRealEvolver(num_timesteps=0) classic_evolver.evolve(evolution_problem) with self.subTest("1 timestep"): classic_evolver = SciPyRealEvolver(num_timesteps=1) result = classic_evolver.evolve(evolution_problem) np.testing.assert_equal(result.times, np.array([0.0, 1.0])) with self.subTest("Negative timesteps"): with self.assertRaises(ValueError): classic_evolver = SciPyRealEvolver(num_timesteps=-5) classic_evolver.evolve(evolution_problem) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Variational Quantum Imaginary Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit_algorithms.gradients import LinCombQGT, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp, Pauli from qiskit.utils import algorithm_globals from qiskit_algorithms import TimeEvolutionProblem, VarQITE from qiskit_algorithms.time_evolvers.variational import ( ImaginaryMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import Statevector @ddt class TestVarQITE(QiskitAlgorithmsTestCase): """Test Variational Quantum Imaginary Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_run_d_1_with_aux_ops(self): """Test VarQITE for d = 1 and t = 1 with evaluating auxiliary operator and the Forward Euler solver..""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.87984606025879, 2.04681975664763, 2.68980594039104, 2.75915988512186, 2.38796546567171, 1.78144857115127, 2.13109162826101, 1.9259609596416, ] thetas_expected_shots = [ 0.9392668013702317, 1.8756706968454864, 2.6915067128662398, 2.655420131540562, 2.174687086978046, 1.6997059390911056, 1.8056912289547045, 1.939353810908912, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator) var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient) var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = (-0.2177982985749799, 0.2556790598588627) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator) var_principle = ImaginaryMcLachlanPrinciple(qgt, gradient) var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = (-0.24629853310903974, 0.2518122871921184) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) def test_run_d_1_t_7(self): """Test VarQITE for d = 1 and t = 7 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 var_principle = ImaginaryMcLachlanPrinciple() time = 7 var_qite = VarQITE( ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25 ) thetas_expected = [ 0.828917365718767, 1.88481074798033, 3.14111335991238, 3.14125849601269, 2.33768562678401, 1.78670990729437, 2.04214275514208, 2.04009918594422, ] self._test_helper(observable, thetas_expected, time, var_qite, 2) def test_run_d_2(self): """Test VarQITE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 var_principle = ImaginaryMcLachlanPrinciple() time = 1 var_qite = VarQITE( ansatz, init_param_values, var_principle, ode_solver="RK45", num_timesteps=25 ) thetas_expected = [ 1.29495364023786, 1.08970061333559, 0.667488228710748, 0.500122687902944, 1.4377736672043, 1.22881086103085, 0.729773048146251, 1.01698854755226, 0.050807780587492, 0.294828474947149, 0.839305697704923, 0.663689581255428, ] self._test_helper(observable, thetas_expected, time, var_qite, 4) def test_run_d_1_time_dependent(self): """Test VarQITE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18] thetas_expected_shots = [1.83881002737137e-18, 2.43224994794434, -3.05311331771918e-18] state_expected = Statevector([0.34849948 + 0.0j, 0.93730897 + 0.0j]).to_dict() # the expected final state is Statevector([0.34849948+0.j, 0.93730897+0.j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() var_principle = ImaginaryMcLachlanPrinciple() var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qite.evolve(evolution_problem) evolved_state = evolution_result.evolved_state parameter_values = evolution_result.parameter_values[-1] for key, evolved_value in Statevector(evolved_state).to_dict().items(): # np.allclose works with complex numbers self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02)) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) var_principle = ImaginaryMcLachlanPrinciple() var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qite.evolve(evolution_problem) evolved_state = evolution_result.evolved_state parameter_values = evolution_result.parameter_values[-1] for key, evolved_value in Statevector(evolved_state).to_dict().items(): # np.allclose works with complex numbers self.assertTrue(np.allclose(evolved_value, state_expected[key], 1e-02)) for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qite, decimal): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qite.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=decimal ) if __name__ == "__main__": unittest.main()
https://github.com/ElePT/qiskit-algorithms-test
ElePT
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Variational Quantum Real Time Evolution algorithm.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterVector from qiskit_algorithms.gradients import LinCombQGT, DerivativeType, LinCombEstimatorGradient from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from qiskit.quantum_info import SparsePauliOp, Pauli, Statevector from qiskit_algorithms import TimeEvolutionProblem, VarQRTE from qiskit_algorithms.time_evolvers.variational import ( RealMcLachlanPrinciple, ) from qiskit.circuit.library import EfficientSU2 @ddt class TestVarQRTE(QiskitAlgorithmsTestCase): """Test Variational Quantum Real Time Evolution algorithm.""" def setUp(self): super().setUp() self.seed = 11 np.random.seed(self.seed) def test_time_dependent_hamiltonian(self): """Simple test case with a time dependent Hamiltonian.""" t_param = Parameter("t") hamiltonian = SparsePauliOp(["Z"], np.array(t_param)) x = ParameterVector("x", 3) circuit = QuantumCircuit(1) circuit.rz(x[0], 0) circuit.ry(x[1], 0) circuit.rz(x[2], 0) initial_parameters = np.array([0, np.pi / 2, 0]) def expected_state(time): # possible with pen and paper as the Hamiltonian is diagonal return 1 / np.sqrt(2) * np.array([np.exp(-0.5j * time**2), np.exp(0.5j * time**2)]) final_time = 0.75 evolution_problem = TimeEvolutionProblem(hamiltonian, t_param=t_param, time=final_time) estimator = Estimator() varqrte = VarQRTE(circuit, initial_parameters, estimator=estimator) result = varqrte.evolve(evolution_problem) final_parameters = result.parameter_values[-1] final_state = Statevector(circuit.bind_parameters(final_parameters)).to_dict() final_expected_state = expected_state(final_time) for key, expected_value in final_state.items(): self.assertTrue(np.allclose(final_expected_state[int(key)], expected_value, 1e-02)) def test_run_d_1_with_aux_ops(self): """Test VarQRTE for d = 1 and t = 0.1 with evaluating auxiliary operators and the Forward Euler solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) aux_ops = [Pauli("XX"), Pauli("YZ")] d = 1 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 2 init_param_values[0] = 1 time = 0.1 evolution_problem = TimeEvolutionProblem(observable, time, aux_operators=aux_ops) thetas_expected = [ 0.886841151529636, 1.53852629218265, 1.57099556659882, 1.5889216657174, 1.5996487153364, 1.57018939515742, 1.63950719260698, 1.53853696496673, ] thetas_expected_shots = [ 0.886975892820015, 1.53822607733397, 1.57058096749141, 1.59023223608564, 1.60105707043745, 1.57018042397236, 1.64010900210835, 1.53959523034133, ] with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [0.06836996703935797, 0.7711574493422457] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] expected_aux_ops = [ 0.070436, 0.777938, ] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) np.testing.assert_array_almost_equal( [result[0] for result in aux_ops], expected_aux_ops, decimal=2 ) def test_run_d_2(self): """Test VarQRTE for d = 2 and t = 1 with RK45 ODE solver.""" observable = SparsePauliOp.from_list( [ ("II", 0.2252), ("ZZ", 0.5716), ("IZ", 0.3435), ("ZI", -0.4347), ("YY", 0.091), ("XX", 0.091), ] ) d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) for i in range(len(parameters)): init_param_values[i] = np.pi / 4 estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) param_dict = dict(zip(parameters, init_param_values)) time = 1 var_qrte = VarQRTE(ansatz, param_dict, var_principle, ode_solver="RK45", num_timesteps=25) thetas_expected = [ 0.348407744196573, 0.919404626262464, 1.18189219371626, 0.771011177789998, 0.734384256533924, 0.965289520781899, 1.14441687204195, 1.17231927568571, 1.03014771379412, 0.867266309056347, 0.699606368428206, 0.610788576398685, ] self._test_helper(observable, thetas_expected, time, var_qrte) def test_run_d_1_time_dependent(self): """Test VarQRTE for d = 1 and a time-dependent Hamiltonian with the Forward Euler solver.""" t_param = Parameter("t") time = 1 observable = SparsePauliOp(["I", "Z"], np.array([0, t_param])) x, y, z = [Parameter(s) for s in "xyz"] ansatz = QuantumCircuit(1) ansatz.rz(x, 0) ansatz.ry(y, 0) ansatz.rz(z, 0) parameters = list(ansatz.parameters) init_param_values = np.zeros(len(parameters)) x_val = 0 y_val = np.pi / 2 z_val = 0 init_param_values[0] = x_val init_param_values[1] = y_val init_param_values[2] = z_val evolution_problem = TimeEvolutionProblem(observable, time, t_param=t_param) thetas_expected = [1.27675647831902e-18, 1.5707963267949, 0.990000000000001] thetas_expected_shots = [0.00534345821469238, 1.56260960200375, 0.990017403734316] # the expected final state is Statevector([0.62289306-0.33467034j, 0.62289306+0.33467034j]) with self.subTest(msg="Test exact backend."): algorithm_globals.random_seed = self.seed estimator = Estimator() qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected[i], decimal=2 ) with self.subTest(msg="Test shot-based backend."): algorithm_globals.random_seed = self.seed estimator = Estimator(options={"shots": 4 * 4096, "seed": self.seed}) qgt = LinCombQGT(estimator) gradient = LinCombEstimatorGradient(estimator, derivative_type=DerivativeType.IMAG) var_principle = RealMcLachlanPrinciple(qgt, gradient) var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=100 ) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal( float(parameter_value), thetas_expected_shots[i], decimal=2 ) def _test_helper(self, observable, thetas_expected, time, var_qrte): evolution_problem = TimeEvolutionProblem(observable, time) evolution_result = var_qrte.evolve(evolution_problem) parameter_values = evolution_result.parameter_values[-1] for i, parameter_value in enumerate(parameter_values): np.testing.assert_almost_equal(float(parameter_value), thetas_expected[i], decimal=4) if __name__ == "__main__": unittest.main()
https://github.com/orpgol/quantum_algorithms_qiskit
orpgol
import numpy as np from qiskit import BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram from qiskit import IBMQ, assemble, transpile from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import argparse, sys import time provider = IBMQ.load_account() parser = argparse.ArgumentParser() parser.add_argument('--s', help = 'Enter the secret string.') class Bernstein_Vazirani(object): def __init__(self, n, s): self.n = n self.s = s def _run_bv(self): bv_circuit = QuantumCircuit(self.n+1,self.n) bv_circuit.h(self.n) bv_circuit.barrier() bv_circuit.z(self.n) bv_circuit.barrier() for i in range(self.n): bv_circuit.h(i) bv_circuit.barrier() s = self.s[::-1] for q in range(self.n): if s[q] == '0': bv_circuit.i(q) else: bv_circuit.cx(q, self.n) bv_circuit.barrier() for i in range(self.n): bv_circuit.h(i) bv_circuit.barrier() for i in range(self.n): bv_circuit.measure(i, i) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self.qubits) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 8000 job = execute(bv_circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) try: result = job.result() except: print(job.error_message()) return -1, -1 answer = result.get_counts(bv_circuit) print(answer) fi = plot_histogram(answer) fi.savefig(fname = "bv_results4_8000.png") print("--%s seconds--" % result.time_taken) if __name__ == '__main__': start_time = time.time() args = parser.parse_args() s = args.s for i in s: if i != '0' and i != '1': raise AssertionError("s must be a bitstring") n = len(s) bv = Bernstein_Vazirani(n, s) bv._run_bv()
https://github.com/orpgol/quantum_algorithms_qiskit
orpgol
import numpy as np from qiskit import BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram from qiskit import IBMQ, assemble, transpile from qiskit.tools.monitor import job_monitor import argparse, sys import time provider = IBMQ.load_account() parser = argparse.ArgumentParser() parser.add_argument('--bits', help = 'Enter the number of bits you want to run with.') parser.add_argument('--algo', help = 'Enter either "constant" or "balanced".') class Deutsch_Jozsa(object): def __init__(self, n, algo): self.n = n self.algo = algo #change to self def _dj_oracle(self): oracle_qc = QuantumCircuit(self.n+1) if self.algo == "balanced": b = np.random.randint(1,2**self.n) b_str = format(b, '0'+str(self.n)+'b') for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) for qubit in range(self.n): oracle_qc.cx(qubit, self.n) for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) if self.algo == "constant": output = np.random.randint(2) if output == 1: oracle_qc.x(self.n) return oracle_qc.to_gate() def _dj_algorithm(self, oracle): dj_circuit = QuantumCircuit(self.n+1, self.n) dj_circuit.x(self.n) dj_circuit.barrier() dj_circuit.h(self.n) dj_circuit.barrier() for qubit in range(self.n): dj_circuit.h(qubit) dj_circuit.barrier() dj_circuit.append(oracle, range(n+1)) for qubit in range(self.n): dj_circuit.h(qubit) dj_circuit.barrier() for i in range(self.n): dj_circuit.measure(i, i) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self.qubits) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 8000 job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) try: result = job.result() except: print(job.error_message()) return -1, -1 answer = result.get_counts(dj_circuit) print(answer) fi = plot_histogram(answer) fi.savefig(fname = "dj_results5_8000.png") #fig = dj_circuit.draw(output = "mpl") #fig.savefig(fname = "dj6.png") print("--%s seconds--" % result.time_taken) if __name__ == '__main__': start_time = time.time() args = parser.parse_args() n = int((args.bits)) if n < 1: raise AssertionError("n must be a number of bits greater than 0") if args.algo != ('constant') and args.algo != ('balanced'): raise AssertionError("algo must be either balanced or constant") dj = Deutsch_Jozsa(n, args.algo) oracle_gate = dj._dj_oracle() dj_circuit = dj._dj_algorithm(oracle_gate)
https://github.com/orpgol/quantum_algorithms_qiskit
orpgol
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/orpgol/quantum_algorithms_qiskit
orpgol
from pprint import pprint import numpy as np import argparse from collections import defaultdict from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit.visualization import plot_histogram from sympy import Matrix, mod_inverse from qiskit import IBMQ from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy #IBMQ.save_account('<your acct number>') class Simons(object): def __init__(self, n, f): self._qr = QuantumRegister(2*n) self._cr = ClassicalRegister(n) self._oracle = self._create_oracle(f) def _create_oracle(self, f): n = len(list(f.keys())[0]) U = np.zeros(shape=(2 ** (2 * n), 2 ** (2 * n))) for a in range(2 ** n): ab = np.binary_repr(a, n) for k, v in f.items(): U[int(ab + k, 2), int(xor(ab, v) + k, 2)] = 1 return U def _create_circuit(self, oracle): circuit = QuantumCircuit(self._qr, self._cr) circuit.h(self._qr[:len(self._cr)]) circuit.barrier() circuit.unitary(oracle, self._qr, label='oracle') circuit.barrier() circuit.h(self._qr[:len(self._cr)]) circuit.measure(self._qr[:len(self._cr)], self._cr) return circuit def _solve(self, counts): # reverse inputs, remove all zero inputs, and sort counts = [(k[::-1], v) for k, v in counts.items() if not all([x == '0' for x in k])] counts.sort(key=lambda x: x[1], reverse=True) # construct sympy matrix matrix = Matrix([[int(i) for i in k] for k, _ in counts]) # gaussian elimination mod 2 matrix = matrix.rref(iszerofunc=lambda x: x % 2 == 0) matrix = matrix[0].applyfunc(lambda x: mod(x, 2)) # extract string n_rows, _ = matrix.shape s = [0] * len(self._cr) for r in range(n_rows): yi = [i for i, v in enumerate(list(matrix[r, :])) if v == 1] if len(yi) == 2: s[yi[0]] = '1' s[yi[1]] = '1' return s[::-1] def run(self, shots=1024, provider=None): circuit = self._create_circuit(self._oracle) if provider is None: # run the program on a QVM simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=shots) else: backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= len(self._qr) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) job = execute(circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) try: results = job.result() except: raise Exception(job.error_message()) counts = results.get_counts() print('Generated circuit: ') print(circuit.draw()) print('Circuit output:') print(counts) print("Time taken:", results.time_taken) return self._solve(counts) def mod(x, modulus): numer, denom = x.as_numer_denom() return numer * mod_inverse(denom, modulus) % modulus def xor(x, y): assert len(x) == len(y) n = len(x) return format(int(x, 2) ^ int(y, 2), f'0{n}b') def one_to_one_mapping(s): n = len(s) form_string = "{0:0" + str(n) + "b}" bit_map_dct = {} for idx in range(2 ** n): bit_string = np.binary_repr(idx, n) bit_map_dct[bit_string] = xor(bit_string, s) return bit_map_dct def two_to_one_mapping(s): mapping = one_to_one_mapping(s) n = len(mapping.keys()) // 2 new_range = np.random.choice(list(sorted(mapping.keys())), replace=False, size=n).tolist() mapping_pairs = sorted([(k, v) for k, v in mapping.items()], key=lambda x: x[0]) new_mapping = {} # f(x) = f(x xor s) for i in range(n): x = mapping_pairs[i] y = new_range[i] new_mapping[x[0]] = y new_mapping[x[1]] = y return new_mapping def main(): parser = argparse.ArgumentParser() parser.add_argument('string', help='Secret string s of length n') parser.add_argument('ftype', type=int, help='1 for one-to-one or 2 for two-to-one') parser.add_argument('--ibmq', action='store_true', help='Run on IBMQ') args = parser.parse_args() if args.ibmq: try: provider = IBMQ.load_account() except: raise Exception("Could not find saved IBMQ account.") assert all([x == '1' or x == '0' for x in args.string]), 'string argument must be a binary string.' n = len(args.string) if args.ftype == 1: mapping = one_to_one_mapping(args.string) elif args.ftype == 2: mapping = two_to_one_mapping(args.string) else: raise ValueError('Invalid function type.') print('Generated mapping:') pprint(mapping) simons = Simons(n, mapping) result = simons.run(provider=provider if args.ibmq else None) result = ''.join([str(x) for x in result]) # Check if result satisfies two-to-one function constraint success = np.array([mapping[x] == mapping[xor(x, result)] for x in mapping.keys()]).all() and not all([x == '0' for x in result]) if success: print(f'Oracle function is two-to-one with s = {result}.') else: print('Oracle is one-to-one.') if __name__ == '__main__': main()
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import bv_widget #bv_widget(2, "11") # initialization # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram n = 3 # number of qubits used to represent s s = '011' # the hidden binary string ## noise options options = { "plot": True, "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # We need a circuit with n qubits, plus one auxiliary qubit # Also need n classical bits to write the output to bv_circuit = QuantumCircuit(n+1, n) # put auxiliary in state |-> bv_circuit.h(n) bv_circuit.z(n) # Apply Hadamard gates before querying the oracle for i in range(n): bv_circuit.h(i) # Apply barrier bv_circuit.barrier() # Apply the inner-product oracle s = s[::-1] # reverse s to fit qiskit's qubit ordering for q in range(n): if s[q] == '0': bv_circuit.i(q) else: bv_circuit.cx(q, n) # Apply barrier bv_circuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(n): bv_circuit.h(i) # Measurement for i in range(n): bv_circuit.measure(i, i, basis='Ensemble',add_param='Z') bv_circuit.draw() # use local simulator backend = qiskit.BasicAer.get_backend('qasm_simulator') # without noise job = execute(bv_circuit, backend=backend, shots=1024) job_result = job.result() job_result.get_counts(bv_circuit) #with noise job1 = execute(bv_circuit, backend=backend, backend_options=options, shots=1024) job_result1 = job1.result() job_result1.get_counts(bv_circuit) plot_histogram(job.result().get_counts(), color='midnightblue', title="New Histogram") plot_histogram(job1.result().get_counts(), color='midnightblue', title="New Histogram") # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_bv_circuit = transpile(bv_circuit, backend) job = backend.run(transpiled_bv_circuit, shots=shots) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.widgets import bv_widget bv_widget(3, "011", hide_oracle=False) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import bv_widget #bv_widget(2, "11") # initialization # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram n = 3 # number of qubits used to represent s s = '011' # the hidden binary string ## noise options options = { "plot": True, "thermal_factor": 0.99, "decoherence_factor": .99, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[.9, 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # We need a circuit with n qubits, plus one auxiliary qubit # Also need n classical bits to write the output to bv_circuit = QuantumCircuit(n+1, n) # put auxiliary in state |-> bv_circuit.h(n) bv_circuit.z(n) # Apply Hadamard gates before querying the oracle for i in range(n): bv_circuit.h(i) # Apply barrier bv_circuit.barrier() # Apply the inner-product oracle s = s[::-1] # reverse s to fit qiskit's qubit ordering for q in range(n): if s[q] == '0': bv_circuit.i(q) else: bv_circuit.cx(q, n) # Apply barrier bv_circuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(n): bv_circuit.h(i) # Measurement for i in range(n): bv_circuit.measure(i, i, basis='Ensemble',add_param='Z') bv_circuit.draw() qc = QuantumCircuit(4,4) s = '101' string = '111' for i in range(3): if string[i] == '1': qc.x(i) qc.barrier() s = s[::-1] # reverse s to fit qiskit's qubit ordering for q in range(n): if s[q] == '0': qc.i(q) else: qc.cx(q, n) # Measurement for i in range(n): qc.measure(i, i, basis='Ensemble',add_param='Z') qc.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(qc, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(bv_circuit, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] #with noise job1 = execute(bv_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() #print(job_result1['results'][0]['data']['densitymatrix']) job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_bv_circuit = transpile(bv_circuit, backend) job = backend.run(transpiled_bv_circuit, shots=shots) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.widgets import bv_widget bv_widget(3, "011", hide_oracle=False) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
# @title Copyright 2020 The Cirq Developers # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq import cirq print("installed cirq.") qubits = cirq.GridQubit.square(3) print(qubits[0]) print(qubits) # This is an Pauli X gate. It is an object instance. x_gate = cirq.X # Applying it to the qubit at location (0, 0) (defined above) # turns it into an operation. x_op = x_gate(qubits[0]) print(x_op) cz = cirq.CZ(qubits[0], qubits[1]) x = cirq.X(qubits[2]) moment = cirq.Moment(x, cz) print(moment) cz01 = cirq.CZ(qubits[0], qubits[1]) x2 = cirq.X(qubits[2]) cz12 = cirq.CZ(qubits[1], qubits[2]) moment0 = cirq.Moment([cz01, x2]) moment1 = cirq.Moment([cz12]) circuit = cirq.Circuit((moment0, moment1)) print(circuit) q0, q1, q2 = [cirq.GridQubit(i, 0) for i in range(3)] circuit = cirq.Circuit() circuit.append([cirq.CZ(q0, q1), cirq.H(q2)]) print(circuit) circuit.append([cirq.H(q0), cirq.CZ(q1, q2)]) print(circuit) circuit = cirq.Circuit() circuit.append([cirq.CZ(q0, q1), cirq.H(q2), cirq.H(q0), cirq.CZ(q1, q2)]) print(circuit) from cirq.circuits import InsertStrategy circuit = cirq.Circuit() circuit.append([cirq.CZ(q0, q1)]) circuit.append([cirq.H(q0), cirq.H(q2)], strategy=InsertStrategy.EARLIEST) print(circuit) circuit = cirq.Circuit() circuit.append([cirq.H(q0), cirq.H(q1), cirq.H(q2)], strategy=InsertStrategy.NEW) print(circuit) circuit = cirq.Circuit() circuit.append([cirq.CZ(q1, q2)]) circuit.append([cirq.CZ(q1, q2)]) circuit.append([cirq.H(q0), cirq.H(q1), cirq.H(q2)], strategy=InsertStrategy.INLINE) print(circuit) circuit = cirq.Circuit() circuit.append([cirq.H(q0)]) circuit.append([cirq.CZ(q1, q2), cirq.H(q0)], strategy=InsertStrategy.NEW_THEN_INLINE) print(circuit) def my_layer(): yield cirq.CZ(q0, q1) yield [cirq.H(q) for q in (q0, q1, q2)] yield [cirq.CZ(q1, q2)] yield [cirq.H(q0), [cirq.CZ(q1, q2)]] circuit = cirq.Circuit() circuit.append(my_layer()) for x in my_layer(): print(x) print(circuit) circuit = cirq.Circuit(cirq.H(q0), cirq.H(q1)) print(circuit) circuit = cirq.Circuit(cirq.H(q0), cirq.CZ(q0, q1)) for moment in circuit: print(moment) circuit = cirq.Circuit(cirq.H(q0), cirq.CZ(q0, q1), cirq.H(q1), cirq.CZ(q0, q1)) print(circuit[1:3]) subcircuit = cirq.Circuit(cirq.H(q1), cirq.CZ(q0, q1), cirq.CZ(q2, q1), cirq.H(q1)) subcircuit_op = cirq.CircuitOperation(subcircuit.freeze()) circuit = cirq.Circuit(cirq.H(q0), cirq.H(q2), subcircuit_op) print(circuit) circuit = cirq.Circuit( cirq.CircuitOperation( cirq.FrozenCircuit(cirq.H(q1), cirq.CZ(q0, q1), cirq.CZ(q2, q1), cirq.H(q1)) ) ) print(circuit) subcircuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.CZ(q0, q1))) # Create a copy of subcircuit_op that repeats twice... repeated_subcircuit_op = subcircuit_op.repeat(2) # ...and another copy that replaces q0 with q2 to perform CZ(q2, q1). moved_subcircuit_op = subcircuit_op.with_qubit_mapping({q0: q2}) circuit = cirq.Circuit(repeated_subcircuit_op, moved_subcircuit_op) print(circuit) subcircuit_op = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q0))) circuit = cirq.Circuit( subcircuit_op.repeat(3), subcircuit_op.repeat(2).with_qubit_mapping({q0: q1}) ) print(circuit) qft_1 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q0))) qft_2 = cirq.CircuitOperation(cirq.FrozenCircuit(cirq.H(q1), cirq.CZ(q0, q1) ** 0.5, qft_1)) qft_3 = cirq.CircuitOperation( cirq.FrozenCircuit(cirq.H(q2), cirq.CZ(q1, q2) ** 0.5, cirq.CZ(q0, q2) ** 0.25, qft_2) ) # etc. # A large CircuitOperation with other sub-CircuitOperations. print('Original qft_3 CircuitOperation') print(qft_3) # Unroll the outermost CircuitOperation to a normal circuit. print('Single layer unroll:') print(qft_3.mapped_circuit(deep=False)) # Unroll all of the CircuitOperations recursively. print('Recursive unroll:') print(qft_3.mapped_circuit(deep=True))
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute, BasicAer from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.7, 0.5], 'ry':[0.7, 0.4], 'rz':[0.5, 0.5]}, "tsp_model_error": [0.5, 0.8], "thermal_factor": 0.7, "decoherence_factor": 0.8, "depolarization_factor": 0.5, "bell_depolarization_factor": 0.4, "decay_factor": 0.6, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator #backend = qiskit.BasicAer.get_backend('qasm_simulator') print('Qasm simulator') sim_backend = BasicAer.get_backend('qasm_simulator') # without noise job = execute(dj_circuit, backend=sim_backend, shots=1024) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) #job_result['results'][0]['data']['ensemble_probability'] job_result print(job_result.get_counts(dj_circuit)) #with noise job1 = execute(dj_circuit, backend=sim_backend, backend_options=options, shots=1024) job_result1 = job1.result() job_result1 print(job_result1.get_counts(dj_circuit)) #print(job_result1['results'][0]['data']['densitymatrix']) #job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result.get_counts(dj_circuit) x= no_noise.keys() y = no_noise.values() plt.bar(x, y, width=0.6, label='No Noise') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities') plt.show() noisy=job_result1.get_counts(dj_circuit) x1 = noisy.keys() y1 = noisy.values() plt.bar(x1, y1, width=0.6, label='Noisy', color='coral') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities Over Noisy data') plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() print(job_result['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.9, 0.9], 'ry':[0.9, 0.9], 'rz':[0.9, 0.9]}, "tsp_model_error": [0.9, 0.9], "thermal_factor": 0.9, "decoherence_factor": 0.9, "depolarization_factor": 0.9, "bell_depolarization_factor": 0.9, "decay_factor": 0.89, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle # dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) #job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result = job.result() #job_result1 = job1.result() #print(job_result['results'][0]['data']['densitymatrix']) #print(job_result1['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] backend = qiskit.BasicAer.get_backend('dm_simulator') job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] x= no_noise.keys() y = no_noise.values() plt.bar(x, y, width=0.6, label='No Noise') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities') plt.figure(figsize=(3, 3)) plt.show() noisy=job_result1['results'][0]['data']['ensemble_probability'] x1 = noisy.keys() y1 = noisy.values() plt.bar(x1, y1, width=0.6, label='Noisy', color='coral') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities Over Noisy data') plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() ##NO_NOISE backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() print(job_result['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator ## Noisy job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() print(job_result1['results'][0]['data']['densitymatrix']) from qiskit.visualization import plot_state_city get_ipython().run_line_magic('matplotlib', 'inline') plot_state_city(job_result1['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise") ##no_noise_ensemble_probabs job_result['results'][0]['data']['ensemble_probability'] ##noisy_ensemble_probabs job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.9, 0.9], 'ry':[0.9, 0.9], 'rz':[0.9, 0.9]}, "tsp_model_error": [0.9, 0.9], "thermal_factor": 0.9, "decoherence_factor": 0.9, "depolarization_factor": 0.9, "bell_depolarization_factor": 0.9, "decay_factor": 0.89, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle # dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) #job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result = job.result() #job_result1 = job1.result() #print(job_result['results'][0]['data']['densitymatrix']) #print(job_result1['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] backend = qiskit.BasicAer.get_backend('dm_simulator') job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] x= no_noise.keys() y = no_noise.values() plt.bar(x, y, width=0.6, label='No Noise') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities') plt.figure(figsize=(3, 3)) plt.show() noisy=job_result1['results'][0]['data']['ensemble_probability'] x1 = noisy.keys() y1 = noisy.values() plt.bar(x1, y1, width=0.6, label='Noisy', color='coral') plt.xlabel('combination of bits') plt.ylabel('Probablities') plt.title('Ensemble Probabilities Over Noisy data') plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() ##NO_NOISE backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() print(job_result['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator ## Noisy job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() print(job_result1['results'][0]['data']['densitymatrix']) from qiskit.visualization import plot_state_city get_ipython().run_line_magic('matplotlib', 'inline') plot_state_city(job_result1['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise") ##no_noise_ensemble_probabs job_result['results'][0]['data']['ensemble_probability'] ##noisy_ensemble_probabs job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#from qiskit_textbook.widgets import dj_widget #dj_widget(size="small", case="balanced") # initialization ####################################################################################################################### qiskit_edit_1 from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### import numpy as np options = { 'plot': True, "rotation_error": {'rx':[0.7, 0.5], 'ry':[0.7, 0.4], 'rz':[0.5, 0.5]}, "tsp_model_error": [0.5, 0.8], "thermal_factor": 0.7, "decoherence_factor": 0.8, "depolarization_factor": 0.5, "bell_depolarization_factor": 0.4, "decay_factor": 0.6, } # importing Qiskit #from qiskit import IBMQ, Aer #from qiskit.providers.ibmq import least_busy #from qiskit import QuantumCircuit, assemble, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw() balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw() dj_circuit = QuantumCircuit(n+1, n+1) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') # Display circuit dj_circuit.draw() # use local simulator backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] #with noise job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() #print(job_result1['results'][0]['data']['densitymatrix']) job_result1['results'][0]['data']['ensemble_probability'] no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i, basis='Ensemble', add_param='Z') return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() ##no_noise backend = qiskit.BasicAer.get_backend('dm_simulator') job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) ##noisy job1 = execute(dj_circuit, backend=backend,backend_options=options, shots=1) job_result1 = job1.result() no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] no_noise #print(noisy) #print(job_result1['results'][0]['data']['densitymatrix']) ##plot_histogram(answer) ###no histrogram because of single shot in DM simulator noisy no_noise=job_result['results'][0]['data']['ensemble_probability'] noisy=job_result1['results'][0]['data']['ensemble_probability'] labels = noisy.keys() without_noise = no_noise.values() with_noise = noisy.values() x = np.arange(len(labels)) # the label locations width = 0.5 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show() #plot_histogram(ax) backend = qiskit.BasicAer.get_backend('dm_simulator') # without noise job = execute(dj_circuit, backend=backend, shots=1) job_result = job.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] #with noise job1 = execute(dj_circuit, backend=backend, backend_options=options, shots=1) job_result1 = job1.result() #print(job_result['results'][0]['data']['densitymatrix']) job_result['results'][0]['data']['ensemble_probability'] job_result1['results'][0]['data']['ensemble_probability'] from qiskit.visualization import plot_state_city %matplotlib inline plot_state_city(job_result['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise") from qiskit.visualization import plot_state_city %matplotlib inline plot_state_city(job_result1['results'][0]['data']['densitymatrix'], color=['midnightblue', 'midnightblue'],title="Density Matrix_no_noise") plot_histogram(job_result['results'][0]['data']['ensemble_probability'], color='blue', title="No_noise") plot_histogram(job_result1['results'][0]['data']['ensemble_probability'], color='coral', title="Noisy") # Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3) job = backend.run(transpiled_dj_circuit) job_monitor(job, interval=2) # Get the results of the computation results = job.result() answer = results.get_counts() plot_histogram(answer) from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit import qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer # import basic plot tools from qiskit.visualization import plot_histogram def example_grover_iteration(): """Small circuit with 5/16 solutions""" # Do circuit qc = QuantumCircuit(4) # Oracle qc.h([2,3]) qc.ccx(0,1,2) qc.h(2) qc.x(2) qc.ccx(0,2,3) qc.x(2) qc.h(3) qc.x([1,3]) qc.h(2) qc.mct([0,1,3],2) qc.x([1,3]) qc.h(2) # Diffuser qc.h(range(3)) qc.x(range(3)) qc.z(3) qc.mct([0,1,2],3) qc.x(range(3)) qc.h(range(3)) qc.z(3) return qc # Create controlled-Grover grit = example_grover_iteration().to_gate() grit.label = "Grover" cgrit = grit.control() def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(4) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qft_dagger = qft(4).to_gate().inverse() qft_dagger.label = "QFT†" # Create QuantumCircuit t = 4 # no. of counting qubits n = 4 # no. of searching qubits qc = QuantumCircuit(n+t, t) # Circuit with n+t qubits and t classical bits # Initialize all qubits to |+> for qubit in range(t+n): qc.h(qubit) # Begin controlled Grover iterations iterations = 1 for qubit in range(t): for i in range(iterations): qc.append(cgrit, [qubit] + [*range(t, n+t)]) iterations *= 2 # Do inverse QFT on counting qubits qc.append(qft_dagger, range(t)) # Measure counting qubits qc.measure(range(t), range(t)) # Display the circuit qc.draw() # Execute and see results aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) job = aer_sim.run(qobj) hist = job.result().get_counts() plot_histogram(hist) measured_str = max(hist, key=hist.get) measured_int = int(measured_str,2) print("Register Output = %i" % measured_int) theta = (measured_int/(2**t))*math.pi*2 print("Theta = %.5f" % theta) N = 2**n M = N * (math.sin(theta/2)**2) print("No. of Solutions = %.1f" % (N-M)) m = t - 1 # Upper bound: Will be less than this err = (math.sqrt(2*M*N) + N/(2**(m+1)))*(2**(-m)) print("Error < %.2f" % err) def calculate_M(measured_int, t, n): """For Processing Output of Quantum Counting""" # Calculate Theta theta = (measured_int/(2**t))*math.pi*2 print("Theta = %.5f" % theta) # Calculate No. of Solutions N = 2**n M = N * (math.sin(theta/2)**2) print("No. of Solutions = %.1f" % (N-M)) # Calculate Upper Error Bound m = t - 1 #Will be less than this (out of scope) err = (math.sqrt(2*M*N) + N/(2**(m+1)))*(2**(-m)) print("Error < %.2f" % err) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
# initialization ####################################################################################################################### qiskit_edit_1 import qiskit from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep import numpy as np from qiskit.visualization import plot_histogram ######################################################################################################################### options = { 'plot': True, "rotation_error": {'rx':[0.7, 0.5], 'ry':[0.7, 0.4], 'rz':[0.5, 0.5]}, "tsp_model_error": [0.5, 0.8], "thermal_factor": 0.7, "decoherence_factor": 0.8, "depolarization_factor": 0.5, "bell_depolarization_factor": 0.4, "decay_factor": 0.6, } qc = QuantumCircuit(3,3) qc.h(2) qc.draw() qc.cu1(np.pi/2, 1, 2) # CROT from qubit 1 to qubit 2 qc.draw() qc.cu1(np.pi/4, 0, 2) # CROT from qubit 2 to qubit 0 qc.draw() qc.h(1) qc.cu1(np.pi/2, 0, 1) # CROT from qubit 0 to qubit 1 qc.h(0) qc.draw() qc.swap(0,2) qc.draw() def qft_rotations(circuit, n): if n == 0: # Exit function if circuit is empty return circuit n -= 1 # Indexes start from 0 circuit.h(n) # Apply the H-gate to the most significant qubit for qubit in range(n): # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cu1(np.pi/2**(n-qubit), qubit, n) qc = QuantumCircuit(4,4) qft_rotations(qc,4) qc.draw() from qiskit_textbook.widgets import scalable_circuit scalable_circuit(qft_rotations) def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cu1(np.pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) # Let's see how it looks: qc = QuantumCircuit(4,4) qft_rotations(qc,4) qc.draw() scalable_circuit(qft_rotations) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def measure(circuit, n): for i in range(n): qc.measure(i, i, basis='Ensemble', add_param='Z') def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit n=4 # Let's see how it looks: qc = QuantumCircuit(4,4) qft(qc,4) measure(qc,4) qc.draw() scalable_circuit(qft) bin(5) # Create the circuit qc = QuantumCircuit(3,3) # Encode the state 5 qc.x(0) qc.x(2) qc.draw() backend = qiskit.BasicAer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=1024) job_result = job.result() job.result.get_counts(qc) #job_result #sim = Aer.get_backend("aer_simulator") #qc_init = qc.copy() #qc_init.save_statevector() #statevector = sim.run(qc_init).result().get_statevector() #plot_bloch_multivector(statevector) qft(qc,3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector) def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n,n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates nqubits = 3 number = 5 qc = QuantumCircuit(nqubits, nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.draw() qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 2048 transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector from numpy.random import randint import numpy as np print("Imports Successful") qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) qc.barrier() # Alice now sends the qubit to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(1,1) # Alice prepares qubit in state |+> qc.h(0) # Alice now sends the qubit to Bob # but Eve intercepts and tries to read it qc.measure(0, 0) qc.barrier() # Eve then passes this on to Bob # who measures it in the X-basis qc.h(0) qc.measure(0,0) # Draw and simulate circuit display(qc.draw()) aer_sim = Aer.get_backend('aer_simulator') job = aer_sim.run(assemble(qc)) plot_histogram(job.result().get_counts()) np.random.seed(seed=0) n = 100 np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) print(alice_bits) np.random.seed(seed=0) n = 100 ## Step 1 #Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) print(alice_bases) def encode_message(bits, bases): message = [] for i in range(n): qc = QuantumCircuit(1,1) if bases[i] == 0: # Prepare qubit in Z-basis if bits[i] == 0: pass else: qc.x(0) else: # Prepare qubit in X-basis if bits[i] == 0: qc.h(0) else: qc.x(0) qc.h(0) qc.barrier() message.append(qc) return message np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) print('bit = %i' % alice_bits[0]) print('basis = %i' % alice_bases[0]) message[0].draw() print('bit = %i' % alice_bits[4]) print('basis = %i' % alice_bases[4]) message[4].draw() np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) print(bob_bases) def measure_message(message, bases): backend = Aer.get_backend('aer_simulator') measurements = [] for q in range(n): if bases[q] == 0: # measuring in Z-basis message[q].measure(0,0) if bases[q] == 1: # measuring in X-basis message[q].h(0) message[q].measure(0,0) aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(message[q], shots=1, memory=True) result = aer_sim.run(qobj).result() measured_bit = int(result.get_memory()[0]) measurements.append(measured_bit) return measurements np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) message[0].draw() message[6].draw() print(bob_results) def remove_garbage(a_bases, b_bases, bits): good_bits = [] for q in range(n): if a_bases[q] == b_bases[q]: # If both used the same basis, add # this to the list of 'good' bits good_bits.append(bits[q]) return good_bits np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) print(alice_key) np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) print(bob_key) def sample_bits(bits, selection): sample = [] for i in selection: # use np.mod to make sure the # bit we sample is always in # the list range i = np.mod(i, len(bits)) # pop(i) removes the element of the # list at index 'i' sample.append(bits.pop(i)) return sample np.random.seed(seed=0) n = 100 ## Step 1 # Alice generates bits alice_bits = randint(2, size=n) ## Step 2 # Create an array to tell us which qubits # are encoded in which bases alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Step 3 # Decide which basis to measure in: bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) bob_key = remove_garbage(alice_bases, bob_bases, bob_results) ## Step 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample print(bob_key) print(alice_key) print("key length = %i" % len(alice_key)) np.random.seed(seed=3) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) print(alice_bits) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) print(alice_bases) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) print(intercepted_message) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) message[0].draw() np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) np.random.seed(seed=3) ## Step 1 alice_bits = randint(2, size=n) ## Step 2 alice_bases = randint(2, size=n) message = encode_message(alice_bits, alice_bases) ## Interception!! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) ## Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) ## Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) ## Step 5 sample_size = 15 bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) print(" bob_sample = " + str(bob_sample)) alice_sample = sample_bits(alice_key, bit_selection) print("alice_sample = "+ str(alice_sample)) bob_sample == alice_sample n = 100 # Step 1 alice_bits = randint(2, size=n) alice_bases = randint(2, size=n) # Step 2 message = encode_message(alice_bits, alice_bases) # Interception! eve_bases = randint(2, size=n) intercepted_message = measure_message(message, eve_bases) # Step 3 bob_bases = randint(2, size=n) bob_results = measure_message(message, bob_bases) # Step 4 bob_key = remove_garbage(alice_bases, bob_bases, bob_results) alice_key = remove_garbage(alice_bases, bob_bases, alice_bits) # Step 5 sample_size = 15 # Change this to something lower and see if # Eve can intercept the message without Alice # and Bob finding out bit_selection = randint(n, size=sample_size) bob_sample = sample_bits(bob_key, bit_selection) alice_sample = sample_bits(alice_key, bit_selection) if bob_sample != alice_sample: print("Eve's interference was detected.") else: print("Eve went undetected!") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit ####################################################################################################################### qiskit_edit_1 import qiskit from qiskit import QuantumCircuit, execute from qiskit import QuantumRegister, ClassicalRegister from qiskit.tools.monitor import job_monitor from qiskit import * import time import matplotlib.pyplot as plt import argparse import sys from concurrent.futures import ThreadPoolExecutor import resource from time import sleep ######################################################################################################################### # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) qpe.draw() for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU repetitions *= 2 qpe.draw() def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) qpe.draw() IBMQ.load_account() from qiskit.tools.monitor import job_monitor provider = IBMQ.get_provider(hub='ibm-q') santiago = provider.get_backend('ibmq_santiago') # Run with 2048 shots shots = 2048 t_qpe = transpile(qpe, santiago, optimization_level=3) job = santiago.run(t_qpe, shots=shots) job_monitor(job) # get the results from the computation results = job.result() answer = results.get_counts(qpe) plot_histogram(answer) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import QFT from numpy import pi from qiskit.quantum_info import Statevector from matplotlib import pyplot as plt import numpy as np # Loading your IBM Q account(s) provider = IBMQ.load_account() one_step_circuit = QuantumCircuit(6, name=' ONE STEP') # Coin operator one_step_circuit.h([4,5]) one_step_circuit.z([4,5]) one_step_circuit.cz(4,5) one_step_circuit.h([4,5]) one_step_circuit.draw() # Shift operator function for 4d-hypercube def shift_operator(circuit): for i in range(0,4): circuit.x(4) if i%2==0: circuit.x(5) circuit.ccx(4,5,i) shift_operator(one_step_circuit) one_step_gate = one_step_circuit.to_instruction() one_step_circuit.draw() one_step_circuit.inverse().draw() # Make controlled gates inv_cont_one_step = one_step_circuit.inverse().control() inv_cont_one_step_gate = inv_cont_one_step.to_instruction() cont_one_step = one_step_circuit.control() cont_one_step_gate = cont_one_step.to_instruction() inv_qft_gate = QFT(4, inverse=True).to_instruction() qft_gate = QFT(4, inverse=False).to_instruction() QFT(4, inverse=True).decompose().draw("mpl") phase_circuit = QuantumCircuit(6, name=' phase oracle ') # Mark 1011 phase_circuit.x(2) phase_circuit.h(3) phase_circuit.mct([0,1,2], 3) phase_circuit.h(3) phase_circuit.x(2) # Mark 1111 phase_circuit.h(3) phase_circuit.mct([0,1,2],3) phase_circuit.h(3) phase_oracle_gate = phase_circuit.to_instruction() # Phase oracle circuit phase_oracle_circuit = QuantumCircuit(11, name=' PHASE ORACLE CIRCUIT ') phase_oracle_circuit.append(phase_oracle_gate, [4,5,6,7,8,9]) phase_circuit.draw() # Mark q_4 if the other qubits are non-zero mark_auxiliary_circuit = QuantumCircuit(5, name=' mark auxiliary ') mark_auxiliary_circuit.x([0,1,2,3,4]) mark_auxiliary_circuit.mct([0,1,2,3], 4) mark_auxiliary_circuit.z(4) mark_auxiliary_circuit.mct([0,1,2,3], 4) mark_auxiliary_circuit.x([0,1,2,3,4]) mark_auxiliary_gate = mark_auxiliary_circuit.to_instruction() mark_auxiliary_circuit.draw() # Phase estimation phase_estimation_circuit = QuantumCircuit(11, name=' phase estimation ') phase_estimation_circuit.h([0,1,2,3]) for i in range(0,4): stop = 2**i for j in range(0,stop): phase_estimation_circuit.append(cont_one_step, [i,4,5,6,7,8,9]) # Inverse fourier transform phase_estimation_circuit.append(inv_qft_gate, [0,1,2,3]) # Mark all angles theta that are not 0 with an auxiliary qubit phase_estimation_circuit.append(mark_auxiliary_gate, [0,1,2,3,10]) # Reverse phase estimation phase_estimation_circuit.append(qft_gate, [0,1,2,3]) for i in range(3,-1,-1): stop = 2**i for j in range(0,stop): phase_estimation_circuit.append(inv_cont_one_step, [i,4,5,6,7,8,9]) phase_estimation_circuit.barrier(range(0,10)) phase_estimation_circuit.h([0,1,2,3]) # Make phase estimation gate phase_estimation_gate = phase_estimation_circuit.to_instruction() phase_estimation_circuit.draw() # Implementation of the full quantum walk search algorithm theta_q = QuantumRegister(4, 'theta') node_q = QuantumRegister(4, 'node') coin_q = QuantumRegister(2, 'coin') auxiliary_q = QuantumRegister(1, 'auxiliary') creg_c2 = ClassicalRegister(4, 'c') circuit = QuantumCircuit(theta_q, node_q, coin_q, auxiliary_q, creg_c2) # Apply Hadamard gates to the qubits that represent the nodes and the coin circuit.h([4,5,6,7,8,9]) iterations = 2 for i in range(0,iterations): circuit.append(phase_oracle_gate, [4,5,6,7,8,9]) circuit.append(phase_estimation_gate, [0,1,2,3,4,5,6,7,8,9,10]) circuit.measure(node_q[0], creg_c2[0]) circuit.measure(node_q[1], creg_c2[1]) circuit.measure(node_q[2], creg_c2[2]) circuit.measure(node_q[3], creg_c2[3]) circuit.draw() backend = Aer.get_backend('qasm_simulator') job = execute( circuit, backend, shots=1024 ) hist = job.result().get_counts() plot_histogram( hist ) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
import numpy as np from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Simon from qiskit.aqua.components.oracles import TruthTableOracle bitmaps = [ '01101001', '10011001', '01100110' ] oracle = TruthTableOracle(bitmaps) def compute_mask(input_bitmaps): vals = list(zip(*input_bitmaps))[::-1] def find_pair(): for i in range(len(vals)): for j in range(i + 1, len(vals)): if vals[i] == vals[j]: return i, j return 0, 0 k1, k2 = find_pair() return np.binary_repr(k1 ^ k2, int(np.log2(len(input_bitmaps[0])))) mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') simon = Simon(oracle) backend = BasicAer.get_backend('qasm_simulator') result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask) bitmaps = [ '00011110', '01100110', '10101010' ] mask = compute_mask(bitmaps) print(f'The groundtruth mask is {mask}.') oracle = TruthTableOracle(bitmaps) simon = Simon(oracle) result = simon.run(QuantumInstance(backend, shots=1024)) print('The mask computed using Simon is {}.'.format(result['result'])) assert(result['result'] == mask)
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
# Importing everything from qiskit import QuantumCircuit from qiskit import IBMQ, Aer, transpile from qiskit.visualization import plot_histogram def create_bell_pair(): """ Returns: QuantumCircuit: Circuit that produces a Bell pair """ qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): """Encodes a two-bit message on qc using the superdense coding protocol Args: qc (QuantumCircuit): Circuit to encode message on qubit (int): Which qubit to add the gate to msg (str): Two-bit message to send Returns: QuantumCircuit: Circuit that, when decoded, will produce msg Raises: ValueError if msg is wrong length or contains invalid characters """ if len(msg) != 2 or not set(msg).issubset({"0","1"}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc # Charlie creates the entangled pair between Alice and Bob qc = create_bell_pair() # We'll add a barrier for visual separation qc.barrier() # At this point, qubit 0 goes to Alice and qubit 1 goes to Bob # Next, Alice encodes her message onto qubit 1. In this case, # we want to send the message '10'. You can try changing this # value and see how it affects the circuit message = '10' qc = encode_message(qc, 1, message) qc.barrier() # Alice then sends her qubit to Bob. # After receiving qubit 0, Bob applies the recovery protocol: qc = decode_message(qc) # Finally, Bob measures his qubits to read Alice's message qc.measure_all() # Draw our output qc.draw() aer_sim = Aer.get_backend('aer_simulator') result = aer_sim.run(qc).result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) from qiskit import IBMQ from qiskit.providers.ibmq import least_busy shots = 1024 # Load local account information IBMQ.load_account() # Get the least busy backend provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit t_qc = transpile(qc, backend, optimization_level=3) job = backend.run(t_qc) # Monitoring our job from qiskit.tools.monitor import job_monitor job_monitor(job) # Plotting our result result = job.result() plot_histogram(result.get_counts(qc)) correct_results = result.get_counts(qc)[message] accuracy = (correct_results/shots)*100 print(f"Accuracy = {accuracy:.2f}%") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
vandnaChaturvedi
# 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)