repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, MetalGUI from qiskit_metal import Dict, Headings design = designs.DesignPlanar() gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket from qiskit_metal.qlibrary.tlines.meandered import RouteMeander design.overwrite_enabled = True N_x =4 N_y =3 design.chips.main.size.size_x = str((N_x+1) * 3)+'mm' design.chips.main.size.size_y = str((N_y+1) * 3)+'mm' design.chips.main.size.center_x = str((N_x-1) * 1.5)+'mm' design.chips.main.size.center_y = str((N_y-0.5) * 1.5)+'mm' #Loop to generate and draw the qubits for x in range(N_x): for y in range(N_y): options = dict(pos_x= str(x*3000)+'um', pos_y = str(y*3000 + (x%2)*1500)+'um', orientation = "-90", connection_pads = dict( B0 = dict(loc_W=-1, loc_H=-1, pad_width='75um'), B1 = dict(loc_W=-1, loc_H=+1, pad_width='120um'), B2 = dict(loc_W=+1, loc_H=-1, pad_width='120um'), B3 = dict(loc_w = +1, loc_H = +1, pad_width='90um'))) obj=TransmonPocket(design,'Q_'+str(x)+'_'+str(y),options) gui.rebuild() gui.autoscale() for x in range(N_x): for y in range(N_y): #"upward" connection, avoids drawing connectors for 'top' row. Changes connector length by +/-50um to avoid frequency collisions if y<(N_y-1): connectorAD = RouteMeander(design,'CU_'+str(x)+'_'+str(y),options = dict(total_length = str(7+(y%2)*0.5)+'mm', fillet = "99um",lead=dict( start_straight='0.5mm', end_straight='0.25mm'), meander = dict(asymmetry='-700um'), pin_inputs = dict( start_pin=dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B0'), end_pin=dict( component='Q_'+str(x)+'_'+str(y+1), pin='B3')))) #"sideways" connection, avoids drawing for far right col, and for top qubit in odd col. Changes connector length by +/- 25um #to avoid frequency collisions if x<(N_x-1) and (not(x%2 and y==(N_y-1))): connectorBC = RouteMeander(design,'CS_'+str(x)+'_'+str(y),options= dict(total_length = str(6+(y%2)*0.5)+'mm', fillet = "99um",lead=Dict( start_straight='0.3mm', end_straight='0.25mm'), meander = Dict(asymmetry='-200um'), pin_inputs = Dict( start_pin=Dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B1'), end_pin=Dict( component='Q_'+str(x+1)+'_'+str(y+(x%2)), pin='B2')))) gui.rebuild() gui.autoscale() gui.screenshot() from qiskit_metal.analyses.quantization import LOManalysis c1 = LOManalysis(design, "q3d") c1.sim.setup c1.sim.setup.name = 'LOM' c1.sim.setup.max_passes = 14 #To change multiple settings use the following method: #c1.sim.setup_update(name = 'LOM', max_passes = 14) c1.sim.setup c1.sim.run(components=['Q_0_0'], open_terminations=[('Q_0_0', 'B0'), ('Q_0_0', 'B1'), ('Q_0_0', 'B2'), ('Q_0_0', 'B3')]) c1.setup.junctions = Dict({'Lj': 12.31, 'Cj': 2}) c1.setup.freq_readout = 6.6 c1.setup.freq_bus = [6.0, 6.2,6.4] c1.run_lom() c1.sim.close() chip_gds = design.renderers.gds chip_gds.options['no_cheese']['buffer'] = '50um' chip_gds.options['path_filename'] = '../../resources/Fake_Junctions.GDS' chip_gds.export_to_gds("NxN_Chip.gds") gui.main_window.close()
https://github.com/gatchan00/QPlex
gatchan00
import matplotlib.pyplot as plt import matplotlib.axes as axes import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import Operator, run_algorithm from qiskit.aqua.input import EnergyInput from qiskit.aqua.translators.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance # setup aqua logging import logging from qiskit.aqua import set_qiskit_aqua_logging # set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log from docplex.mp.model import Model from qiskit.aqua.translators.ising import docplex def createMatrixRestrictionDefaultOrig(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r return matrix def wrapper(qbits_encode, input_vars, options): if options['restriction'] == 'default': matrix = createMatrixRestrictionDefault(qbits_encode, input_vars, options['input_rest'], options['beta']) return matrix def createMatrixSinRestrictionDefault(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = 1#-input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionDefaultOrig2(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = r matrix[col, row] = r for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionDefault(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1000 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = -r matrix[col, row] = -r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def createMatrixRestrictionBackup1(qbits_code, input_vars, input_rest, beta): num_vars = len(input_vars) tamMatrix = num_vars * qbits_code # matrix is num_vars * qbits used for each var p = 1 # very high number matrix = np.zeros([tamMatrix, tamMatrix]) for row in range(tamMatrix): for col in range(row, tamMatrix): dom_row = row // qbits_code dom_col = col // qbits_code if row == col: matrix[row, col] = -input_vars[dom_row] * 2 ** (row % qbits_code) else: if dom_row == dom_col: # Si estamos en un X0 X1 o X0 X2... no hay relación, se pone 0 matrix[row, col] = 0 matrix[col, row] = 0 else: r = -p / beta * (input_rest[dom_row] * input_rest[dom_col]) matrix[row, col] = -r matrix[col, row] = -r #print(matrix) for row in range(tamMatrix): acu = 0. for col in range(row+1, tamMatrix): acu += matrix[row, col] matrix[row, row] = (matrix[row, row]/2) + (acu/4) return matrix def getPauliMatrix(matrix): rows = matrix.shape[0] paulis = [] for row_pos in range(rows): for col_pos in range(matrix.shape[1]): temp = {} temp["imag"] = 0.0 temp["real"] = matrix[row_pos, col_pos] label_pauli = ["I" for _ in range(rows)] if row_pos != col_pos: label_pauli[row_pos] = 'Z' label_pauli[col_pos] = 'Z' label_pauli = "".join(label_pauli) paulis.append({"coeff": temp, "label": label_pauli}) paulis_dict = {"paulis": paulis} for i in paulis_dict["paulis"]: print(i) pauli_matrix = Operator.load_from_dict(paulis_dict) return pauli_matrix def dameInversoBinario(target, precision, num_vars): contador = {} for i in range(precision): contador[i] = 0 while target > 0: for i in range(precision-1, -1, -1): while target >= 2**i: target -= 2**i contador[i] += 1 print(contador) #Invertir bits long_buscada = num_vars * precision array = np.zeros(long_buscada) for i in range(precision): for j in range(contador[i]): array[j*num_vars + (i)] = 1 invert_array = ['0' if x == 1 else '1' for x in array] arrays = np.array_split(np.array(invert_array), 3) acu = 0 for i in arrays: en_binario = "".join(list(np.flip(i))) acu += int(en_binario, 2) return acu def optimize_f(precision, coefs_param, beta): coefs = coefs_param.copy() coefs.append(0) coefs_restr = (1, 1, 1) lista_vars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] mdl = Model() variables = [] for num_var in range(len(coefs)): tmp = {i: mdl.binary_var(name=(lista_vars[num_var] + '_{0}').format(i)) for i in range(precision)} variables.append(tmp) # x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(precision)} # y = {i: mdl.binary_var(name='y_{0}'.format(i)) for i in range(precision)} # z = {i: mdl.binary_var(name='z_{0}'.format(i)) for i in range(precision)} #print(variables) # Object function # my_func = mdl.sum(coefs[0]*(2**i)*x[i]+coefs[1]*(2**i)*y[i]+(2**i)*coefs[2]*z[i] for i in range(precision)) # my_func = mdl.sum(coefs[j]*(2**i)*vars[j][i] for j in range(len(coefs)) for i in range(precision)) my_func = mdl.sum(coefs[j] * (2 ** i) * variables[j][i] for j in range(len(coefs)) for i in range(precision)) # (x[i] for i in range(precision)), (y[i] for i in range(precision)), (z[i] for i in range(precision) # tmp = {0:{'var':x,'coef':coefs_restr[0]}, # 1:{'var':y,'coef':coefs_restr[1]}, # 2:{'var':z,'coef':coefs_restr[2]}} mdl.maximize(my_func) inverted_beta = dameInversoBinario(beta, precision, len(coefs)) # mdl.add_constraint(mdl.sum( tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == beta) # mdl.add_constraint(mdl.sum( x[0] + x[1]*(2) + x[2]*(4) + y[0] + y[1]*(2) + y[2]*(4) + z[0] + z[1]*(2) + z[2]*(4) ) == inverted_beta) # mdl.add_constraint(mdl.sum( variables[0][0] + variables[0][1]*(2) + variables[0][2]*(4) + variables[1][0] + variables[1][1] # *(2) + variables[1][2]*(4) + variables[2][0] + variables[2][1]*(2) + variables[2][2]*(4) ) == inverted_beta) mdl.add_constraint( mdl.sum(variables[v][i] * 2 ** i for v in range(len(coefs)) for i in range(precision)) == inverted_beta) # mdl.add_constraint(mdl.sum( -x[0] - x[1]*(2) - x[2]*(4) - y[0] - y[1]*(2) - y[2]*(4) - z[0] - z[1]*(2) - z[2]*(4) ) == 6) # mdl.add_constraint(mdl.sum( -1*tmp[v]['var'][i]*(2**i)*tmp[v]['coef'] for v in range(len(coefs)) for i in range(precision)) == -beta) qubitOp_docplex, offset_docplex = docplex.get_qubitops(mdl) #print(qubitOp_docplex) # algo_input = EnergyInput(qubitOp_docplex) # print(algo_input.) # ee = VQE(qubitOp_docplex) # ee.run() ee = ExactEigensolver(qubitOp_docplex, k=1) result_ee = ee.run() x_ee = max_cut.sample_most_likely(result_ee['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x_ee)) solucion_ee = max_cut.get_graph_solution(x_ee) return (solucion_ee, None) """ algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) """ # x = max_cut.sample_most_likely(result['eigvecs'][0]) # print('energy:', result['energy']) # print('max-cut objective:', result['energy'] + offset_docplex) # print('solution:', max_cut.get_graph_solution(x)) # print('solution objective:', max_cut.max_cut_value(x, w)) seed = 10598 # change optimizer(spsa), change ry (riyc) spsa = SPSA(max_trials=300) ry = RY(qubitOp_docplex.num_qubits, depth=6, entanglement='linear') vqe = VQE(qubitOp_docplex, ry, spsa, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed=seed, seed_transpiler=seed) result = vqe.run(quantum_instance) x = max_cut.sample_most_likely(result['eigvecs'][0]) print('solution:', max_cut.get_graph_solution(x)) return (solucion_ee, max_cut.get_graph_solution(x)) def wrapper_optimiza_f(precision, coefs_param, beta): r = optimize_f(precision, coefs_param, beta) r_ee = r[0] vars = np.array_split(r_ee, 3) tam = len(vars) answer = {} for i in range(tam): curr = vars[i] curr_i = np.flip(curr) curr_i = [str(int(k)) for k in curr_i] en_binario = "".join(list(curr_i)) curr_var = int(en_binario, 2) if i != tam - 1: answer[i]=curr_var return answer if __name__ == '__main__': precision = 6 coefs_param = [2, -3] beta = 7 a = wrapper_optimiza_f(precision, coefs_param, beta) print(a) exit() dameInversoBinario(6, 3, 3) exit() qbits_encode = 2 # Max number of qubits for coding a number input_vars = [2, -3] # 2*x + 4*y +6*z # basic restriction options = {} options['restriction'] = 'default' # a*x+b*y+c*z <= beta (que puede ser 1) options['input_rest'] = [1, 1] options['beta'] = 2 matrix = wrapper(qbits_encode, input_vars, options) print(matrix) pauli_matrix = getPauliMatrix(matrix) print(pauli_matrix) from docplex.mp.model import Model mdl = Model() mdl.add_constraint
https://github.com/MAI-cyber/QIT
MAI-cyber
#! pip install numpy #! pip install qiskit #! pip install matplotlib from qiskit import QuantumCircuit, Aer ,BasicAer, execute from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere from qiskit.quantum_info import Statevector import matplotlib.pyplot as plt import numpy as np GHZ_circuit = QuantumCircuit(3) GHZ_circuit.h(0) GHZ_circuit.cx(0, 1) GHZ_circuit.cx(1, 2) GHZ_circuit.draw('mpl') initial = ["000", "001", "010", "011", "100", "101", "110", "111"] initial_states = [] for label in initial: initial_states.append(Statevector.from_label(label)) #print(initial_states) evolved_states = [] for state in initial_states: evolved_states.append(state.evolve(GHZ_circuit)) #print(evolved_states) matrix = np.zeros((2**3, 2**3), dtype = "complex_") for i in range(2**3): for j in range(2**3): matrix[i][j] = evolved_states[i][j] matrix = matrix.T print("Matrix form of the GHZ entangler = ") print(matrix)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
import qiskit from qiskit.dagcircuit import DAGCircuit from qiskit.providers import BaseBackend from qiskit.transpiler.basepasses import TransformationPass, BasePass from qiskit.converters import circuit_to_dag, dag_to_circuit from pytket._transform import Transform from pytket._routing import route, Architecture from pytket.qiskit import qiskit_to_tk, tk_to_qiskit class TketPass(TransformationPass): """The :math:`\\mathrm{t|ket}\\rangle` compiler to be plugged in to the Qiskit compilation sequence""" filecount = 0 def __init__(self,backend:BaseBackend, DROP_CONDS:bool=False,BOX_UNKNOWN:bool=True,name:str="T|KET>") : BasePass.__init__(self) self.DROP_CONDS=DROP_CONDS self.BOX_UNKNOWN=BOX_UNKNOWN self.name = name my_backend = None if isinstance(backend, BaseBackend): my_backend = backend else: raise RuntimeError("Requires BaseBackend instance") self.coupling_map = my_backend.configuration().to_dict().get('coupling_map', None) def process_circ(self, circ): num_qubits = circ.n_qubits if num_qubits == 1 or self.coupling_map == "all-to-all": coupling_map = None else: coupling_map = self.coupling_map # pre-routing optimise Transform.OptimisePhaseGadgets().apply(circ) circlay = list(range(num_qubits)) if coupling_map: directed_arc = Architecture(coupling_map) # route_ibm fnction that takes directed Arc, returns dag with cnots etc. circ, circlay = route(circ,directed_arc) circ.apply_boundary_map(circlay[0]) # post route optimise Transform.OptimisePostRouting().apply(circ) circ.remove_blank_wires() return circ, circlay def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ qc = dag_to_circuit(dag) circ = qiskit_to_tk(qc) circ, circlay = self.process_circ(circ) qc = tk_to_qiskit(circ) newdag = circuit_to_dag(qc) newdag.name = dag.name finlay = dict() for i, qi in enumerate(circlay): finlay[('q', i)] = ('q', qi) newdag.final_layout = finlay return newdag
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 6 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] dsID='3c' print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 6 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[0.25,0.25,0.25,0.81] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) import matplotlib.pyplot as plt for lr in range(4): \ data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
# initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualization import plot_histogram nQubits = 2 # number of physical qubits used to represent s s = 3 # the hidden integer # make sure that a can be represented with nqubits s = s % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # bits for recording the measurement on qr cr = ClassicalRegister(nQubits) bvCircuit = QuantumCircuit(qr, cr) barriers = True # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (s & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier if barriers: bvCircuit.barrier() # Measurement bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # 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 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 job = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job, interval = 2) # Get the results from the computation results = job.result() answer = results.get_counts() plot_histogram(answer) import qiskit qiskit.__qiskit_version__
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # ┌───┐ ░ ┌─┐ # q_0: ┤ H ├──■──────────────────░─┤M├──────────── # ├───┤┌─┴─┐ ░ └╥┘┌─┐ # q_1: ┤ H ├┤ X ├──■─────────────░──╫─┤M├───────── # ├───┤└───┘ │ ┌───┐ ░ ║ └╥┘┌─┐ # q_2: ┤ H ├───────┼──┤ X ├──■───░──╫──╫─┤M├────── # ├───┤ │ └─┬─┘┌─┴─┐ ░ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├───────┼────┼──┤ X ├─░──╫──╫──╫─┤M├─── # ├───┤ ┌─┴─┐ │ └───┘ ░ ║ ║ ║ └╥┘┌─┐ # q_4: ┤ H ├─────┤ X ├──■────────░──╫──╫──╫──╫─┤M├ # └───┘ └───┘ ░ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # ┌───┐ # q_0: ┤ H ├──■──────────────────── # └───┘ │ ┌───┐┌─┐ # q_1: ───────┼────────────┤ X ├┤M├ # ┌───┐ │ ┌───┐┌───┐└─┬─┘└╥┘ # q_2: ┤ X ├──┼──┤ X ├┤ X ├──┼───╫─ # └───┘ │ └───┘└───┘ │ ║ # q_3: ───────┼──────────────┼───╫─ # ┌─┴─┐┌───┐ │ ║ # q_4: ─────┤ X ├┤ X ├───────■───╫─ # └───┘└───┘ ║ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # ┌───┐ # q1_0: ┤ H ├──■────■───────────────── # ├───┤ │ ┌─┴─┐ # q1_1: ┤ H ├──┼──┤ X ├──■──────────── # ├───┤ │ └───┘ │ ┌───┐ # q1_2: ┤ H ├──┼─────────┼──┤ X ├──■── # ├───┤┌─┴─┐ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├┤ X ├───────┼────┼──┤ X ├ # ├───┤└─┬─┘ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├──■───────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├───────────────── # ├───┤┌─┴─┐└╥┘┌─┐ # q_1: ┤ H ├┤ X ├─╫─┤M├────────────── # ├───┤└───┘ ║ └╥┘ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 1 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # ┌───┐ ┌─┐┌─┐ # q_0: ┤ H ├──■──┤M├┤M├────────────── # ├───┤┌─┴─┐└╥┘└╥┘ # q_1: ┤ H ├┤ X ├─╫──╫─────────────── # ├───┤└───┘ ║ ║ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 0 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────────────────── # ├───┤└╥┘ ┌───┐ # q_1: ┤ H ├─╫───────┤ H ├────────────── # ├───┤ ║ ┌─┐ └─╥─┘ # q_2: ┤ H ├─╫─┤M├─────╫──────────────── # ├───┤ ║ └╥┘ ║ ┌───┐ # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├─── # └───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌────╨────┐┌────╨────┐ # c: 4/══════╩══╩═╡ c_0=0x1 ╞╡ c_2=0x0 ╞ # 0 2 └─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # ┌───┐┌─┐ » # q_0: ┤ H ├┤M├──────────────────────────────■─────────────────────■─────» # ├───┤└╥┘ ┌───┐ ┌─┴─┐ │ » # q_1: ┤ H ├─╫───────┤ H ├─────────────────┤ X ├───────────────────┼─────» # ├───┤ ║ ┌─┐ └─╥─┘ └─╥─┘ ┌─┴─┐ » # q_2: ┤ H ├─╫─┤M├─────╫─────────────────────╫──────────■────────┤ H ├───» # ├───┤ ║ └╥┘ ║ ┌───┐ ║ ┌─┴─┐ └─╥─┘ » # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├────────╫────────┤ X ├────────╫─────» # └───┘ ║ ║ ║ └─╥─┘ ║ └─╥─┘ ║ » # ║ ║ ┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐» # c: 4/══════╩══╩═╡ c_1=0x1 ╞╡ c_3=0x1 ╞╡ c_0=0x0 ╞╡ c_2=0x0 ╞╡ c_1=0x1 ╞» # 0 2 └─────────┘└─────────┘└─────────┘└─────────┘└─────────┘» # « # «q_0: ─────────── # « # «q_1: ─────■───── # « │ # «q_2: ─────┼───── # « ┌─┴─┐ # «q_3: ───┤ H ├─── # « └─╥─┘ # « ┌────╨────┐ # «c: 4/╡ c_3=0x1 ╞ # « └─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├────────────────────────────────────── # ├───┤└╥┘ ┌───┐ ┌─┐ # q_1: ┤ H ├─╫────┤ H ├─────────────────────┤M├────── # ├───┤ ║ └─╥─┘ ┌───┐ └╥┘┌─┐ # q_2: ┤ H ├─╫──────╫──────┤ H ├─────────────╫─┤M├─── # ├───┤ ║ ║ └─╥─┘ ┌───┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──────╫────────╫──────┤ H ├────╫──╫─┤M├ # └───┘ ║ ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌────╨────┐┌──╨──┐┌────╨────┐ ║ ║ ║ # c: 4/══════╩═╡ c_0=0x1 ╞╡ 0x2 ╞╡ c_3=0x1 ╞═╩══╩══╩═ # 0 └─────────┘└─────┘└─────────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # ┌───┐┌─┐┌─┐┌─┐┌─┐ # q_0: ┤ H ├┤M├┤M├┤M├┤M├ # ├───┤└╥┘└╥┘└╥┘└╥┘ # q_1: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_2: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_3: ┤ H ├─╫──╫──╫──╫─ # └───┘ ║ ║ ║ ║ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # ┌───┐ ░ ░ ░ ░ ░ # q_0: ┤ H ├─░───■───░──░──░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ ░ ░ # q_1: ──────░─┤ X ├─░──░──░───────░────── # ░ └───┘ ░ ░ ░ ┌───┐ ░ # q_2: ──────░───────░──░──░─┤ H ├─░───■── # ░ ░ ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░──░──░───────░─┤ X ├ # ░ ░ ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # ┌───┐ ░ ░ # q_0: ┤ H ├──■───░──░─────────── # └───┘┌─┴─┐ ░ ░ # q_1: ─────┤ X ├─░──░─────────── # └───┘ ░ ░ ┌───┐ # q_2: ───────────░──░─┤ H ├──■── # ░ ░ └───┘┌─┴─┐ # q_3: ───────────░──░──────┤ X ├ # ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # ┌───┐ # q_0: ┤ H ├──■─────────────────── # └───┘┌─┴─┐┌─────────┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■───────────────────────────┤ X ├─── # └───┘ │ ┌─────────┐ ┌─┐ └─╥─┘ # q_1: ───────■──┤ Rz(0.1) ├──────■─┤M├─────╫───── # ┌─┴─┐└──┬───┬──┘ │ └╥┘ ║ # q_2: ─────┤ X ├───┤ H ├─────■───┼──╫──────╫───── # └───┘ └───┘ ┌─┴─┐ │ ║ ║ # q_3: ─────────────────────┤ X ├─■──╫──────╫───── # └───┘ ║ ┌────╨────┐ # c: 1/══════════════════════════════╩═╡ c_0 = T ╞ # 0 └─────────┘ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■─────┤ T ├───────── # └───┘┌─┴─┐┌──┴───┴──┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # ┌───┐ ┌────────┐ # q_0: ┤ H ├───────────────────┤0 ├ # ├───┤ ┌───┐ │ │ # q_1: ┤ H ├───┤ X ├─────────■─┤ ├ # ├───┤ └───┘ │ │ │ # q_2: ┤ H ├─────■───────────X─┤ Iswap ├ # ├───┤ │ ┌───┐ │ │ │ # q_3: ┤ H ├─────┼─────┤ Z ├─X─┤ ├ # ├───┤┌────┴────┐├───┤ │ │ # q_4: ┤ H ├┤ Ry(0.1) ├┤ Z ├───┤1 ├ # ├───┤└──┬───┬──┘└───┘ └───╥────┘ # q_5: ┤ H ├───┤ Z ├───────────────╫───── # └───┘ └───┘ ┌──╨──┐ # c: 2/═════════════════════════╡ 0x2 ╞══ # └─────┘ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # │ # q1_1: ──┼─────────■── # │ ┌───┐ │ # q1_2: ──┼──┤ X ├──┼── # │ └─┬─┘┌─┴─┐ # q2_0: ──┼────■──┤ X ├ # ┌─┴─┐ └───┘ # q2_1: ┤ X ├────────── # └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # │ # q1_1: ──┼────■───────────────── # │ │ # q1_2: ──┼────┼────■──────────── # │ │ │ # q1_3: ──┼────┼────┼────■─────── # │ │ │ │ # q1_4: ──┼────┼────┼────┼────■── # │ │ │ │ ┌─┴─┐ # q2_0: ──┼────┼────┼────┼──┤ X ├ # │ │ │ ┌─┴─┐└───┘ # q2_1: ──┼────┼────┼──┤ X ├───── # │ │ ┌─┴─┐└───┘ # q2_2: ──┼────┼──┤ X ├────────── # │ ┌─┴─┐└───┘ # q2_3: ──┼──┤ X ├─────────────── # ┌─┴─┐└───┘ # q2_4: ┤ X ├──────────────────── # └───┘ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├─┤ H ├──────── # ├───┤ └─╥─┘ # q_1: ┤ H ├───╫──────■─── # ├───┤ ║ ┌─┴─┐ # q_2: ┤ H ├───╫────┤ X ├─ # ├───┤ ║ └─╥─┘ # q_3: ┤ H ├───╫──────╫─── # └───┘┌──╨──┐┌──╨──┐ # c: 8/═════╡ 0x0 ╞╡ 0x4 ╞ # └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # ┌───┐┌─┐ ┌───┐ # q0_0: ┤ H ├┤M├─┤ H ├────────────────── # ├───┤└╥┘ └─╥─┘ # q0_1: ┤ H ├─╫────╫──────■───────────── # ├───┤ ║ ║ ┌─┴─┐ ┌─┐ # q0_2: ┤ H ├─╫────╫────┤ X ├─┤M├─────── # ├───┤ ║ ║ └─╥─┘ └╥┘ ┌───┐ # q0_3: ┤ H ├─╫────╫──────╫────╫──┤ X ├─ # └───┘ ║ ║ ║ ║ └─╥─┘ # ║ ┌──╨──┐┌──╨──┐ ║ ┌──╨──┐ # c0: 4/══════╩═╡ 0x0 ╞╡ 0x1 ╞═╩═╡ 0x2 ╞ # 0 └─────┘└─────┘ 2 └─────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────■──────── # ├───┤└╥┘┌─┐ │ # q_1: ┤ H ├─╫─┤M├────────┼──────── # ├───┤ ║ └╥┘┌─┐ │ # q_2: ┤ H ├─╫──╫─┤M├─────┼──────── # ├───┤ ║ ║ └╥┘ ┌─┴─┐ ┌─┐ # q_3: ┤ H ├─╫──╫──╫────┤ X ├───┤M├ # └───┘ ║ ║ ║ └─╥─┘ └╥┘ # ║ ║ ║ ┌────╨────┐ ║ # c: 4/══════╩══╩══╩═╡ c_0=0x1 ╞═╩═ # 0 1 2 └─────────┘ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├───┤ H ├─────────────────┤ X ├─── # ├───┤ └─╥─┘ └─┬─┘ # q_1: ┤ H ├─────╫─────────────────────■───── # ├───┤ ║ ║ # q_2: ┤ H ├─────╫──────────■──────────╫───── # ├───┤ ║ │ ║ # q_3: ┤ H ├─────╫──────────■──────────╫───── # └───┘┌────╨────┐┌────╨────┐┌────╨────┐ # c: 6/═════╡ c_1=0x1 ╞╡ c_0=0x1 ╞╡ c_4=0x0 ╞ # └─────────┘└─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # ┌───┐ ┌───┐ # q0_0: ┤ H ├───┤ H ├─────────────────────── # ├───┤ └─╥─┘ # q0_1: ┤ H ├─────╫─────────■─────────────── # ├───┤ ║ ┌─┴─┐ # q0_2: ┤ H ├─────╫───────┤ X ├───────────── # ├───┤ ║ └─╥─┘ ┌───┐ # q0_3: ┤ H ├─────╫─────────╫──────┤ X ├──── # └───┘ ║ ║ └─╥─┘ # ┌────╨─────┐┌──╨──┐┌────╨─────┐ # c0: 4/═════╡ c0_0=0x1 ╞╡ 0x1 ╞╡ c0_2=0x1 ╞ # └──────────┘└─────┘└──────────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├────────■──────────■────■──────────■──┤M├─── # ├───┤ │ │ │ ┌─┐ │ └╥┘ # q_1: ┤ H ├──■─────┼─────■────┼────┼──┤M├─────┼───╫──── # ├───┤┌─┴─┐ │ ┌─┴─┐ │ │ └╥┘┌─┐ │ ║ # q_2: ┤ H ├┤ X ├───┼───┤ X ├──┼────┼───╫─┤M├──┼───╫──── # ├───┤└───┘ ┌─┴─┐ └───┘┌─┴─┐┌─┴─┐ ║ └╥┘┌─┴─┐ ║ ┌─┐ # q_3: ┤ H ├──────┤ X ├──────┤ X ├┤ X ├─╫──╫─┤ X ├─╫─┤M├ # └───┘ └─╥─┘ └───┘└───┘ ║ ║ └───┘ ║ └╥┘ # ┌──╨──┐ ║ ║ ║ ║ # c: 4/══════════╡ 0x2 ╞════════════════╩══╩═══════╩══╩═ # └─────┘ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # q_4: ──────╫──╫──╫──╫─ # ║ ║ ║ ║ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Chi quantum channel representation class.""" import copy import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import QiskitError from qiskit.quantum_info.states import DensityMatrix from qiskit.quantum_info.operators.channel import Chi from .channel_test_case import ChannelTestCase class TestChi(ChannelTestCase): """Tests for Chi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Chi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat16 = np.eye(16) / 4 chan = Chi(mat16) assert_allclose(chan.data, mat16) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan.num_qubits, 2) # Wrong input or output dims should raise exception self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4) # Non multi-qubit dimensions should raise exception self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Chi(circuit) target = Chi(target) self.assertEqual(op, target) def test_circuit_init_except(self): """Test initialization from circuit with measure raises exception.""" circuit = self.simple_circuit_with_measure() self.assertRaises(QiskitError, Chi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4, real=True) self.assertEqual(Chi(mat), Chi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(4) with self.subTest("Deep copy"): orig = Chi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Chi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_is_cptp(self): """Test is_cptp method.""" self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp()) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16))) self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan1.compose(chan2) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # 50% depolarizing channel chan1 = Chi(self.depol_chi(0.5)) chan = chan1.compose(chan1) target = rho.evolve(Chi(self.depol_chi(0.75))) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan1.compose(chan2) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) chan = chan1 & chan2 output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_dot(self): """Test dot method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan2.dot(chan1)) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.dot(chan1) output = rho.evolve(chan) self.assertEqual(output, target) chan = chan2 @ chan1 output = rho.evolve(chan) self.assertEqual(output, target) def test_compose_front(self): """Test front compose method.""" # Random input test state rho = DensityMatrix(self.rand_rho(2)) # UnitaryChannel evolution chan1 = Chi(self.chiX) chan2 = Chi(self.chiY) chan = chan2.compose(chan1, front=True) target = rho.evolve(Chi(self.chiZ)) output = rho.evolve(chan) self.assertEqual(output, target) # Compose random chi1 = self.rand_matrix(4, 4, real=True) chi2 = self.rand_matrix(4, 4, real=True) chan1 = Chi(chi1, input_dims=2, output_dims=2) chan2 = Chi(chi2, input_dims=2, output_dims=2) target = rho.evolve(chan1).evolve(chan2) chan = chan2.compose(chan1, front=True) output = rho.evolve(chan) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(output, target) def test_expand(self): """Test expand method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan1.expand(chan2) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.expand(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_tensor(self): """Test tensor method.""" # Pauli channels paulis = [self.chiI, self.chiX, self.chiY, self.chiZ] targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats for i, chi1 in enumerate(paulis): for j, chi2 in enumerate(paulis): chan1 = Chi(chi1) chan2 = Chi(chi2) chan = chan2.tensor(chan1) # Target for diagonal Pauli channel targ = Chi(np.diag(targs[i + 4 * j])) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Test overload chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(chan, targ) # Completely depolarizing rho = DensityMatrix(np.diag([1, 0, 0, 0])) chan_dep = Chi(self.depol_chi(1)) chan = chan_dep.tensor(chan_dep) target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) # Test operator overload chan = chan_dep ^ chan_dep output = rho.evolve(chan) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(output, target) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Chi(self.depol_chi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Chi(self.depol_chi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.chiI mat2 = 0.5 * self.depol_chi(1) chan1 = Chi(mat1) chan2 = Chi(mat2) targ = Chi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Chi(mat1 - mat2) self.assertEqual(chan1 - chan2, targ) def test_add_qargs(self): """Test add method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op + op0([0]) target = op + eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op + op0([1]) target = op + eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op + op0([2]) target = op + op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op + op01([0, 1]) target = op + eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op + op01([1, 0]) target = op + eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op + op01([0, 2]) target = op + op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op + op01([2, 0]) target = op + op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_sub_qargs(self): """Test subtract method with qargs.""" mat = self.rand_matrix(8**2, 8**2) mat0 = self.rand_matrix(4, 4) mat1 = self.rand_matrix(4, 4) op = Chi(mat) op0 = Chi(mat0) op1 = Chi(mat1) op01 = op1.tensor(op0) eye = Chi(self.chiI) with self.subTest(msg="qargs=[0]"): value = op - op0([0]) target = op - eye.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1]"): value = op - op0([1]) target = op - eye.tensor(op0).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[2]"): value = op - op0([2]) target = op - op0.tensor(eye).tensor(eye) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 1]"): value = op - op01([0, 1]) target = op - eye.tensor(op1).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[1, 0]"): value = op - op01([1, 0]) target = op - eye.tensor(op0).tensor(op1) self.assertEqual(value, target) with self.subTest(msg="qargs=[0, 2]"): value = op - op01([0, 2]) target = op - op1.tensor(eye).tensor(op0) self.assertEqual(value, target) with self.subTest(msg="qargs=[2, 0]"): value = op - op01([2, 0]) target = op - op0.tensor(eye).tensor(op1) self.assertEqual(value, target) def test_add_except(self): """Test add method raises exceptions.""" chan1 = Chi(self.chiI) chan2 = Chi(np.eye(16)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Chi(self.chiI) val = 0.5 targ = Chi(val * self.chiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Chi(self.chiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Chi(self.chiI) self.assertRaises(QiskitError, chan._multiply, "s") self.assertRaises(QiskitError, chan.__rmul__, "s") self.assertRaises(QiskitError, chan._multiply, chan) self.assertRaises(QiskitError, chan.__rmul__, chan) def test_negate(self): """Test negate method""" chan = Chi(self.chiI) targ = Chi(-self.chiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np # Import Qiskit from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator # Construct quantum circuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0,1], [0,1]) # Select the AerSimulator from the Aer provider simulator = AerSimulator(method='matrix_product_state') # Run and get counts, using the matrix_product_state method tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() counts = result.get_counts(0) counts circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) # Define a snapshot that shows the current state vector circ.save_statevector(label='my_sv') circ.save_matrix_product_state(label='my_mps') circ.measure([0,1], [0,1]) # Execute and get saved data tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() data = result.data(0) #print the result data data num_qubits = 50 circ = QuantumCircuit(num_qubits, num_qubits) # Create EPR state circ.h(0) for i in range (0, num_qubits-1): circ.cx(i, i+1) # Measure circ.measure(range(num_qubits), range(num_qubits)) tcirc = transpile(circ, simulator) result = simulator.run(tcirc).result() print("Time taken: {} sec".format(result.time_taken)) result.get_counts() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
from mip import Model, INTEGER, xsum, OptimizationStatus, minimize import numpy as np from itertools import permutations A = np.array([[0,1,2,3,4,1], [2,1,4,1,0,2], [1,5,2,3,1,1], [0,0,1,2,2,0]]) var_type = INTEGER max_gap = 0.05 max_seconds=10 c = np.array([-1,2,-2,2,1,1]) m, n = A.shape def createModelAndCheck(A, b, var_type, max_gap, max_seconds): m, n = A.shape model = Model() x = [model.add_var(var_type=var_type) for j in range(n)] for i in range(m): A_i = A[i] b_i = b[i] model += xsum(A_i[j]*x[j] for j in range(n)) == b_i model.objective = minimize(xsum(c[j]*x[j] for j in range(n))) model.max_gap = max_gap status = model.optimize(max_seconds=max_seconds) """ if status != OptimizationStatus.INFEASIBLE: print("Found b: ", b) if status == OptimizationStatus.OPTIMAL: print('optimal solution cost {} found'.format(model.objective_value)) elif status == OptimizationStatus.FEASIBLE: print('sol.cost {} found, best possible: {}'.format(model.objective_value, model.objective_bound)) elif status == OptimizationStatus.NO_SOLUTION_FOUND: print('no feasible solution found, lower bound is: {}'.format(model.objective_bound)) """ if status == OptimizationStatus.OPTIMAL:# or status == OptimizationStatus.FEASIBLE: print('solution:') for v in model.vars: if abs(v.x) > 1e-6: # only printing non-zeros print('{} : {}'.format(v.name, v.x)) return model else: return None brute_force_b = list(permutations([0,1,2,3,4,5,6,7,8],m)) goodB = [] for b in brute_force_b: model = createModelAndCheck(A, np.array(b), var_type, max_gap, max_seconds) if model is not None: count = 0 good = 0 for v in model.vars: if abs(v.x) > 1e-6: count += 1 if abs(v.x) > 1: good += 1 if count > 2 and good > 1: goodB +=[b] print(goodB) for b in goodB : createModelAndCheck(A, np.array(b), var_type, max_gap, max_seconds)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb # tem algum problema com a funcao produto tensorial do sympy (implementar eu mesmo ...) k000 = Matrix([1,0,0,0,0,0,0,0]); k001 = Matrix([0,1,0,0,0,0,0,0]) k010 = Matrix([0,0,1,0,0,0,0,0]); k011 = Matrix([0,0,0,1,0,0,0,0]) k100 = Matrix([0,0,0,0,1,0,0,0]); k101 = Matrix([0,0,0,0,0,1,0,0]) k110 = Matrix([0,0,0,0,0,0,1,0]); k111 = Matrix([0,0,0,0,0,0,0,1]) #k000,k001,k010,k011,k100,k101,k110,k111, k001*k001.T p = symbols('p') #p = 0 Psi0 = sqrt((4-3*p)/4)*k000 + sqrt(p/4)*(k101+k010+k111) Psi1 = sqrt((4-3*p)/4)*k100 + sqrt(p/4)*(k001-k110-k011) #Psi0.T, Psi1.T r00,r01,r10,r11 = symbols('r_{00} r_{01} r_{10} r_{11}') rhoA = Matrix([[r00,r01],[r10,r11]]); rhoA, rhoA[0,0] #rhoA = Matrix([[2/3,1/3],[1/3,1/3]]); #rhoA, rhoA[0,0] def rhoABt_s(rhoA,p): Psi0 = sqrt((4-3*p)/4)*k000 + sqrt(p/4)*(k101+k010+k111) Psi1 = sqrt((4-3*p)/4)*k100 + sqrt(p/4)*(k001-k110-k011) return rhoA[0,0]*Psi0*Psi0.T + rhoA[0,1]*Psi0*Psi1.T + rhoA[1,0]*Psi1*Psi0.T + rhoA[1,1]*Psi1*Psi1.T rhoABt_ = rhoABt_s(rhoA,p); rhoABt_ # não foi possivel diagonalizar com sympy def ptraceB(da, db, rho): rhoA = zeros(da,da) for j in range(0, da): for k in range(0, da): for l in range(0, db): rhoA[j,k] += rho[j*db+l,k*db+l] return rhoA rhoAt = ptraceB(2, 4, rhoABt_); simplify(rhoAt) # ok! rhoA = Matrix([[2/3,1/3],[1/3,1/3]]) p = np.arange(0,1.1,0.1); N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoABt_ = rhoABt_s(rhoA,p[j]) rhoA_ = ptraceB(2, 4, rhoABt_) Cl1[j] = coh_l1_s(rhoA_) Pjb[j] = predict_jb_s(rhoA_) # calculo feito a partir de rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() evv = rhoABt.eigenvects(); evv def tp_vv_s(psi, csi): # tensor product, of vectors, symbolic M = psi.shape[0]; N = csi.shape[0] eta = zeros(M*N,1) for j in range(0,M): for k in range(0,N): eta[j*N+k] = psi[j]*csi[k] return eta def cb(d,j): # estados da base computacional v = zeros(d,1) v[j] = 1 return v cb(2,0) def PhiABCt_s(rhoA,p): rhoABt = rhoABt_s(rhoA,p) eig = rhoABt.eigenvects() d = rhoABt.shape[0]; Phi = zeros(d*d,1) ne = 0; j = 0; l = -1 while ne < d: mult = eig[j][1]; ne += mult for k in range(0,mult): l += 1 Phi += sqrt(abs(eig[j][0]))*tp_vv_s(eig[j][2][k],cb(d,l)) j += 1 for j in range(0,d*d): if im(Phi[j]) < 10**-5: Phi[j] = re(Phi[j]) return Phi def coh_l1_s(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += abs(rho[j,k]) return 2*C def predict_jb_s(rho): return abs(rho[0,0]-rho[1,1]) def proj_s(psi): # simbolic projector d = psi.shape[0] proj = zeros(d,d) for j in range(0,d): for k in range(0,d): proj[j,k] = psi[j]*conjugate(psi[k]) return proj rhoA = Matrix([[2/3,1/3],[1/3,1/3]]) p = np.arange(0,1.1,0.1); N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): Phi = PhiABCt_s(rhoA,p[j]); PPhi = proj_s(Phi)#; print(PPhi) rhoA_ = ptraceB(2, 2**5, PPhi)#; print(rhoA_[0,1]) Cl1[j] = coh_l1_s(rhoA_) Pjb[j] = predict_jb_s(rhoA_) # calculo feito a partir de PhiABC import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() def rho_AB_til(rhoA,p): rhoAbc = np.zeros((2**3,2**3), dtype=complex)#; print(rhoAbc) ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]])#; print(ket0,ket1) ket00 = np.kron(ket0,ket0); ket01 = np.kron(ket0,ket1); ket10 = np.kron(ket1,ket0) ket11 = np.kron(ket1,ket1); #print(ket00,'',ket01,'',ket10,'',ket11) ket000 = np.kron(ket0,ket00); ket100 = np.kron(ket1,ket00) ket001 = np.kron(ket0,ket01); ket101 = np.kron(ket1,ket01) ket010 = np.kron(ket0,ket10); ket110 = np.kron(ket1,ket10) ket011 = np.kron(ket0,ket11); ket111 = np.kron(ket1,ket11) Psi0 = math.sqrt((4-3*p)/4)*ket000 + math.sqrt(p/4)*(ket101+ket010+ket111) Psi1 = math.sqrt((4-3*p)/4)*ket100 + math.sqrt(p/4)*(ket001-ket110-ket011) rhoAbc = rhoA[0,0]*Psi0@Psi0.T + rhoA[0,1]*Psi0@Psi1.T\ + rhoA[1,0]*Psi1@Psi0.T + rhoA[1,1]*Psi1@Psi1.T return rhoAbc def pTraceR_num(dl, dr, rhoLR): rhoL = np.zeros((dl, dl), dtype=complex) for j in range(0, dl): for k in range(j, dl): for l in range(0, dr): rhoL[j,k] += rhoLR[j*dr+l,k*dr+l] if j != k: rhoL[k,j] = np.conj(rhoL[j,k]) return rhoL rhoA = np.array([[2/3,1/3],[1/3,1/3]]); print(rhoA) # estado inicial p = 0. rhoAbc = rho_AB_til(rhoA,p)#; print(rhoAbc) rhoA_ = pTraceR_num(2, 4, rhoAbc); print(rhoA_) def coh_l1(rho): d = rho.shape[0]; #d = rho.dims()[0] C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) p = np.arange(0,1.1,0.1); #print(p) N = len(p)#; print(N) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoAbc = rho_AB_til(rhoA,p[j]) rhoA_ = pTraceR_num(2, 4, rhoAbc) Cl1[j] = coh_l1(rhoA_) Pjb[j] = predict_jb(rhoA_) # calculo feito a partir de rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() from numpy import linalg w, v = linalg.eig(rhoAbc) print(v[0][:]) print(np.shape(v[:][0])) ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]) ket00 = np.kron(ket0,ket0); ket01 = np.kron(ket0,ket1) ket10 = np.kron(ket1,ket0); ket11 = np.kron(ket1,ket1) ket000 = np.kron(ket0,ket00); ket100 = np.kron(ket1,ket00) ket001 = np.kron(ket0,ket01); ket101 = np.kron(ket1,ket01) ket010 = np.kron(ket0,ket10); ket110 = np.kron(ket1,ket10) ket011 = np.kron(ket0,ket11); ket111 = np.kron(ket1,ket11) p = np.arange(0,1.1,0.1) N = len(p) Cl1 = np.zeros(N); Pjb = np.zeros(N) for j in range(0,N): rhoAbc = rho_AB_til(rhoA,p[j]) w, v = linalg.eig(rhoAbc); w = np.abs(w) PhiAbcdef = math.sqrt(w[0])*np.kron(v.T[0],ket000) + math.sqrt(w[1])*np.kron(v.T[1],ket001)\ + math.sqrt(w[2])*np.kron(v.T[2],ket010) + math.sqrt(w[3])*np.kron(v.T[3],ket011)\ + math.sqrt(w[4])*np.kron(v.T[4],ket100) + math.sqrt(w[5])*np.kron(v.T[5],ket101)\ + math.sqrt(w[6])*np.kron(v.T[6],ket110) + math.sqrt(w[7])*np.kron(v.T[7],ket111) rhoAbcdef = np.outer(PhiAbcdef,np.conj(PhiAbcdef))#; print(np.shape(rhoAbcdef)) rhoA_ = pTraceR_num(2, 2**5, rhoAbcdef); print(rhoA_)#; print(np.shape(rhoA_)) Cl1[j] = coh_l1(rhoA_) Pjb[j] = predict_jb(rhoA_) # calculo feito a partir da purificacao rhoAB_til import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(p,Cl1,label=r'$C_{l_1}$') plt.plot(p,Pjb,label=r'$P_{jb}$') plt.xlabel(r'$p$') plt.legend() plt.show() rho_A = Matrix([[2/3,1/3],[1/3,1/3]]) rho_A.eigenvects() rho_A*Matrix([[0.85],[0.52]])/0.87, rho_A*Matrix([[-0.5257],[0.85]])/0.127 w, v = linalg.eig(rhoA) # os autovetores são as colunas de v print(w, v, v.T[0], v.T[1], np.shape(v.T[1])) # nao pode usar import qiskit from qiskit import * nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_quito') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit_experiments.library import StateTomography r00 = 2/3; r01 = 1.33/3; r10 = 1.33/3; r11 = 1/3 # initial state r = math.sqrt((r00-r11)**2 + abs(2*r01)**2) # raio de Bloch th = math.acos((r00-r11)/r) ph = math.acos(re(2*r01)/(r*sin(th))) # angulos de Bloch r0 = (1+r)/2.; r1 = (1-r)/2. # autovetores print(r, th, ph, r0, r1) pt = np.arange(0,1.01,0.01) # for the theoretical results Ct = (1-pt)*(2*1.33/3) Pt = (1-pt)*(1/3) p = np.arange(0,1.1,0.1) d = len(p) Csim = np.zeros(d); Psim = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 # depolarizing # sequencia: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 # = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[3],qr[2],qr[1],qr[0]]) job_sim = StateTomography(qc, measurement_qubits = [0]) data = job_sim.run(simulator, shots=nshots).block_for_results() rho_sim = data.analysis_results(0).value rho = rho_sim.to_operator().data Csim[j] = coh_l1(rho) Psim[j] = predict_jb(rho) p = np.arange(0,1.1,0.1); d = len(p) Cexp = np.zeros(d); Pexp = np.zeros(d) for j in range(0,d): pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2), math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pZ)*math.cos(th/2), -1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r1*pI)*math.sin(th/2), -math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pZ)*math.sin(th/2), 1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), math.sqrt(r0*pX)*math.cos(th/2), -math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2), 1j*math.sqrt(r0*pY)*math.cos(th/2), -math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), math.sqrt(r1*pX)*math.sin(th/2), math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2), 1j*math.sqrt(r1*pY)*math.sin(th/2)] qr = QuantumRegister(4); qc = QuantumCircuit(qr) qc.initialize(Phi_ABCD, [qr[3],qr[2],qr[1],qr[0]]) qcst = StateTomography(qc, measurement_qubits = [0]) data = qcst.run(device) print(data.experiment_id) rho = data.block_for_results().analysis_results(0).value rhoM = rho.to_operator().data Cexp[j] = coh_l1(rhoM) Pexp[j] = predict_jb(rhoM) print(Cexp,Pexp) import matplotlib matplotlib.rcParams.update({'font.size':12}) plt.figure(figsize = (6,4), dpi = 100) plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$') plt.plot(pt,Pt,label=r'$P_{jb}^{the}$') plt.plot(p,Csim,'*',label=r'$C_{l_1}^{sim}$') plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$') plt.plot(p,Cexp,'^',label=r'$C_{l_1}^{exp}$') plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$') plt.xlabel(r'$p$') plt.legend() plt.show() # para o chip quito, sem mitigacao de erro # para o chip manila sem mitigacao de erro
https://github.com/jcylim/QiskitProject
jcylim
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(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) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import os import qiskit class TranspilerBenchSuite: def _build_cx_circuit(self): cx_register = qiskit.QuantumRegister(2) cx_circuit = qiskit.QuantumCircuit(cx_register) cx_circuit.h(cx_register[0]) cx_circuit.h(cx_register[0]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) return cx_circuit def _build_single_gate_circuit(self): single_register = qiskit.QuantumRegister(1) single_gate_circuit = qiskit.QuantumCircuit(single_register) single_gate_circuit.h(single_register[0]) return single_gate_circuit def setup(self): self.single_gate_circuit = self._build_single_gate_circuit() self.cx_circuit = self._build_cx_circuit() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = qiskit.QuantumCircuit.from_qasm_file(large_qasm_path) self.coupling_map = [ [0, 1], [1, 0], [1, 2], [1, 4], [2, 1], [2, 3], [3, 2], [3, 5], [4, 1], [4, 7], [5, 3], [5, 8], [6, 7], [7, 4], [7, 6], [7, 10], [8, 5], [8, 9], [8, 11], [9, 8], [10, 7], [10, 12], [11, 8], [11, 14], [12, 10], [12, 13], [12, 15], [13, 12], [13, 14], [14, 11], [14, 13], [14, 16], [15, 12], [15, 18], [16, 14], [16, 19], [17, 18], [18, 15], [18, 17], [18, 21], [19, 16], [19, 20], [19, 22], [20, 19], [21, 18], [21, 23], [22, 19], [22, 25], [23, 21], [23, 24], [24, 23], [24, 25], [25, 22], [25, 24], [25, 26], [26, 25], ] self.basis = ["id", "rz", "sx", "x", "cx", "reset"] def time_single_gate_compile(self): circ = qiskit.compiler.transpile( self.single_gate_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_cx_compile(self): circ = qiskit.compiler.transpile( self.cx_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_compile_from_large_qasm(self): circ = qiskit.compiler.transpile( self.large_qasm, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ)
https://github.com/QuCO-CSAM/Solving-Combinatorial-Optimisation-Problems-Using-Quantum-Algorithms
QuCO-CSAM
import numpy as np from itertools import permutations import gzip from qiskit import* import time from qiskit.aqua.algorithms import VQE from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import SPSA # from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance from qiskit.aqua.components.optimizers import COBYLA from qiskit import IBMQ from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.optimization.applications.ising.tsp import TspData import qiskit.optimization.applications.ising.tsp as tsp from qiskit.circuit.library import TwoLocal from qiskit.circuit.library import RealAmplitudes # # # Load account from disk IBMQ.load_account() IBMQ.providers() def readInData(): """ Output G : N by N distance matrix from Matrices1a.txt file. """ G = [] p = [3,4,5,6,7,8,9,10,11] q = [i**(2) for i in p ] m = 0 v = open("Matrices.txt" , "r") w = v.read().split() for i in range (len(w)): w[i] = int(float(w[i])) for i in range (len(q)): G.append(np.reshape(w[m:m+q[i]] , (p[i] , p[i]))) m = m + q[i] return G distanceMatrix = readInData() #Array of different sized matrices def determineIfFeasible(result): """ Determines if eigenstate is feasible or infeasible. Output: arr = Infeasible if eiegenstate is infeasible or arr = binary array of feasible solution """ data = sorted(result['eigenstate'].items(), key=lambda item: item[1])[::-1] for i in range(len(data)): a = tsp.tsp_feasible(data[i][0]) arr = 'Infeasible' if a == True: b = str(data[i][0]) arr = [b , data[i][1]] break return arr def optimal(a,b,c,f,u): """ Read in data of initial optimal point that will be used in the quantum algorithm """ openfile = open("optimal.txt" , "r") readFile = openfile.read().split() t = [] for i in readFile: if i != ',': q = len(i) t.append(float(i[0:q-1])) v, r, o, d, z = np.array(t[0:a]), np.array(t[a:a+b]), np.array(t[a+b : a+b+c]), np.array(t[a+b+c:a+b+c+f]), np.array(t[a+b+c+f:a+b+c+f+u]) return [v,r,o,d,z] R = optimal(54,96,100,216,294) #Array of corresponding initial points def quantumApproximateOptimizationAlgorithm(numIter, numShots, distanceMatrix,pValue, deviceName, initialPoint): """ Implementation of the QAOA Output: classial TSP solution (total length of tour), time taken to execute algorithm """ # Map problem to isining hamiltonian x = TspData('tmp',len(distanceMatrix),np.zeros((3,3)),distanceMatrix) qubitOp = tsp.get_operator(x) seed = 10598 spsa = SPSA(maxiter = numIter) qaoa = QAOA(qubitOp, spsa, pValue, include_custom = False, initialPoint = initialPoint) my_provider = IBMQ.get_provider(ibm_hub) #Replace ibm_hub with appropriate qiskit hub name device = my_provider.get_backend(deviceName) # deviceName is the Device of IBM qunatum device in a string quantum_instance = QuantumInstance(device, seed_simulator=seed, seed_transpiler=seed,shots = numShots, skip_qobj_validation = False) #Convert quantum result into its classical form and determine if feasible or infeasible result = qaoa.run(quantum_instance) answer = determineIfFeasible(result) if answer == 'Infeasible': solution = -1 else: binarry = [int(p) for p in answer[0]] route = tsp.get_tsp_solution(binarry) solution = tsp.tsp_value(route,distanceMatrix) return solution, result['optimizer_time'] ## Example for 3 by 3 instance implemented using QAOA: numIter = 1 numShots = 8192 distanceMatrix = distanceMatrix[0] pValue = 3 deviceName = 'ibmq_manhattan' initialPoint = R[0] finalResult quantumApproximateOptimizationAlgorithm(numIter, numShots, distanceMatrix, pValue, deviceName, initialPoint)
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Unit tests for DDD slack windows and DDD insertion tools.""" import cirq import numpy as np import pyquil import pytest import qiskit from mitiq.ddd.insertion import ( _get_circuit_mask, get_slack_matrix_from_circuit_mask, insert_ddd_sequences, ) from mitiq.ddd.rules import xx, xyxy circuit_cirq_one = cirq.Circuit( cirq.SWAP(q, q + 1) for q in cirq.LineQubit.range(7) ) qreg_cirq = cirq.GridQubit.rect(10, 1) circuit_cirq_two = cirq.Circuit( cirq.ops.H.on_each(*qreg_cirq), cirq.ops.H.on(qreg_cirq[1]), ) circuit_cirq_three = cirq.Circuit( cirq.ops.H.on_each(*qreg_cirq), 5 * [cirq.ops.H.on(qreg_cirq[1])], ) circuit_cirq_three_validated = cirq.Circuit( cirq.ops.H.on_each(*qreg_cirq), 5 * [cirq.ops.H.on(qreg_cirq[1])], cirq.ops.I.on_each(qreg_cirq[0], *qreg_cirq[2:]), cirq.ops.X.on_each(qreg_cirq[0], *qreg_cirq[2:]), cirq.ops.Y.on_each(qreg_cirq[0], *qreg_cirq[2:]), cirq.ops.X.on_each(qreg_cirq[0], *qreg_cirq[2:]), cirq.ops.Y.on_each(qreg_cirq[0], *qreg_cirq[2:]), ) qreg = qiskit.QuantumRegister(4) creg = qiskit.ClassicalRegister(4) # Qiskit test without measurement circuit_qiskit_one = qiskit.QuantumCircuit(qreg) for q in qreg: circuit_qiskit_one.x(q) circuit_qiskit_one.x(3) circuit_qiskit_one.cx(0, 3) # Qiskit test with measurement circuit_qiskit_two = qiskit.QuantumCircuit(qreg, creg) for q in qreg: circuit_qiskit_two.x(q) circuit_qiskit_two.x(3) circuit_qiskit_two.measure(2, 3) circuit_qiskit_two.cx(0, 3) circuit_qiskit_validated = qiskit.QuantumCircuit(qreg) for i in range(4): circuit_qiskit_validated.x(i) circuit_qiskit_validated.x(3) if i != 3 and i != 0: circuit_qiskit_validated.id(i) circuit_qiskit_validated.x(i) circuit_qiskit_validated.id(i) circuit_qiskit_validated.x(i) circuit_qiskit_validated.id(i) elif i == 0: circuit_qiskit_validated.id(i) circuit_qiskit_validated.x(i) circuit_qiskit_validated.x(i) circuit_qiskit_validated.id(i) circuit_qiskit_validated.cx(0, 3) # Qiskit validate with measurement circuit_qiskit_two_validated = qiskit.QuantumCircuit(qreg, creg) for i in range(4): circuit_qiskit_two_validated.x(i) circuit_qiskit_two_validated.x(3) if i != 3 and i != 0: if i == 1: circuit_qiskit_two_validated.id(i) circuit_qiskit_two_validated.id(i) circuit_qiskit_two_validated.x(i) circuit_qiskit_two_validated.id(i) circuit_qiskit_two_validated.x(i) circuit_qiskit_two_validated.id(i) elif i == 0: circuit_qiskit_two_validated.id(i) circuit_qiskit_two_validated.x(i) circuit_qiskit_two_validated.x(i) circuit_qiskit_two_validated.id(i) circuit_qiskit_two_validated.cx(0, 3) circuit_qiskit_two_validated.measure(2, 3) # Define test mask matrices test_mask_one = np.array( [ [1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1], ] ) test_mask_two = np.array( [ [1, 0], [1, 1], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], ] ) one_mask = np.array( [ [0, 1, 1, 1, 1], [1, 0, 1, 1, 1], [1, 1, 0, 1, 1], [1, 1, 1, 0, 1], [1, 1, 1, 1, 0], [0, 1, 0, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], ] ) two_mask = np.array( [ [0, 0, 1, 1, 1], [1, 0, 0, 1, 1], [1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [0, 0, 1, 0, 0], ] ) mixed_mask = np.array( [ [1, 0, 1, 1, 1], [1, 1, 0, 0, 1], [0, 0, 0, 1, 1], [1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], ] ) # Define test slack matrices one_slack = np.array( [ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], ] ) two_slack = np.array( [ [2, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 2, 0], [2, 0, 0, 2, 0], ] ) mixed_slack = np.array( [ [0, 1, 0, 0, 0], [0, 0, 2, 0, 0], [3, 0, 0, 0, 0], [0, 0, 3, 0, 0], [0, 4, 0, 0, 0], [5, 0, 0, 0, 0], [0, 0, 0, 0, 0], ] ) masks = [one_mask, two_mask, mixed_mask] slack_matrices = [one_slack, two_slack, mixed_slack] @pytest.mark.parametrize( ("circuit", "test_mask"), [(circuit_cirq_one, test_mask_one), (circuit_cirq_two, test_mask_two)], ) def test_get_circuit_mask(circuit, test_mask): circuit_mask = _get_circuit_mask(circuit) assert np.allclose(circuit_mask, test_mask) def test_get_slack_matrix_from_circuit_mask(): for mask, expected in zip(masks, slack_matrices): slack_matrix = get_slack_matrix_from_circuit_mask(mask) assert np.allclose(slack_matrix, expected) def test_get_slack_matrix_from_circuit_mask_extreme_cases(): assert np.allclose( get_slack_matrix_from_circuit_mask(np.array([[0]])), np.array([[1]]) ) assert np.allclose( get_slack_matrix_from_circuit_mask(np.array([[1]])), np.array([[0]]) ) def test_get_slack_matrix_from_circuit__bad_input_errors(): with pytest.raises(TypeError, match="must be a numpy"): get_slack_matrix_from_circuit_mask([[1, 0], [0, 1]]) with pytest.raises(ValueError, match="must be a 2-dimensional"): get_slack_matrix_from_circuit_mask(np.array([1, 2])) with pytest.raises(TypeError, match="must have integer elements"): get_slack_matrix_from_circuit_mask(np.array([[1, 0], [1, 1.7]])) with pytest.raises(ValueError, match="elements must be 0 or 1"): get_slack_matrix_from_circuit_mask(np.array([[2, 0], [0, 0]])) @pytest.mark.parametrize( ("circuit", "result", "rule"), [ (circuit_cirq_two, circuit_cirq_two, xx), (circuit_cirq_three, circuit_cirq_three_validated, xyxy), (circuit_qiskit_one, circuit_qiskit_validated, xx), (circuit_qiskit_two, circuit_qiskit_two_validated, xx), ], ) def test_insert_sequences(circuit, result, rule): circuit_with_sequences = insert_ddd_sequences(circuit, rule) assert circuit_with_sequences == result def test_midcircuit_measurement_raises_error(): qreg = qiskit.QuantumRegister(2) creg = qiskit.ClassicalRegister(1) circuit = qiskit.QuantumCircuit(qreg, creg) for q in qreg: circuit.x(q) circuit.measure(0, 0) circuit.cx(0, 1) with pytest.raises(ValueError, match="midcircuit measurements"): insert_ddd_sequences(circuit, xx) def test_pyquil_midcircuit_measurement_raises_error(): p = pyquil.Program() cbit = p.declare("cbit") p += pyquil.gates.X(0) p += pyquil.gates.X(1) p += pyquil.gates.MEASURE(0, cbit[0]) p += pyquil.gates.X(0) with pytest.raises(ValueError, match="midcircuit measurements"): insert_ddd_sequences(p, xx) def test_insert_sequence_over_identity_gates(): qubits = cirq.LineQubit.range(2) circuit = cirq.Circuit( cirq.ops.H.on_each(*qubits), cirq.ops.I.on_each(*qubits), cirq.ops.I.on_each(*qubits), cirq.ops.H.on_each(*qubits), ) circuit_expected = cirq.Circuit( cirq.ops.H.on_each(*qubits), cirq.ops.X.on_each(*qubits), cirq.ops.X.on_each(*qubits), cirq.ops.H.on_each(*qubits), ) ddd_circuit = insert_ddd_sequences(circuit, rule=xx) assert ddd_circuit == circuit_expected
https://github.com/ankitkmisra/Quantum-Computing-and-Cryptography
ankitkmisra
from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1 = QuantumCircuit(3,3) # All initialized to '0' by default. qc1.x(0) #This is for the purpose of setting the control qubit to '1' qc1.x(2) #As a result, the second target qubit becomes '1' while the first remains '0'. Now, lets's try swapping them. #Fredkin gate: def fredkin(qc): qc.toffoli(0,1,2) qc.toffoli(0,2,1) qc.toffoli(0,1,2) fredkin(qc1) qc1.draw('mpl') #First let's measure all three qubits. #We're using the classical bits to store the result obtained on measuring each corresponding qubit. qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) #Now we use the same function we defined yesterday to run a quantum circuit def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts1=run_circuit(qc1) print(counts1) plot_histogram(counts1) qc2 = QuantumCircuit(3,3) # All initialized to '0' by default. qc2.x(2) #The second target qubit is initialised to '1' fredkin(qc2) qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw(output='mpl') counts2=run_circuit(qc2) print(counts2) plot_histogram(counts2) qc = QuantumCircuit(1) #This is how we apply the rotation operators in Qiskit, mentioning the angle of rotation and qubit no. as parameters qc.rx(np.pi/2, 0) qc.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc)) # This prints the vector obtained on applying the above gate to the qubit state '0' # The Pauli-X gate serves this purpose, as demonstrated below: qc3 = QuantumCircuit(1) theta = np.pi/7 qc3.x(0) qc3.ry(theta, 0) qc3.x(0) print(final_vector(qc3)) qc3 = QuantumCircuit(1) qc3.ry(-theta, 0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case qc4 = QuantumCircuit(1) alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc4, 0, beta, delta) qc4.x(0) B(qc4, 0, beta, gamma, delta) qc4.x(0) A(qc4, 0, beta, gamma) qc4.unitary([[1.j, 0.], [0., 1.j]], [0]) print(final_vector(qc4)) qc4 = QuantumCircuit(1) qc4.h(0) print(final_vector(qc4)) qc5 = QuantumCircuit(3, 3) # Target qubit q1 is initially |1> and target qubit q2 is initially |0>. qc5.x(0) # Control qubit initialized to |1> to see effects of controlled Hadamard. qc5.x(1) # One target qubit initialized to |1>. alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc5, [1, 2], beta, delta) qc5.cx(0, [1, 2]) B(qc5, [1, 2], beta, gamma, delta) qc5.cx(0, [1, 2]) A(qc5, [1, 2], beta, gamma) qc5.s(0) # Using S gate because alpha = pi/2 qc5.measure(0, 0) qc5.measure(1, 1) qc5.measure(2, 2) qc5.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 10000).result() counts = result.get_counts() return counts counts = run_circuit(qc5) print(counts) plot_histogram(counts) qc_u3=QuantumCircuit(1) qc_u3.u3(np.pi/6,-np.pi/2,np.pi/2,0) print(final_vector(qc_u3)) qc_rx=QuantumCircuit(1) qc_rx.rx(np.pi/6,0) print(final_vector(qc_rx)) #Getting the same results will verify our observation stated above ######### Defining some constants and functions ########## # Constants for the decomposition of Hadamard gate. H_alpha = np.pi/2 H_beta = 0 H_gamma = np.pi/2 H_delta = np.pi # V^2 = X V = [[0.5+0.5j, 0.5-0.5j], [0.5-0.5j, 0.5+0.5j]] # Constants for the decomposition of V (where V^2 = X). V_alpha = np.pi/4 V_beta = np.pi/2 V_gamma = -np.pi/2 V_delta = -np.pi/2 # Functions to implement A, B, C (generalized). def A_gate(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B_gate(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C_gate(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) # Higher abstraction functions. def controlled_V(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, V_gamma) qc.t(control) # Using T gate because V_alpha = pi/4. def controlled_Vdg(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, -V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, -V_gamma) qc.tdg(control) # Using Tdg gate because V_alpha = pi/4, so Vdg_alpha would be -pi/4. def double_controlled_X(qc, control1, control2, target): controlled_V(qc, control2, target) qc.cx(control1, control2) controlled_Vdg(qc, control2, target) qc.cx(control1, control2) controlled_V(qc, control1, target) ############ Constructing the circuit ############## qc6 = QuantumCircuit(7, 5) # No need to measure ancillary qubits :P # q0, q1, q2, q3 are control qubits # q4, q5 are ancillary qubits # q6 is the target qubit # Change the following line to try different combinations of control qubits: qc6.x([0,1,2,3]) C_gate(qc6, 6, H_beta, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) B_gate(qc6, 6, H_beta, H_gamma, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) A_gate(qc6, 6, H_beta, H_gamma) qc6.s([0,1,2,3]) # Using S gate because H_alpha = pi/2. qc6.measure(0, 0) qc6.measure(1, 1) qc6.measure(2, 2) qc6.measure(3, 3) qc6.measure(6, 4) qc6.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/abbarreto/qiskit3
abbarreto
from qiskit.circuit import Parameter from qiskit import QuantumCircuit theta = Parameter('$\\theta$') chsh_circuits_no_meas = QuantumCircuit(2) chsh_circuits_no_meas.h(0) chsh_circuits_no_meas.cx(0, 1) chsh_circuits_no_meas.ry(theta, 0) chsh_circuits_no_meas.draw('mpl') import numpy as np number_of_phases = 21 phases = np.linspace(0, 2*np.pi, number_of_phases) # Phases need to be expressed as list of lists in order to work individual_phases = [[ph] for ph in phases] individual_phases from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] # Simulator with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) est_result = job.result() chsh_est_sim.append(est_result) # <CHSH1> = <AB> - <Ab> + <aB> + <ab> chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values # <CHSH2> = <AB> + <Ab> - <aB> + <ab> chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend() from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp backend = service.get_backend("ibmq_belem") ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) print(job.job_id()) est_result = job.result() chsh_est_sim.append(est_result) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_quito" from qiskit_ibm_runtime import Estimator, Session from qiskit.quantum_info import SparsePauliOp #from qiskit.tools.monitor import job_monitor ZZ = SparsePauliOp.from_list([("ZZ", 1)]) ZX = SparsePauliOp.from_list([("ZX", 1)]) XZ = SparsePauliOp.from_list([("XZ", 1)]) XX = SparsePauliOp.from_list([("XX", 1)]) ops = [ZZ, ZX, XZ, XX] chsh_est_sim = [] with Session(service=service, backend=backend): estimator = Estimator() for op in ops: job = estimator.run( circuits=[chsh_circuits_no_meas]*len(individual_phases), observables=[op]*len(individual_phases), parameter_values=individual_phases) print(job.job_id()) #job_monitor(job) # deu erro est_result = job.result() chsh_est_sim.append(est_result) import matplotlib.pyplot as plt import matplotlib.ticker as tck fig, ax = plt.subplots(figsize=(10, 6)) # results from a simulator ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation') ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation') # classical bound +-2 ax.axhline(y=2, color='r', linestyle='--') ax.axhline(y=-2, color='r', linestyle='--') # quantum bound, +-2√2 ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.') ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.') # set x tick labels to the unit of pi ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$')) ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5)) # set title, labels, and legend plt.title('Violation of CHSH Inequality') plt.xlabel('Theta') plt.ylabel('CHSH witness') plt.legend()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer qreg = QuantumRegister(4) # quantum register with 4 qubits creg = ClassicalRegister(4) # classical register with 4 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to each qubit for i in range(4): mycircuit.h(qreg[i]) # measure both qubits mycircuit.measure(qreg,creg) # execute the circuit 1600 times, and print the outcomes job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600) counts = job.result().get_counts(mycircuit) for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # find the angle theta u2 = [(13/16)**0.5,(3/16)**0.5] print(u2) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta2 = angle_between_two_quantum_states(u2,[1,0]) print(theta2) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states2 =[] qreg2 = QuantumRegister(1) # quantum register with 1 qubit creg2 = ClassicalRegister(1) # classical register with 1 bit mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta2 # do not forget to multiply it by 2 mycircuit2.ry(2*theta2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['u',x,y]) # this is (-2*theta2) in the first iteration rotation_angle_for_the_first_reflection2 = -2 * theta2 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection2) rotation_angle_for_the_second_reflection2 = (2*theta2) + (-1*rotation_angle_for_the_first_reflection2) # the first reflection: rotate by rotation_angle_for_the_first_reflection2 mycircuit2.ry(2*rotation_angle_for_the_first_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['r',x,y]) # the label is r (reflected state) # the second reflection: rotate by rotation_angle_for_the_second_reflection2 mycircuit2.ry(2*rotation_angle_for_the_second_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['n',x,y]) # the label is n (new state) visualize_quantum_states(all_visited_quantum_states2) # measure both qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts2 = job.result().get_counts(mycircuit2) for outcome in counts2: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts2[outcome],"times") print(all_visited_quantum_states2) # find the angle theta u3 = [(63/64)**0.5,(1/64)**0.5] print(u3) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta3 = angle_between_two_quantum_states(u3,[1,0]) print(theta3) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states3 =[] qreg3 = QuantumRegister(1) # quantum register with 1 qubit creg3 = ClassicalRegister(1) # classical register with 1 bit mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta3 # do not forget to multiply it by 2 mycircuit3.ry(2*theta3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['u',x,y]) # this is -2 * theta3 in the first iteration rotation_angle_for_the_first_reflection3 = -2 * theta3 # this is always (2*theta3) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) for i in range(3): # three iterations # later check 4, 5, 6, 7, 8, 9, and 10 # the first reflection: rotate by rotation_angle_for_the_first_reflection3 mycircuit3.ry(2*rotation_angle_for_the_first_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['r'+str(i+1),x,y]) # the labels are r1, r2, ... (reflected states) # the second reflection: rotate by rotation_angle_for_the_second_reflection3 mycircuit3.ry(2*rotation_angle_for_the_second_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['n'+str(i+1),x,y]) # the labels are n1, n2, ... (new states) # this will be increased by (-4*theta2) after each iteration rotation_angle_for_the_first_reflection3 = rotation_angle_for_the_first_reflection3 -4* theta3 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) # end of iterations visualize_quantum_states(all_visited_quantum_states3) # measure both qubits mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts3 = job.result().get_counts(mycircuit3) for outcome in counts3: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts3[outcome],"times") print(all_visited_quantum_states3) # find the angle theta # k=8, 2^k = 256 u4 = [(255/256)**0.5,(1/256)**0.5] print(u4) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta4 = angle_between_two_quantum_states(u4,[1,0]) print(theta4) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer how_many_times_state_one_observed = 0 decrease = False number_of_iteration = 1 while decrease == False: qreg4 = QuantumRegister(1) # quantum register with 1 qubit creg4 = ClassicalRegister(1) # classical register with 1 bit mycircuit4 = QuantumCircuit(qreg4,creg4) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta4 # do not forget to multiply it by 2 mycircuit4.ry(2*theta4,qreg4[0]) # this is -2 * theta4 in the first iteration rotation_angle_for_the_first_reflection4 = -2 * theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) for i in range(number_of_iteration): # the first reflection: rotate by rotation_angle_for_the_first_reflection4 mycircuit4.ry(2*rotation_angle_for_the_first_reflection4,qreg4[0]) # the second reflection: rotate by rotation_angle_for_the_second_reflcetion4 mycircuit4.ry(2*rotation_angle_for_the_second_reflection4,qreg4[0]) # this will be increased by (-4*theta4) after each iteration rotation_angle_for_the_first_reflection4 = rotation_angle_for_the_first_reflection4 -4* theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) # end of iterations # measure both qubits mycircuit4.measure(qreg4,creg4) # execute the circuit 1000 times, and print the outcomes job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=1000) counts4 = job.result().get_counts(mycircuit4) print(number_of_iteration,counts4) # print the outcomes for outcome in counts4: if outcome == '1': # how_many_times_state_one_observed is more than 500 and has a less value than the previous one # then it is time to STOP if how_many_times_state_one_observed> 500 and how_many_times_state_one_observed > counts4[outcome]: print("B is",number_of_iteration-1) decrease = True else: # we should continue how_many_times_state_one_observed = counts4[outcome] # update how_many_times_state_one_observed number_of_iteration = number_of_iteration + 1 # increase number_of_iteration
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() fermionic_op = problem.hamiltonian.second_q_op() from qiskit_nature.second_q.mappers import JordanWignerMapper mapper = JordanWignerMapper() qubit_jw_op = mapper.map(fermionic_op) print(qubit_jw_op) from qiskit_nature.second_q.mappers import ParityMapper mapper = ParityMapper() qubit_p_op = mapper.map(fermionic_op) print(qubit_p_op) mapper = ParityMapper(num_particles=problem.num_particles) qubit_op = mapper.map(fermionic_op) print(qubit_op) tapered_mapper = problem.get_tapered_mapper(mapper) print(type(tapered_mapper)) qubit_op = tapered_mapper.map(fermionic_op) print(qubit_op) from qiskit_nature.second_q.circuit.library import HartreeFock hf_state = HartreeFock(2, (1, 1), JordanWignerMapper()) hf_state.draw() from qiskit_nature.second_q.mappers import InterleavedQubitMapper interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper()) hf_state = HartreeFock(2, (1, 1), interleaved_mapper) hf_state.draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### replaced cx gate ### qc.cy(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).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
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
import random from qiskit import QuantumCircuit from QiskitPBT.case_studies.deutsch_jozsa.deutsch_jozsa import deutsch_jozsa_circ from QiskitPBT.case_studies.deutsch_jozsa.dj_helpers import ConstantOracleInputGenerator from QiskitPBT.property import Property class DeutschJozsaWorksForConstantFunction(Property): # specify the inputs that are to be generated def get_input_generators(self): return [ConstantOracleInputGenerator(5, 10)] # specify the preconditions for the test def preconditions(self, oracle): return True # specify the operations to be performed on the input def operations(self, oracle: QuantumCircuit): circ = deutsch_jozsa_circ(oracle) # if oracle is constant this should be all 0 baseline = QuantumCircuit(oracle.num_qubits - 1, oracle.num_qubits - 1) self.statistical_analysis.assert_equal(self, list(range(oracle.num_qubits - 1)), circ, list(range(oracle.num_qubits - 1)), baseline, basis=["z"])
https://github.com/rmlarose/qcbq
rmlarose
# Do the necessary import for our program #!pip install qiskit-aqua from qiskit import BasicAer from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle from qiskit.tools.visualization import plot_histogram log_expr = '((A & B) | (C & D)) & ~(A & D)' algorithm = Grover(LogicalExpressionOracle(log_expr)) # Run the algorithm on a simulator, printing the most frequently occurring result backend = BasicAer.get_backend('qasm_simulator') result = algorithm.run(backend) print(result['top_measurement']) plot_histogram(result['measurement'])
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'ccx', 'barrier', 'measure', 'snapshot'] or_oracle = QuantumCircuit(3) or_oracle.x(range(2)) or_oracle.ccx(0,1,2) or_oracle.x(range(3)) # Do not change below this line or_oracle.draw(output='mpl') or_tt = ['000', '011', '101', '111'] def check_or_oracle(tt_row): check_qc = QuantumCircuit(3) for i in range(2): if (tt_row[i] == '1'): check_qc.x(i) check_qc.extend(or_oracle) check_qc.measure_all() return (execute(check_qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() == tt_row) try: assert list(or_oracle.count_ops()) != [], f"Circuit cannot be empty" assert 'measure' not in or_oracle.count_ops(), f"Please remove measurements" assert set(or_oracle.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" for tt_row in or_tt: assert check_or_oracle(tt_row), f" Input {tt_row[0:2]}: Your encoding is not correct" print("Your oracle construction passed all checks") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') bv_oracle = QuantumCircuit(3) bv_oracle.cx(0,2) bv_oracle.cx(1,2) bv_oracle.draw('mpl') bv_circ = QuantumCircuit(3,2) bv_circ.x(2) bv_circ.h(range(3)) bv_circ.barrier() # Extend the circuit using bv_oracle bv_circ.extend(bv_oracle) bv_circ.barrier() # Apply the Hadamard transformation on all qubits and then measure q_0 and q_1 bv_circ.h(range(3)) bv_circ.measure([0,1], [0,1]) # Do not remove this line bv_circ.draw(output='mpl') try: assert list(bv_circ.count_ops()) != [], f"Circuit cannot be empty" assert set(bv_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" counts = execute(bv_circ.reverse_bits(), backend=QasmSimulator(), shots=8192).result().get_counts() assert list(counts.keys()) == ['11'], "Your circuit did not produce the right answer" print(" Your circuit produced the correct output. Please submit for evaluation.") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('statevector_simulator') qc1 = QuantumCircuit(4) # perform gate operations on individual qubits qc1.x(0) qc1.y(1) qc1.z(2) qc1.s(3) # Draw circuit qc1.draw() # Plot blochshere out1 = execute(qc1,backend).result().get_statevector() plot_bloch_multivector(out1) qc2 = QuantumCircuit(4) # initialize qubits qc2.x(range(4)) # perform gate operations on individual qubits qc2.x(0) qc2.y(1) qc2.z(2) qc2.s(3) # Draw circuit qc2.draw() # Plot blochshere out2 = execute(qc2,backend).result().get_statevector() plot_bloch_multivector(out2) qc3 = QuantumCircuit(4) # initialize qubits qc3.h(range(4)) # perform gate operations on individual qubits qc3.x(0) qc3.y(1) qc3.z(2) qc3.s(3) # Draw circuit qc3.draw() # Plot blochshere out3 = execute(qc3,backend).result().get_statevector() plot_bloch_multivector(out3) qc4 = QuantumCircuit(4) # initialize qubits qc4.x(range(4)) qc4.h(range(4)) # perform gate operations on individual qubits qc4.x(0) qc4.y(1) qc4.z(2) qc4.s(3) # Draw circuit qc4.draw() # Plot blochshere out4 = execute(qc4,backend).result().get_statevector() plot_bloch_multivector(out4) qc5 = QuantumCircuit(4) # initialize qubits qc5.h(range(4)) qc5.s(range(4)) # perform gate operations on individual qubits qc5.x(0) qc5.y(1) qc5.z(2) qc5.s(3) # Draw circuit qc5.draw() # Plot blochshere out5 = execute(qc5,backend).result().get_statevector() plot_bloch_multivector(out5) qc6 = QuantumCircuit(4) # initialize qubits qc6.x(range(4)) qc6.h(range(4)) qc6.s(range(4)) # perform gate operations on individual qubits qc6.x(0) qc6.y(1) qc6.z(2) qc6.s(3) # Draw circuit qc6.draw() # Plot blochshere out6 = execute(qc6,backend).result().get_statevector() plot_bloch_multivector(out6) import qiskit qiskit.__qiskit_version__
https://github.com/Dpbm/scientific-research-1-quantum-oracles
Dpbm
%matplotlib inline from qiskit import QuantumCircuit, transpile, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit.quantum_info import Statevector from qiskit_aer import AerSimulator from qiskit_ibm_provider import IBMProvider import matplotlib.pyplot as plt import numpy as np import pandas as pd from dotenv import load_dotenv from tqdm.notebook import tqdm import functools import os from time import time from collections import defaultdict from utils import fibonacci, fibonacci_no_cache, get_image_path ONE_KM_TO_MILES=0.621371 @functools.lru_cache(maxsize=1000) def km_to_miles(km, last=0, n=0): fib_value = fibonacci(n) if(fib_value == km): return last if(fib_value > km*ONE_KM_TO_MILES): raise Exception(f"{km} Not in the sequence") return km_to_miles(km, fib_value, n+1) km_to_miles(21) @functools.lru_cache(maxsize=1000) def miles_to_km(miles, last=0, n=0): fib_value = fibonacci(n) if(last == miles): return fib_value if(fib_value > miles/ONE_KM_TO_MILES): raise Exception(f"{miles} Not in the sequence") return miles_to_km(miles, fib_value, n+1) miles_to_km(13) km_miles = lambda km : km*ONE_KM_TO_MILES miles_km = lambda miles: miles/ONE_KM_TO_MILES km_miles(12) km_miles(24) BASE_NUMBERS = (1, 2, 3, 5, 8, 13, 21) def breakdown(n, base_numbers=BASE_NUMBERS): used_numbers = defaultdict(int) for base_number in reversed(base_numbers): while(base_number <= n): used_numbers[base_number] += 1 n -= base_number return dict(used_numbers) breakdown(10) def get_fib_pos(n, base_numbers=BASE_NUMBERS): return base_numbers.index(n) def get_relative_miles_km(n): numbers = list(BASE_NUMBERS)+[34] pos = get_fib_pos(n) return numbers[pos+1] def get_relative_km_miles(n): numbers = [1]+list(BASE_NUMBERS) pos = get_fib_pos(n) return numbers[pos] get_relative_miles_km(8) get_relative_km_miles(8) def new_miles_to_km(n): result = 0 factors = breakdown(n) for (number, total) in factors.items(): relative = get_relative_miles_km(number) result += (relative*total) return result new_miles_to_km(15) def new_km_to_miles(n): result = 0 factors = breakdown(n) print(factors) for (number, total) in factors.items(): relative = get_relative_km_miles(number) result += (relative*total) return result new_km_to_miles(12) PI = np.pi class Oracle(QuantumCircuit): def __init__(self, n_qubits): assert n_qubits >= 2, "Invalid number of qubits!" self.n_qubits = n_qubits super().__init__(n_qubits, name="oracle") self.generate() def generate(self): self.ry(PI/2, range(self.n_qubits)) for i in range(self.n_qubits-1): self.cry(-PI/2, i, i+1) def simulate(self, backend=AerSimulator(), shots=1000): qc_copy = self.copy() qc_copy.measure_all() transpiled_qc = transpile(qc_copy, backend) return backend.run(transpiled_qc).result().get_counts() oracle = Oracle(2) display(oracle.draw('mpl')) class KM_to_Miles(object): def __init__(self, iterations=3, base_oracle=Oracle): self.iterations = iterations self.total_qubits = 2 self.oracle = base_oracle self.qc = self.oracle(2) self.results = pd.DataFrame(columns=['n_qubits', 'result']) def run(self, backend=AerSimulator(), shots=1000, debug=True): for i in tqdm(range(self.iterations)): results = self.qc.simulate(backend, shots) fibonacci_number = len(results) if(debug): print('-'*20) print(f'i: {i}') print(f'n: {self.total_qubits}') print(f'F({i}): {fibonacci_number}') self.results = pd.concat([self.results, pd.DataFrame({'n_qubits':self.total_qubits, 'result':fibonacci_number}, columns=['n_qubits', 'result'], index=[iter])], ignore_index=True) self.total_qubits+=1 self.qc = self.oracle(self.total_qubits) converter = KM_to_Miles(10) converter.run(debug=False) quantum_results = converter.results quantum_results def generate_miles_km_table(iter=3): return pd.DataFrame([(fibonacci(i), fibonacci(i+1)) for i in range(iter)], columns=['miles', 'km']) miles_km_data = generate_miles_km_table(12).loc[2:].reset_index().drop(columns=['index']) miles_km_data miles_km_data.shape, quantum_results.shape def get_all_data(iter, converter, shots=1000): miles_km = generate_miles_km_table(iter+2).loc[2:].reset_index().drop(columns=['index']) converter_obj = KM_to_Miles(iter) converter_obj.run(shots=shots, debug=False) all_data = pd.concat([miles_km, converter_obj.results], axis=1) return all_data result_data = get_all_data(24, converter, shots=100000) result_data.tail() fig, ((ax1,ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10)) first_batch = result_data.loc[:8] ax1.plot('miles', 'km', data=first_batch) ax1.plot('miles', 'result', data=first_batch) ax1.set_title('[0-7]') ax1.set(xlabel="miles", ylabel="km") second_batch = result_data.loc[8:16] ax2.plot('miles', 'km', data=second_batch) ax2.plot('miles', 'result', data=second_batch) ax2.set_title('[8-15]') ax2.set(xlabel="miles", ylabel="km") third_batch = result_data.loc[16:] ax3.plot('miles', 'km', data=third_batch) ax3.plot('miles', 'result', data=third_batch) ax3.set_title('[16-23]') ax3.set(xlabel="miles", ylabel="km") ax4.set_visible(False) fig.legend(["classical", "quantum"], bbox_to_anchor=(0.75,0.4), fontsize=20) plt.savefig(get_image_path("miles_to_km_defiance.png")) plt.show() QUANTUM_BASE_NUMBERS = (3, 5, 8, 13, 21) def get_quantum_fib_numbers(inp_value, base_numbers=QUANTUM_BASE_NUMBERS): breakdown_values = breakdown(inp_value, base_numbers=base_numbers) remain = inp_value - sum(breakdown_values.keys()) remain_values = {} if(remain > 0): REMAIN_BASE_NUMBERS = (1, 2) remain_values = breakdown(remain, base_numbers=REMAIN_BASE_NUMBERS) return breakdown_values, remain_values values, remain = get_quantum_fib_numbers(100) values total_n_qubits = [ get_fib_pos(i, base_numbers=QUANTUM_BASE_NUMBERS)+2 for i in values ] n_qubits = max(total_n_qubits) measures = len(total_n_qubits) total_n_qubits, n_qubits, measures qubits = QuantumRegister(n_qubits, name="q") measurements = [ClassicalRegister(cbits, name=index) for (index, cbits) in enumerate(total_n_qubits)] qc = QuantumCircuit(qubits, *measurements) for n, measurement in zip(total_n_qubits, measurements): qc.append(Oracle(n), range(n)) qc.measure(range(n), measurement) qc.reset(range(n)) qc.barrier() qc.draw('mpl', filename=get_image_path("number_breakdown_circuit.png")) def get_counts(qc, sim=AerSimulator()): return sim.run(transpile(qc, sim)).result().get_counts() result = get_counts(qc) plot_histogram(result) bit_string = result.keys() total = result.values() data = {"bit_string": bit_string, 'total':total} df = pd.DataFrame(data, columns=['bit_string', 'total']) df.head() df[['bit_string0', 'bit_string1', 'bit_string2']] = df['bit_string'].str.split(' ', n=2, expand=True) df.head() len(df['bit_string0'].unique()), len(df['bit_string1'].unique()), len(df['bit_string2'].unique()) def get_times(func, values_range): results = [] for i in values_range: start = time() func(i) results.append(time() - start) return results def quantum_run(n): qc = Oracle(n) qc.simulate() values_range = range(2, 25) classical_no_cache_results = pd.Series(get_times(fibonacci_no_cache, values_range), dtype=np.float64) classical_cache_results = pd.Series(get_times(fibonacci, values_range), dtype=np.float64) quantum_local = pd.Series(get_times(quantum_run, values_range), dtype=np.float64) times_data = pd.DataFrame({ "n": pd.Series(list(values_range), dtype=np.int8), "classical_nc": classical_no_cache_results, "classical_c": classical_cache_results, "quantum_local": quantum_local }) times_data.head() load_dotenv() IBMProvider.save_account(token=os.getenv("IBM_TOKEN"), overwrite=True) provider = IBMProvider() backends = provider.backends(min_num_qubits=25, operational=True, simulator=False) min_pending_jobs = 1000000000 selected_backend = '' for backend in backends: backend_name = backend.name pending_jobs = backend.status().pending_jobs if(pending_jobs < min_pending_jobs): min_pending_jobs = pending_jobs selected_backend = backend_name print(f'name: {backend_name}') print(f'qubits: {backend.num_qubits}') print(f'max_shots: {backend.max_shots}') print(f'jobs: {pending_jobs}') print(f'max_circuits: {backend.max_circuits}', end='\n\n') backend = provider.get_backend(selected_backend) circuits = [transpile(Oracle(n), backend) for n in values_range ] ids = [] for i,circuit in enumerate(circuits): status = None job = backend.run(circuit, shots=1000) id = job.job_id() print(f'circuit: {i+1}') print(f'job: {id}', end='\n\n') ids.append(id) while status != 'DONE': status = job.status().name results = [provider.retrieve_job(job_id).result()._metadata['time_taken'] for job_id in ids] quantum_ibm = pd.Series(results, dtype=np.float64) times_data['quantum_ibm'] = quantum_ibm times_data.head() index = times_data.index.tolist() plt.plot(index, "classical_nc", data=times_data) plt.plot(index, "classical_c", data=times_data) plt.plot(index, "quantum_local", data=times_data) plt.plot(index, "quantum_ibm", data=times_data) plt.legend() plt.savefig(get_image_path("comparison_miles_to_km.png")) plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/MiChaelinzo/Quantum-time-travel
MiChaelinzo
""" At the command line, only need to run once to install the package via pip: $ pip install google-generativeai """ import google.generativeai as genai genai.configure(api_key="YOUR_API_KEY") # Set up the model generation_config = { "temperature": 1, "top_p": 0.95, "top_k": 0, "max_output_tokens": 8192, } safety_settings = [ { "category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE" }, { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE" }, ] system_instruction = "https://www.nature.com/articles/s41598-019-40765-6 use this to base some of the generated code be comprehensive and precise" model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest", generation_config=generation_config, system_instruction=system_instruction, safety_settings=safety_settings) convo = model.start_chat(history=[ { "role": "user", "parts": ["from the article generate a working algorithm I can use in IBM Quantum lab"] }, { "role": "model", "parts": ["## Quantum Algorithm based on Nature Article: A Starting Point\n\nDue to the limitations of accessing external websites and specific PDFs directly, I cannot provide a fully tailored algorithm based on the exact article you linked. However, I can offer a general framework and code snippets inspired by typical quantum chemistry applications, which often involve VQE (Variational Quantum Eigensolver) for finding ground state energies of molecules. This should provide a good starting point for your exploration in IBM Quantum Lab.\n\n**General Framework:**\n\n1. **Molecular Hamiltonian Encoding:**\n - Define the molecule you want to study (e.g., H2 molecule).\n - Use a quantum chemistry software package like PySCF or OpenFermion to obtain the Hamiltonian in second quantization form.\n - Map the fermionic Hamiltonian to a qubit Hamiltonian using techniques like Jordan-Wigner or Bravyi-Kitaev transformation. \n\n2. **Ansatz Preparation:**\n - Choose a suitable parameterized quantum circuit (ansatz) to represent the trial wavefunction.\n - Examples include the Unitary Coupled Cluster (UCC) ansatz or the Hardware Efficient Ansatz.\n - The ansatz will have free parameters that need to be optimized.\n\n3. **VQE Implementation:**\n - Define a cost function as the expectation value of the Hamiltonian with respect to the ansatz state.\n - Use a classical optimization algorithm (e.g., COBYLA, SLSQP) to minimize the cost function by varying the ansatz parameters.\n - At each optimization step, the quantum circuit is executed on the quantum computer to estimate the expectation value.\n\n4. **Result Analysis:**\n - The optimized parameters define the approximate ground state wavefunction.\n - Calculate properties of interest like the ground state energy, bond lengths, or vibrational frequencies. \n\n**Code Snippet (Example using Qiskit):**\n\n```python\n# Import necessary libraries\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import X, Z, I, StateFn\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.algorithms import VQE, NumPyMinimumEigensolver\nfrom qiskit.circuit.library import EfficientSU2\n\n# Define molecule and Hamiltonian (replace with your molecule)\nmolecule = \"H2\"\nhamiltonian = # Obtain Hamiltonian using quantum chemistry packages\n\n# Define ansatz (replace with your chosen ansatz)\nansatz = EfficientSU2(num_qubits=2, entanglement='linear') \n\n# Set up VQE\nbackend = Aer.get_backend('statevector_simulator')\nquantum_instance = QuantumInstance(backend)\noptimizer = 'COBYLA' \n\n# Define the VQE algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=quantum_instance)\n\n# Run VQE and get the result\nresult = vqe.compute_minimum_eigenvalue(operator=hamiltonian)\n\n# Print the ground state energy\nprint(\"Ground state energy:\", result.eigenvalue.real)\n\n# Further analysis and calculations ...\n```\n\n**Note:** This code snippet is a basic example and needs to be adapted to your specific molecule, Hamiltonian, and chosen ansatz. You will need to fill in the missing parts, like obtaining the Hamiltonian using a quantum chemistry package and choosing a suitable ansatz.\n\n**Additional Considerations:**\n\n* **Noise Mitigation:** Real quantum computers are noisy. Consider error mitigation techniques to improve the accuracy of your results.\n* **Mapping:** Efficiently map your qubit Hamiltonian to the physical qubits of the quantum device you are using.\n* **Hardware limitations:** Be mindful of the number of qubits and the connectivity of the available quantum hardware.\n\nRemember, this is just a starting point. Explore the rich resources available in the Qiskit documentation and tutorials to delve deeper into quantum chemistry simulations and adapt this framework to your specific research interests."] }, { "role": "user", "parts": ["complete the code above"] }, { "role": "model", "parts": ["## Completing the Code: A Sample H2 Molecule Example\n\nHere's the completed code snippet with an example of the H2 molecule using the STO-3G basis set and the Parity Mapping technique:\n\n```python\n# Import necessary libraries\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import X, Z, I, StateFn, FermionicOp\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.algorithms import VQE, NumPyMinimumEigensolver\nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit_nature.drivers import PySCFDriver\nfrom qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem\nfrom qiskit_nature.mappers.second_quantization import ParityMapper\n\n# Specify molecule and basis set\nmolecule = \"H .0 .0 -{0}; H .0 .0 {0}\"\ndriver = PySCFDriver(atom=molecule.format(0.7414), basis='sto3g')\n\n# Set up electronic structure problem\nproblem = ElectronicStructureProblem(driver)\nsecond_q_ops = problem.second_q_ops()\nmain_op = second_q_ops[0]\n\n# Choose fermionic to qubit mapping\nmapper = ParityMapper()\nqubit_op = mapper.map(main_op)\n\n# Define ansatz \nansatz = EfficientSU2(num_qubits=qubit_op.num_qubits, entanglement='linear') \n\n# Set up VQE\nbackend = Aer.get_backend('statevector_simulator')\nquantum_instance = QuantumInstance(backend)\noptimizer = 'COBYLA' \n\n# Define the VQE algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=quantum_instance)\n\n# Run VQE and get the result\nresult = vqe.compute_minimum_eigenvalue(operator=qubit_op)\n\n# Print the ground state energy\nprint(\"Ground state energy:\", result.eigenvalue.real)\n\n# Further analysis and calculations ...\n```\n\n**Explanation:**\n\n1. **Import Libraries:** We import necessary libraries from Qiskit, including those for chemistry simulations (qiskit_nature) and the VQE algorithm. \n2. **Molecule Definition:** We specify the H2 molecule with a bond length of 0.7414 Angstroms and use the STO-3G basis set. \n3. **Electronic Structure Problem:** We set up the electronic structure problem using the PySCFDriver and obtain the Hamiltonian in second quantization form.\n4. **Fermionic to Qubit Mapping:** We choose the ParityMapper to map the fermionic Hamiltonian to a qubit Hamiltonian. \n5. **Ansatz Selection:** We select the EfficientSU2 ansatz with linear entanglement for the trial wavefunction.\n6. **VQE Setup:** We choose the 'statevector_simulator' backend for simulation and the 'COBYLA' optimizer for minimizing the energy.\n7. **VQE Execution:** We run the VQE algorithm and obtain the ground state energy of the H2 molecule.\n\n**Further Steps:**\n\n* **Change the molecule:** Modify the `molecule` variable to study different molecules.\n* **Experiment with Ansätze:** Try different ansätze like UCCSD or custom-designed circuits to see their impact on the results. \n* **Use a real quantum computer:** If you have access to real quantum hardware through IBM Quantum Experience, change the `backend` to run the experiment on actual quantum processors. Remember to account for noise and hardware limitations.\n* **Analyze the results:** Calculate additional properties like bond lengths, vibrational frequencies, or excited state energies. \n\n**Remember:** This code requires installing the `qiskit_nature` package. You can install it using pip:\n\n```\npip install qiskit-nature\n```\n\nI hope this completed example helps you get started with quantum chemistry simulations in IBM Quantum Lab!"] }, { "role": "user", "parts": ["does the code above work on console or notebook?"] }, { "role": "model", "parts": ["## Running the Code: Console vs Notebook\n\nThe code I provided can work in both environments:\n\n**Console:**\n\n* **Requirements:** You'll need to have Python and the required libraries (Qiskit, qiskit_nature) installed in your environment.\n* **Execution:** Save the code as a Python file (e.g., `h2_vqe.py`) and run it from your terminal using the command:\n\n```bash\npython h2_vqe.py\n```\n\n**Notebook (e.g., Jupyter Notebook):**\n\n* **Benefits:** Notebooks offer a more interactive experience, allowing you to run individual code cells, visualize results, and document your work within the same environment.\n* **Execution:** \n 1. Create a new Jupyter Notebook.\n 2. Paste the code into individual cells.\n 3. Run each cell sequentially. You can then visualize the results, add explanations, and experiment with modifications within the notebook.\n\n**Recommendation:**\n\nI would recommend using a **Jupyter Notebook** for running this code, especially if you're exploring and experimenting with different parameters or modifications. Notebooks provide a more user-friendly and interactive environment for scientific computing and quantum simulations.\n\n**Additional Tips:**\n\n* **Virtual Environments:** Consider using virtual environments to manage your project's dependencies and avoid conflicts with other Python projects.\n* **Visualization:** Use libraries like Matplotlib or Plotly to visualize the results of your simulations, such as plotting the energy convergence or the molecular orbitals.\n\nI hope this information helps! Let me know if you have any other questions."] }, { "role": "user", "parts": ["Traceback (most recent call last):\n Cell In[4], line 2\n from qiskit import Aer, QuantumCircuit\nImportError: cannot import name 'Aer' from 'qiskit' (/opt/conda/lib/python3.10/site-packages/qiskit/__init__.py)\n\nUse %tb to get the full traceback."] }, { "role": "model", "parts": ["## Troubleshooting the Import Error\n\nThe error message indicates that the `Aer` module cannot be imported from Qiskit. This could be due to several reasons:\n\n**1. Qiskit Version:**\n\n* **Older Qiskit versions:** In older versions of Qiskit (prior to 0.34.0), the `Aer` provider was located directly within the `qiskit` package. \n* **Newer Qiskit versions:** From Qiskit 0.34.0 onwards, the providers were moved to separate packages. `Aer` is now part of the `qiskit-aer` package.\n\n**Solution:**\n\n1. **Check Qiskit Version:** Run the following command in your terminal or notebook to check the installed Qiskit version:\n\n```bash\npip show qiskit\n```\n\n2. **Update or Install `qiskit-aer`:**\n\n* **If using an older Qiskit version:** Update Qiskit to the latest version using:\n\n```bash\npip install --upgrade qiskit\n```\n\n* **If using a newer Qiskit version:** Install the `qiskit-aer` package:\n\n```bash\npip install qiskit-aer\n```\n\n**3. Import Correction:**\n\n* **For newer Qiskit versions:** Update the import statement in your code to: \n\n```python\nfrom qiskit_aer import Aer\n```\n\n**Additional Tips:**\n\n* **Restart Kernel (Notebook):** If you were using a Jupyter Notebook, restart the kernel after installing/updating packages to ensure the changes take effect.\n* **Virtual Environments:** Consider using virtual environments to manage your project's dependencies and avoid conflicts between different Qiskit versions.\n\n**With the correct Qiskit version and import statement, the code should work as expected.**"] }, { "role": "user", "parts": ["Traceback (most recent call last):\n Cell In[2], line 3\n from qiskit.opflow import X, Z, I, StateFn, FermionicOp\nModuleNotFoundError: No module named 'qiskit.opflow'\n\nUse %tb to get the full traceback."] }, { "role": "model", "parts": ["## Resolving the `ModuleNotFoundError`\n\nThe error message indicates that the `qiskit.opflow` module is missing. This module is part of the `qiskit-terra` package, which is essential for core Qiskit functionalities. \n\n**Solution:**\n\n1. **Install `qiskit-terra`:**\n\n If you haven't already, install the `qiskit-terra` package using pip:\n\n ```bash\n pip install qiskit-terra\n ```\n\n2. **Verify Installation:**\n\n After installation, check if the `qiskit.opflow` module is accessible:\n\n ```python\n import qiskit.opflow\n ```\n\n If this doesn't raise an error, the installation was successful.\n\n**Additional Considerations:**\n\n* **Virtual Environments:** As mentioned before, using virtual environments is a good practice to isolate project dependencies and avoid conflicts.\n* **Complete Installation:** If you are starting a new project, consider installing the Qiskit metapackage, which includes all the commonly used Qiskit components:\n\n ```bash\n pip install qiskit\n ```\n\n**With `qiskit-terra` installed, the `qiskit.opflow` module should be available, and your code should run without the `ModuleNotFoundError`.**"] }, { "role": "user", "parts": ["Traceback (most recent call last):\n Cell In[2], line 2\n from qiskit import QuantumCircuit\n File /opt/conda/lib/python3.10/site-packages/qiskit/__init__.py:38\n raise ImportError(\nImportError: Qiskit is installed in an invalid environment that has both Qiskit >=1.0 and an earlier version. You should create a new virtual environment, and ensure that you do not mix dependencies between Qiskit <1.0 and >=1.0. Any packages that depend on 'qiskit-terra' are not compatible with Qiskit 1.0 and will need to be updated. Qiskit unfortunately cannot enforce this requirement during environment resolution. See https://qisk.it/packaging-1-0 for more detail.\n\nUse %tb to get the full traceback."] }, { "role": "model", "parts": ["## Resolving Qiskit Version Conflict\n\nThe error message indicates a conflict between different Qiskit versions in your environment. This can occur when you have both Qiskit versions below 1.0 and Qiskit 1.0 or later installed simultaneously. These versions have different package structures and dependencies, leading to compatibility issues.\n\n**Solution:**\n\nThe recommended approach is to create a new virtual environment and install the desired Qiskit version along with its compatible dependencies. Here's how:\n\n**1. Create a Virtual Environment:**\n\n* **Using `venv` (built-in module):**\n\n ```bash\n python3 -m venv my_qiskit_env\n ```\n\n* **Using `conda` (if you use Anaconda):**\n\n ```bash\n conda create --name my_qiskit_env python=3.8\n ```\n\n**2. Activate the Virtual Environment:**\n\n* **On Linux/macOS:**\n\n ```bash\n source my_qiskit_env/bin/activate\n ```\n\n* **On Windows:**\n\n ```bash\n my_qiskit_env\\Scripts\\activate\n ```\n\n**3. Install Qiskit and Dependencies:**\n\n Choose the appropriate installation command based on the Qiskit version you need:\n\n* **Qiskit 1.0 or later (recommended for new projects):**\n\n ```bash\n pip install qiskit\n ```\n\n* **Qiskit version below 1.0 (for compatibility with older projects):**\n\n ```bash\n pip install 'qiskit<0.35'\n ```\n\n**4. Install additional packages:**\n\n Install any other required packages for your project, ensuring they are compatible with your chosen Qiskit version. For example, install `qiskit-aer` for using the Aer simulator:\n\n ```bash\n pip install qiskit-aer\n ```\n\n**Additional Tips:**\n\n* **Check Package Versions:** Use `pip show"] }, { "role": "user", "parts": ["code me the same algorithm above using cirq_google"] }, { "role": "model", "parts": ["## Implementing the Algorithm with Cirq\n\nUnfortunately, directly translating the Qiskit code to Cirq involves significant modifications due to the fundamental differences between the two frameworks. Cirq focuses on near-term quantum devices and uses a different approach to quantum circuit construction and simulation. \n\nHere's a conceptual outline of how you might approach the problem using Cirq, but providing a complete working code example without access to specific details like the Hamiltonian representation and chosen Ansatz is challenging.\n\n**Conceptual Outline:**\n\n1. **Hamiltonian Definition:**\n * You'll need to represent the Hamiltonian of your molecule using Cirq's operations and qubits. This might involve defining individual Pauli terms or using Cirq's `PauliSum` class to represent the Hamiltonian as a sum of Pauli strings.\n\n2. **Ansatz Design:**\n * Create a parameterized quantum circuit using Cirq's gates and operations. This could be a custom circuit or an adaptation of existing Ansätze structures from other sources. \n\n3. **Expectation Value Evaluation:**\n * Use Cirq's simulation capabilities to calculate the expectation value of the Hamiltonian with respect to the Ansatz state. This often involves sampling or simulating the circuit execution.\n\n4. **Optimization:**\n * Implement a classical optimization loop using libraries like SciPy to find the parameters that minimize the expectation value, effectively approximating the ground state energy. \n\n**Challenges:**\n\n* **Mapping and Fermionic Operators:** Cirq doesn't have built-in functionalities for fermionic Hamiltonians or mappings like Jordan-Wigner. You'll likely need to handle these aspects manually or find external libraries that provide such features. \n* **Chemistry Libraries Integration:** Cirq's ecosystem for quantum chemistry applications is not as extensive as Qiskit's. You might need to explore alternative ways to obtain and represent molecular Hamiltonians. \n\n**Example Code Snippet (Illustrative):**\n\n```python\nimport cirq\n\n# Placeholder for Hamiltonian definition\nhamiltonian = # Define Hamiltonian using Cirq operations\n\n# Placeholder for Ansatz circuit\ndef ansatz(params):\n # Construct parameterized circuit using Cirq gates\n\n# Placeholder for expectation value calculation\ndef expectation_value(params):\n circuit = ansatz(params)\n # Simulate or sample circuit to estimate expectation value\n\n# Optimization (using SciPy, for example)\nfrom scipy.optimize import minimize\n\ninitial_params = # Initial guess for parameters\nresult = minimize(expectation_value, initial_params)\n\n# Access optimized parameters and energy\noptimized_params = result.x\noptimized_energy = result.fun\n\n# Further analysis and calculations...\n``` \n\n**Recommendations:**\n\n* **Cirq Documentation:** Refer to the Cirq documentation and tutorials to familiarize yourself with the framework's capabilities and syntax.\n* **OpenFermion:** Explore the OpenFermion library, which can be used with Cirq for some aspects of fermionic Hamiltonian manipulation. \n* **Community Resources:** Search for community-developed tools or libraries that extend Cirq for quantum chemistry applications."] }, { "role": "user", "parts": ["covert the code into cirq_google # Import necessary libraries\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import X, Z, I, StateFn, FermionicOp\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.algorithms import VQE, NumPyMinimumEigensolver\nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit_nature.drivers import PySCFDriver\nfrom qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem\nfrom qiskit_nature.mappers.second_quantization import ParityMapper\n\n# Specify molecule and basis set\nmolecule = \"H .0 .0 -{0}; H .0 .0 {0}\"\ndriver = PySCFDriver(atom=molecule.format(0.7414), basis='sto3g')\n\n# Set up electronic structure problem\nproblem = ElectronicStructureProblem(driver)\nsecond_q_ops = problem.second_q_ops()\nmain_op = second_q_ops[0]\n\n# Choose fermionic to qubit mapping\nmapper = ParityMapper()\nqubit_op = mapper.map(main_op)\n\n# Define ansatz \nansatz = EfficientSU2(num_qubits=qubit_op.num_qubits, entanglement='linear') \n\n# Set up VQE\nbackend = Aer.get_backend('statevector_simulator')\nquantum_instance = QuantumInstance(backend)\noptimizer = 'COBYLA' \n\n# Define the VQE algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=quantum_instance)\n\n# Run VQE and get the result\nresult = vqe.compute_minimum_eigenvalue(operator=qubit_op)\n\n# Print the ground state energy\nprint(\"Ground state energy:\", result.eigenvalue.real)\n\n# Further analysis and calculations ..."] }, { "role": "model", "parts": ["## Cirq Conversion: Challenges and Approach\n\nConverting the provided Qiskit code directly to Cirq for the H2 molecule simulation is not straightforward due to the differences in framework design and the complexities of handling fermionic Hamiltonians and mappings. Here's a breakdown of the challenges and a possible approach: \n\n**Challenges:**\n\n1. **Fermionic Hamiltonian and Mapping:** \n * Cirq does not natively support fermionic operators or mappings like Jordan-Wigner or ParityMapper. This functionality would need to be implemented manually or using external libraries. \n\n2. **Electronic Structure Problem Setup:**\n * Qiskit Nature provides convenient tools like `PySCFDriver` and `ElectronicStructureProblem` to handle molecule specification, basis sets, and Hamiltonian generation. Equivalent functionality would need to be established in Cirq, likely using external quantum chemistry packages like OpenFermion or PySCF directly. \n\n3. **Ansatz Design:**\n * The `EfficientSU2` ansatz is specific to Qiskit. A similar circuit structure would need to be built using Cirq's gates and operations.\n\n4. **VQE Implementation:**\n * Qiskit's `VQE` algorithm conveniently combines optimization and quantum simulation. In Cirq, you would need to manually implement the optimization loop using libraries like SciPy and integrate it with Cirq's simulation capabilities.\n\n**Possible Approach (Conceptual):**\n\n1. **Hamiltonian Representation:**\n * Use OpenFermion or PySCF to generate the H2 molecular Hamiltonian in second quantization form. \n * Implement or find a library to perform the fermionic-to-qubit mapping (e.g., Jordan-Wigner) to represent the Hamiltonian using Cirq's qubit operations (Pauli strings).\n\n2. **Ansatz Construction:**\n * Design a parameterized quantum circuit using Cirq's gates that resembles the structure and functionality of the `EfficientSU2` ansatz. \n\n3. **Expectation Value Evaluation:**\n * Use Cirq's simulator to calculate the expectation value of the Hamiltonian with respect to the parameterized Ansatz state.\n\n4. **Optimization Loop:**\n * Implement a classical optimization routine using SciPy's `minimize` function (or similar) to find the Ansatz parameters that minimize the expectation value.\n\n**Example Code Snippet (Illustrative, Incomplete):**\n\n```python\nimport cirq\nfrom openfermion import * # Assuming OpenFermion for Hamiltonian\n\n# (1) Hamiltonian generation using external library (OpenFermion example)\nmolecule = MolecularData(geometry=[('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))],\n basis='sto-3g', multiplicity=1)\nmolecule.load()\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# (2) Ansatz design using Cirq gates (replace with your design)\ndef ansatz(qubits, params):\n # Implement circuit using Cirq gates and parameters\n\n# (3) Expectation value calculation using Cirq simulator\ndef expectation_value(params):\n # Simulate the circuit and calculate expectation value\n\n# (4) Optimization loop (using SciPy)\nfrom scipy.optimize import minimize\n\n# ... (rest of the optimization implementation)\n```\n\n**Important Notes:**\n\n* This is a high-level outline. The actual implementation will require detailed knowledge of OpenFermion, Cirq, and optimization techniques. \n* Consider exploring existing community resources or libraries that might assist with fermionic Hamiltonians and quantum chemistry simulations in Cirq.\n* The code snippets provided are incomplete placeholders to illustrate the general approach.\n\n**I hope this explanation and conceptual outline provide a starting point for your exploration with Cirq! Let me know if you have any further questions.**"] }, { "role": "user", "parts": ["File \"<ipython-input-7-2e20917b6420>\", line 15\n def expectation_value(params):\n ^\nIndentationError: expected an indented block after function definition on line 11"] }, { "role": "model", "parts": ["## Fixing the Indentation Error\n\nThe error message indicates a Python syntax error related to indentation. In Python, indentation is crucial for defining code blocks, such as the body of a function. \n\n**Solution:**\n\nYou need to indent the code within the `expectation_value` function. In Python, the standard indentation is four spaces. Here's the corrected code snippet:\n\n```python\ndef expectation_value(params):\n # Indent the code within the function\n circuit = ansatz(params)\n # Simulate or sample circuit to estimate expectation value \n # ... (rest of the function implementation)\n```\n\n**Explanation:**\n\n* The line `def expectation_value(params):` defines the function header. \n* Any code that belongs to the function's body must be indented below the header. This tells Python which lines of code are part of the function. \n\n**Additional Tips:**\n\n* **Consistent Indentation:** Use consistent indentation throughout your code (typically four spaces) to improve readability and avoid errors. \n* **Code Editors:** Most code editors and IDEs automatically handle indentation, making it easier to write syntactically correct Python code. \n* **Linters:** Consider using a linter or code formatter to automatically check and correct indentation issues. \n\n**With the corrected indentation, your code should run without syntax errors.**"] }, { "role": "user", "parts": ["import cirq\nfrom openfermion import * # Assuming OpenFermion for Hamiltonian\n\n# (1) Hamiltonian generation using external library (OpenFermion example)\nmolecule = MolecularData(geometry=[('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))],\n basis='sto-3g', multiplicity=1)\nmolecule.load()\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# (2) Ansatz design using Cirq gates (replace with your design)\ndef ansatz(qubits, params):\n # Implement circuit using Cirq gates and parameters\n\n# (3) Expectation value calculation using Cirq simulator\ndef expectation_value(params):\n # Simulate the circuit and calculate expectation value\n\n# (4) Optimization loop (using SciPy)\nfrom scipy.optimize import minimize\n\n# ... (rest of the optimization implementation) complete this code"] }, { "role": "model", "parts": ["## Completing the Cirq Code (Illustrative Example) \n\nDue to the complexities of fermionic-to-qubit mapping and the specific requirements of the Ansatz circuit, I'll provide a conceptual completion of the code with placeholders and explanations. You'll need to adapt and fill in the details based on your chosen mapping method and Ansatz design.\n\n```python\nimport cirq\nfrom openfermion import *\nfrom scipy.optimize import minimize\n\n# ... (Hamiltonian generation as before) ...\n\n# (2) Ansatz Design Example (Simple layered circuit)\ndef ansatz(qubits, params):\n for i in range(len(qubits)):\n yield cirq.rx(params[2*i])(qubits[i])\n yield cirq.rz(params[2*i+1])(qubits[i])\n for i in range(len(qubits) - 1):\n yield cirq.CZ(qubits[i], qubits[i+1])\n\n# (3) Expectation Value (Assuming Jordan-Wigner Mapping)\ndef expectation_value(params):\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n circuit = cirq.Circuit(ansatz(qubits, params))\n simulator = cirq.Simulator()\n result = simulator.simulate(circuit)\n jw_hamiltonian = jordan_wigner(hamiltonian)\n expectation = jw_hamiltonian.expectation_from_state_vector(result.final_state_vector, qubits)\n return expectation.real\n\n# (4) Optimization Loop\ninitial_params = [0.0] * 2 * molecule.n_qubits\nresult = minimize(expectation_value, initial_params)\noptimized_params = result.x\noptimized_energy = result.fun\n\nprint(\"Optimized Energy:\", optimized_energy)\n```\n\n**Explanation:**\n\n1. **Ansatz:** This example uses a simple layered Ansatz with alternating single-qubit rotations and CZ gates. You'll likely need a more sophisticated Ansatz design based on your problem.\n\n2. **Expectation Value:** This assumes you've implemented or found a function `jordan_wigner` to perform the Jordan-Wigner mapping. The `cirq.Simulator` is used to simulate the circuit and obtain the final state vector. Then, the expectation value is calculated using OpenFermion's functionality.\n\n3. **Optimization:** The `scipy.optimize.minimize` function is used with the `expectation_value` function to find the optimal parameters.\n\n**Important Considerations:**\n\n* **Mapping:** Adapt the code based on the chosen mapping method. If you use a different mapping, you'll need to adjust the Hamiltonian representation and expectation value calculation accordingly.\n* **Ansatz:** Replace the example Ansatz with your desired circuit structure and parameterization.\n* **Simulation:** You might consider using noise models or different simulation methods depending on the complexity of the circuit and the available resources. \n\n**Remember, this is a simplified example. You'll need to carefully consider the details of your problem and choose appropriate techniques for Hamiltonian representation, mapping, Ansatz design, and simulation/optimization.**"] }, { "role": "user", "parts": ["ModuleNotFoundError Traceback (most recent call last)\n<ipython-input-11-da76afcd50d5> in <cell line: 2>()\n 1 import cirq\n----> 2 from openfermion import *\n 3 from scipy.optimize import minimize\n 4 \n 5 # ... (Hamiltonian generation as before) ...\n\nModuleNotFoundError: No module named 'openfermion'\n---------------------------------------------------------------------------\nNOTE: If your import is failing due to a missing package, you can\nmanually install dependencies using either !pip or !apt.\n\nTo view examples of installing some common dependencies, click the\n\"Open Examples\" button below.\n---------------------------------------------------------------------------"] }, { "role": "model", "parts": ["## Resolving `ModuleNotFoundError: openfermion`\n\nThe error message indicates that the `openfermion` module is not found in your current Python environment. This library is essential for handling fermionic Hamiltonians and performing operations related to quantum chemistry.\n\n**Solution:**\n\n1. **Install OpenFermion:**\n\n Use pip to install the `openfermion` package:\n\n ```bash\n pip install openfermion\n ```\n\n2. **Verify Installation:**\n\n After installation, try importing `openfermion` again:\n\n ```python\n import openfermion\n ```\n\n If this doesn't raise an error, the installation was successful.\n\n**Additional Considerations:**\n\n* **Virtual Environments:** As mentioned previously, using virtual environments helps manage dependencies and avoid conflicts between different projects. Make sure you've activated your virtual environment before installing `openfermion`.\n* **Dependencies:** OpenFermion has several dependencies, including NumPy, SciPy, and Psi4. The `pip install` command should automatically install these dependencies, but if you encounter issues, you might need to install them manually.\n* **Installation Issues:** If you face any problems during installation, refer to the OpenFermion documentation or online resources for troubleshooting tips. \n\n**With `openfermion` installed, you should be able to proceed with your quantum chemistry simulations using Cirq.**"] }, { "role": "user", "parts": ["---------------------------------------------------------------------------\nNameError Traceback (most recent call last)\n<ipython-input-14-da76afcd50d5> in <cell line: 26>()\n 24 \n 25 # (4) Optimization Loop\n---> 26 initial_params = [0.0] * 2 * molecule.n_qubits\n 27 result = minimize(expectation_value, initial_params)\n 28 optimized_params = result.x\n\nNameError: name 'molecule' is not defined"] }, { "role": "model", "parts": ["## Fixing the `NameError: molecule`\n\nThe error message indicates that the variable `molecule` is not defined within the scope where you are trying to use it. This is likely because the `molecule` variable was defined within the Hamiltonian generation section and is not accessible inside the optimization loop. \n\n**Solution:**\n\nYou need to make sure the `molecule` variable is accessible within the scope of the optimization loop. Here are two possible approaches:\n\n**1. Pass `molecule` as an Argument:**\n\n Modify the `expectation_value` function to accept `molecule` as an argument and pass it during the optimization:\n\n ```python\n def expectation_value(params, molecule): # Add molecule as argument\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n # ... (rest of the function) ...\n\n # In optimization loop:\n initial_params = [0.0] * 2 * molecule.n_qubits\n result = minimize(lambda params: expectation_value(params, molecule), initial_params) \n # Pass molecule to the function\n ``` \n\n**2. Make `molecule` a Global Variable (Less Recommended):**\n\n Declare `molecule` as a global variable before the Hamiltonian generation and use the `global` keyword within the `expectation_value` function to access it: \n\n ```python\n global molecule # Declare as global\n\n # ... (Hamiltonian generation) ... \n\n def expectation_value(params):\n global molecule # Access global variable\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n # ... (rest of the function) ...\n ```\n\n**Recommendation:**\n\nThe first approach (passing `molecule` as an argument) is generally preferred as it makes the dependencies of the function explicit and avoids potential issues with global variables.\n\n**With either of these modifications, the `molecule` variable should be accessible within the `expectation_value` function, resolving the `NameError`.**"] }, { "role": "user", "parts": ["add those to the code above make it woorkable"] }, { "role": "model", "parts": ["## Complete Code with Fixes (Illustrative Example)\n\nHere's the complete code with the fixes to address the `NameError` and make it a more workable example:\n\n```python\nimport cirq\nfrom openfermion import *\nfrom scipy.optimize import minimize\n\n# (1) Hamiltonian generation\nmolecule = MolecularData(geometry=[('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))],\n basis='sto-3g', multiplicity=1)\nmolecule.load()\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# (2) Ansatz Design (Example)\ndef ansatz(qubits, params):\n for i in range(len(qubits)):\n yield cirq.rx(params[2*i])(qubits[i])\n yield cirq.rz(params[2*i+1])(qubits[i])\n for i in range(len(qubits) - 1):\n yield cirq.CZ(qubits[i], qubits[i+1])\n\n# (3) Expectation Value (Assuming Jordan-Wigner and passing molecule)\ndef expectation_value(params, molecule):\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n circuit = cirq.Circuit(ansatz(qubits, params))\n simulator = cirq.Simulator()\n result = simulator.simulate(circuit)\n jw_hamiltonian = jordan_wigner(hamiltonian)\n expectation = jw_hamiltonian.expectation_from_state_vector(result.final_state_vector, qubits)\n return expectation.real\n\n# (4) Optimization Loop\ninitial_params = [0.0] * 2 * molecule.n_qubits\nresult = minimize(lambda params: expectation_value(params, molecule), initial_params)\noptimized_params = result.x\noptimized_energy = result.fun\n\nprint(\"Optimized Energy:\", optimized_energy)\n```\n\n**Explanation of Changes:**\n\n1. **`expectation_value` Function:**\n * The `molecule` is now passed as an argument to the `expectation_value` function.\n * Inside the function, the `molecule` argument is used to determine the number of qubits and construct the circuit.\n\n2. **Optimization Loop:**\n * A lambda function is used within the `minimize` function to pass the `molecule` argument to the `expectation_value` function during each evaluation.\n\n**Important Reminders:**\n\n* **Mapping:** This code assumes you have implemented or have access to a function named `jordan_wigner` that performs the Jordan-Wigner transformation. If you use a different mapping, adapt the code accordingly.\n* **Ansatz:** The provided Ansatz is a simple example. You'll likely need a more sophisticated design based on your problem.\n* **Simulation and Optimization:** Consider using different simulation methods and optimization algorithms depending on your specific requirements and computational resources. \n\n**This code should now be executable without the `NameError`. However, remember that it's an illustrative example, and you'll need to adapt and refine it based on your specific quantum chemistry problem and chosen techniques.**"] }, { "role": "user", "parts": ["---------------------------------------------------------------------------\nFileNotFoundError Traceback (most recent call last)\n<ipython-input-15-2547ad712f22> in <cell line: 8>()\n 6 molecule = MolecularData(geometry=[('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))],\n 7 basis='sto-3g', multiplicity=1)\n----> 8 molecule.load()\n 9 hamiltonian = molecule.get_molecular_hamiltonian()\n 10 \n\n2 frames/usr/local/lib/python3.10/dist-packages/h5py/_hl/files.py in make_fid(name, mode, userblock_size, fapl, fcpl, swmr)\n 229 if swmr and swmr_support:\n 230 flags |= h5f.ACC_SWMR_READ\n--> 231 fid = h5f.open(name, flags, fapl=fapl)\n 232 elif mode == 'r+':\n 233 fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)\n\nh5py/_objects.pyx in h5py._objects.with_phil.wrapper()\n\nh5py/_objects.pyx in h5py._objects.with_phil.wrapper()\n\nh5py/h5f.pyx in h5py.h5f.open()\n\nFileNotFoundError: [Errno 2] Unable to open file (unable to open file: name = '/usr/local/lib/python3.10/dist-packages/openfermion/testing/data/H2_sto-3g_singlet.hdf5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)"] }, { "role": "model", "parts": ["## Resolving the `FileNotFoundError`\n\nThe error message indicates that OpenFermion is unable to find the file `H2_sto-3g_singlet.hdf5`, which contains precomputed data for the H2 molecule with the STO-3G basis set. This file is typically included as part of the OpenFermion installation and used for testing purposes.\n\n**Possible Causes and Solutions:**\n\n1. **Incomplete OpenFermion Installation:**\n * **Reinstall OpenFermion:** Try reinstalling OpenFermion to ensure all necessary files, including testing data, are properly installed.\n\n ```bash\n pip uninstall openfermion\n pip install openfermion\n ```\n\n2. **Incorrect File Path:**\n * **Check File Location:** Verify that the file `H2_sto-3g_singlet.hdf5` exists in the expected location within the OpenFermion package directory. If it's missing or in a different location, you might need to manually place it in the correct directory or adjust the code to point to the correct path.\n\n3. **Permission Issues:** \n * **Check File Permissions:** Ensure that your Python environment has the necessary permissions to access the file. If you're working in a restricted environment, you might need to adjust file permissions or run the code with elevated privileges.\n\n**Alternative Approach (If precomputed data is unavailable):**\n\nIf you cannot resolve the file issue or prefer not to rely on precomputed data, you can generate the H2 molecular Hamiltonian from scratch using OpenFermion's capabilities:\n\n```python\nfrom openfermion.chem import MolecularData\nfrom openfermionpyscf import run_pyscf\n\n# Specify molecule and basis set\ngeometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))]\nbasis = 'sto-3g'\nmultiplicity = 1\n\n# Generate molecule and run PySCF calculation\nmolecule = MolecularData(geometry, basis, multiplicity)\nmolecule = run_pyscf(molecule, run_scf=1, run_mp2=0, run_cisd=0, run_ccsd=0, run_fci=0)\n\n# Get the Hamiltonian\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# ... (rest of the code) ... \n```\n\n**This approach uses PySCF within OpenFermion to perform an electronic structure calculation and generate the Hamiltonian directly, eliminating the need for the precomputed data file.**"] }, { "role": "user", "parts": ["add those code above"] }, { "role": "model", "parts": ["## Complete Code with Alternative Hamiltonian Generation\n\nHere's the complete code with the alternative approach to generate the H2 molecular Hamiltonian directly using PySCF within OpenFermion: \n\n```python\nimport cirq\nfrom openfermion import *\nfrom openfermionpyscf import run_pyscf\nfrom scipy.optimize import minimize\n\n# (1) Hamiltonian Generation (Using PySCF)\ngeometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))]\nbasis = 'sto-3g'\nmultiplicity = 1\nmolecule = MolecularData(geometry, basis, multiplicity)\nmolecule = run_pyscf(molecule, run_scf=1, run_mp2=0, run_cisd=0, run_ccsd=0, run_fci=0)\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# (2) Ansatz Design (Example) \ndef ansatz(qubits, params):\n # ... (your ansatz circuit design) ...\n\n# (3) Expectation Value (Assuming Jordan-Wigner and passing molecule)\ndef expectation_value(params, molecule):\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n circuit = cirq.Circuit(ansatz(qubits, params))\n simulator = cirq.Simulator()\n result = simulator.simulate(circuit)\n jw_hamiltonian = jordan_wigner(hamiltonian)\n expectation = jw_hamiltonian.expectation_from_state_vector(result.final_state_vector, qubits)\n return expectation.real\n\n# (4) Optimization Loop\ninitial_params = [0.0] * 2 * molecule.n_qubits # Adjust based on your ansatz parameters\nresult = minimize(lambda params: expectation_value(params, molecule), initial_params)\noptimized_params = result.x\noptimized_energy = result.fun\n\nprint(\"Optimized Energy:\", optimized_energy)\n```\n\n**Explanation of Changes:**\n\n1. **Hamiltonian Generation:**\n * The code now uses `openfermionpyscf` to run a PySCF calculation and generate the molecular Hamiltonian directly.\n * You'll need to have PySCF installed (`pip install pyscf`) for this approach to work. \n\n2. **Rest of the Code:**\n * The Ansatz design, expectation value calculation, and optimization loop remain conceptually the same, but ensure that the Ansatz parameterization and initial parameters in the optimization loop are consistent with your chosen Ansatz design. \n\n**With this modification, the code should generate the H2 Hamiltonian directly without relying on the precomputed data file. Remember to adapt the Ansatz design and optimization settings according to your specific problem.**"] }, { "role": "user", "parts": ["File \"<ipython-input-16-2ec6c3d908e2>\", line 19\n def expectation_value(params, molecule):\n ^\nIndentationError: expected an indented block after function definition on line 15"] }, { "role": "model", "parts": ["## Correcting the Indentation Error\n\nThe error message indicates a Python syntax error related to indentation. In Python, proper indentation is crucial for defining code blocks, such as the body of a function.\n\n**Solution:**\n\nEnsure that the code within the `expectation_value` function is indented. In Python, the standard indentation is four spaces. Here's the corrected code snippet:\n\n```python\ndef expectation_value(params, molecule):\n # Indent the code within the function (four spaces)\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n circuit = cirq.Circuit(ansatz(qubits, params))\n simulator = cirq.Simulator()\n result = simulator.simulate(circuit)\n jw_hamiltonian = jordan_wigner(hamiltonian)\n expectation = jw_hamiltonian.expectation_from_state_vector(result.final_state_vector, qubits)\n return expectation.real\n```\n\n**Explanation:**\n\n* The line `def expectation_value(params, molecule):` defines the function header.\n* Any code that belongs to the function's body must be indented below the header. This tells Python which lines of code are part of the function.\n\n**Additional Tips:**\n\n* **Consistent Indentation:** Use consistent indentation throughout your code (typically four spaces) to improve readability and avoid errors.\n* **Code Editors:** Most code editors and IDEs automatically handle indentation, making it easier to write syntactically correct Python code.\n* **Linters:** Consider using a linter or code formatter to automatically check and correct indentation issues.\n\n**With the corrected indentation, your code should run without syntax errors.**"] }, { "role": "user", "parts": ["add that code in the above"] }, { "role": "model", "parts": ["## Complete Code with Indentation Fix\n\nHere's the complete code with the indentation fix for the `expectation_value` function:\n\n```python\nimport cirq\nfrom openfermion import *\nfrom openfermionpyscf import run_pyscf\nfrom scipy.optimize import minimize\n\n# (1) Hamiltonian Generation (Using PySCF)\ngeometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))]\nbasis = 'sto-3g'\nmultiplicity = 1\nmolecule = MolecularData(geometry, basis, multiplicity)\nmolecule = run_pyscf(molecule, run_scf=1, run_mp2=0, run_cisd=0, run_ccsd=0, run_fci=0)\nhamiltonian = molecule.get_molecular_hamiltonian()\n\n# (2) Ansatz Design (Example) \ndef ansatz(qubits, params):\n # ... (your ansatz circuit design) ...\n\n# (3) Expectation Value (Assuming Jordan-Wigner and passing molecule)\ndef expectation_value(params, molecule):\n # Indented code within the function\n qubits = cirq.LineQubit.range(molecule.n_qubits)\n circuit = cirq.Circuit(ansatz(qubits, params))\n simulator = cirq.Simulator()\n result = simulator.simulate(circuit)\n jw_hamiltonian = jordan_wigner(hamiltonian)\n expectation = jw_hamiltonian.expectation_from_state_vector(result.final_state_vector, qubits)\n return expectation.real\n\n# (4) Optimization Loop\ninitial_params = [0.0] * 2 * molecule.n_qubits # Adjust based on your ansatz parameters\nresult = minimize(lambda params: expectation_value(params, molecule), initial_params)\noptimized_params = result.x\noptimized_energy = result.fun\n\nprint(\"Optimized Energy:\", optimized_energy)\n``` \n\n**The code should now run without the indentation error. Remember to fill in your desired Ansatz design and adjust the optimization settings as needed.**"] }, { "role": "user", "parts": ["create an algorithm for IBM quantum labs that go forward or in the future than the past"] }, { "role": "model", "parts": ["## Quantum Algorithm for Future-Focused Applications: A Conceptual Exploration \n\nDeveloping a specific quantum algorithm for \"going forward or in the future than the past\" is a highly abstract and philosophical concept. Quantum computers excel at specific tasks, and their ability to influence time or causality directly is not within their current capabilities or theoretical framework. \n\nHowever, we can explore potential quantum algorithms that might have implications for predicting or influencing future events within the bounds of scientific understanding and quantum mechanics. Here are a few conceptual directions:\n\n**1. Quantum Machine Learning for Prediction:**\n\n* **Concept:** Utilize quantum machine learning algorithms to analyze vast datasets and make predictions about future trends or events. Quantum algorithms like Quantum Support Vector Machines (QSVM) or Quantum Neural Networks (QNN) could potentially offer advantages in handling complex data and identifying patterns that classical algorithms might miss.\n* **Applications:** Financial forecasting, climate modeling, risk assessment, and other areas where predicting future outcomes is crucial. \n\n**2. Quantum Simulation for Complex Systems:**\n\n* **Concept:** Employ quantum computers to simulate the behavior of complex systems, such as financial markets, ecosystems, or social dynamics. By understanding the underlying rules governing these systems, we might gain insights into their future evolution and potential outcomes.\n* **Applications:** Economic modeling, environmental management, urban planning, and understanding complex phenomena where classical simulations are computationally intractable. \n\n**3. Quantum Optimization for Decision Making:**\n\n* **Concept:** Leverage quantum algorithms like Quantum Approximate Optimization Algorithm (QAOA) or Quantum Annealing to explore vast solution spaces and identify optimal decisions that maximize positive future outcomes. \n* **Applications:** Resource allocation, logistics planning, portfolio optimization, and scenarios where finding the best course of action with long-term consequences is essential. \n\n**4. Quantum Communication for Secure Information Exchange:**\n\n* **Concept:** Implement quantum key distribution (QKD) protocols to establish secure communication channels for exchanging sensitive information that might be critical for future planning and decision-making.\n* **Applications:** Secure financial transactions, confidential communications, and protecting critical infrastructure.\n\n**Important Considerations:**\n\n* **Quantum Advantage:** The practicality of these concepts relies on demonstrating a clear quantum advantage, meaning that quantum algorithms outperform classical methods for the specific task.\n* **Hardware Development:** The development of more powerful and stable quantum computers is crucial for tackling complex problems and realizing the potential of these algorithms.\n* **Ethical Implications:** As with any powerful technology, it's important to consider the ethical implications of using quantum algorithms for prediction and decision-making, ensuring responsible development and application.\n\n**While quantum computers cannot literally \"go forward in time,\" they offer unique capabilities for analyzing data, simulating complex systems, and exploring potential future scenarios, which could have significant implications for various fields and our understanding of the world.**"] }, { "role": "user", "parts": ["create an algorithm for qism and cirq that go forward or in the future than the past"] }, { "role": "model", "parts": ["## Qiskit & Cirq for Future-Oriented Applications: Conceptual Exploration\n\nSimilar to the previous response, creating a specific algorithm for \"going forward or in the future\" is not feasible within the current capabilities of quantum computing and our understanding of physics. However, we can explore potential directions for using Qiskit and Cirq in algorithms that have implications for predicting or influencing future events.\n\n**Potential Approaches:**\n\n**1. Quantum Machine Learning (QML) for Prediction:**\n\n* **Qiskit:**\n * Utilize Qiskit's machine learning module `qiskit.ml` and libraries like `qiskit_machine_learning` to implement and experiment with quantum machine learning algorithms.\n * Explore algorithms like QSVM, QNN, or quantum versions of classical ML techniques to analyze data and build predictive models for future trends.\n* **Cirq:**\n * Leverage Cirq's ability to design custom quantum circuits and integrate with classical machine learning libraries like TensorFlow Quantum (TFQ).\n * Explore hybrid quantum-classical approaches for training and utilizing quantum models for prediction.\n\n**2. Quantum Simulation for Complex Systems:**\n\n* **Qiskit:**\n * Use Qiskit's simulation capabilities and libraries like `qiskit_nature` to simulate complex systems relevant to your domain.\n * Develop quantum circuits that represent the dynamics of these systems and explore their behavior under different conditions.\n* **Cirq:**\n * Design custom quantum circuits using Cirq to represent the interactions and evolution of complex systems. \n * Utilize Cirq's simulation tools to study the behavior of these systems and gain insights into their future states.\n\n**3. Quantum Optimization for Decision Making:**\n\n* **Qiskit:**\n * Implement quantum optimization algorithms like QAOA or VQE using Qiskit's optimization module and relevant libraries.\n * Formulate decision-making problems as optimization tasks and use quantum algorithms to explore potential solutions with future implications.\n* **Cirq:**\n * Design quantum circuits representing optimization problems and use Cirq's optimization routines or integrate with classical optimization libraries.\n * Explore hybrid approaches where quantum circuits are used to evaluate potential solutions or provide speedups for specific parts of the optimization process.\n\n**Challenges and Considerations:**\n\n* **Quantum Advantage:** Demonstrating a clear quantum advantage for these applications is crucial to justify the use of quantum resources.\n* **Problem Formulation:** Effectively mapping real-world problems onto quantum representations suitable for Qiskit or Cirq requires careful consideration and domain expertise.\n* **Hardware Limitations:** Current quantum hardware has limitations in terms of qubit count, connectivity, and noise, which can impact the feasibility and performance of these algorithms.\n* **Hybrid Approaches:** Combining quantum and classical techniques is often beneficial to leverage the strengths of both paradigms.\n\n**It's important to note that these are conceptual directions, and the specific implementation details will vary depending on the chosen application and available resources. However, this exploration highlights the potential of Qiskit and Cirq in developing quantum algorithms with implications for understanding and influencing future outcomes.**"] }, { "role": "user", "parts": ["show the code"] }, { "role": "model", "parts": ["## Illustrative Code Snippets (Conceptual Examples)\n\nDue to the broad nature of \"future-oriented\" applications, providing a single, complete code example is not feasible. However, I can offer illustrative snippets for each of the conceptual approaches mentioned earlier. These snippets are meant to provide a starting point and would require significant adaptation and expansion based on your specific problem and chosen techniques.\n\n**1. Quantum Machine Learning (QML) for Prediction (Qiskit Example):**\n\n```python\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit.library import ZZFeatureMap\nfrom qiskit.ml.datasets import ad_hoc_data\nfrom qiskit.circuit.library import TwoLocal\nfrom qiskit.aqua import QuantumInstance\nfrom qiskit.aqua.algorithms import QSVM\n\n# Prepare data (example using ad hoc dataset)\nfeature_dim = 2\nsample_total, training_input, test_input, class_labels = ad_hoc_data(\n training_size=20, \n test_size=10, \n n=feature_dim, \n gap=0.3, \n plot_data=False\n)\n\n# Feature map and ansatz\nfeature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2)\nansatz = TwoLocal(feature_dim, ['ry', 'rz'], 'cz', reps=2)\n\n# QSVM setup\nqsvm = QSVM(feature_map, ansatz, training_input, test_input, class_labels)\n\n# Run QSVM (using a simulator backend)\nbackend = Aer.get_backend('qasm_simulator')\nquantum_instance = QuantumInstance(backend, shots=1024)\nresult = qsvm.run(quantum_instance)\n\n# Analyze results (example: prediction accuracy)\nprint(f'Testing accuracy: {result[\"testing_accuracy\"]}')\n```\n\n**2. Quantum Simulation for Complex Systems (Cirq Example):**\n\n```python\nimport cirq\n\n# Define qubits and Hamiltonian (replace with your system)\nqubits = cirq.LineQubit.range(4)\nhamiltonian = # Define the Hamiltonian of your system\n\n# Define simulation time steps and parameters\ntime_steps = 100\ntime_step_size = 0.01\n\n# Construct the simulation circuit\ncircuit = cirq.Circuit()\nfor step in range(time_steps):\n # Implement the Hamiltonian evolution for each time step\n circuit.append(cirq.PauliStringPhasor(hamiltonian, exponent=time_step_size))\n\n# Simulate the circuit\nsimulator = cirq.Simulator()\nresults = simulator.simulate(circuit, qubit_order=qubits)\n\n# Analyze the simulation results (e.g., expectation values of observables)\n# ...\n```\n\n**3. Quantum Optimization for Decision Making (Qiskit Example):**\n\n```python\nfrom qiskit.optimization.applications import Maxcut\nfrom qiskit.aqua.algorithms import QAOA\nfrom qiskit import Aer\n\n# Define a graph representing your decision problem (example: Maxcut)\ngraph = generate_butterfly_graph(with_weights=True)\nmax_cut = Maxcut(graph)\nqp = max_cut.to_quadratic_program()\n\n# QAOA parameters\np = 2 # Number of layers\noptimizer = COBYLA(maxiter=100)\n\n# QAOA setup\nqaoa = QAOA(optimizer, p=p, quantum_instance=Aer.get_backend('qasm_simulator'))\n\n# Run QAOA\nresult = qaoa.solve(qp)\n\n# Analyze the result (e.g., best solution and objective value)\nprint(result)\n```\n\n**These snippets provide a high-level overview of how Qiskit and Cirq can be used for future-oriented applications. Remember that significant modifications and domain-specific knowledge are required to adapt these examples to your particular problem.**\n\n**Important Considerations:**\n\n* **Problem-Specific Implementation:** Adapt the code based on your chosen quantum algorithm, application domain, and data representation.\n* **Hardware Access:** If you have access to real quantum hardware, modify the code to run on actual quantum processors instead of simulators.\n* **Optimization and Analysis:** Pay attention to optimization techniques and result analysis methods that are relevant to your application and chosen algorithm."] }, { "role": "user", "parts": ["give code to # Define the Hamiltonian of your system"] }, { "role": "model", "parts": ["## Defining Hamiltonians in Cirq: Examples \n\nThe way you define the Hamiltonian of your system in Cirq depends on the specific nature of the system and how you want to represent it using qubits and quantum gates. Here are some examples to illustrate different approaches: \n\n**1. Pauli Strings (Simple Example):**\n\nIf your Hamiltonian can be expressed as a sum of Pauli strings (tensor products of Pauli operators), you can directly create it using Cirq's `PauliString` class:\n\n```python\nimport cirq\n\n# Define qubits\nq0, q1 = cirq.LineQubit.range(2)\n\n# Example Hamiltonian: H = X⊗X + Z⊗I\nhamiltonian = cirq.PauliString(cirq.X(q0) * cirq.X(q1)) + cirq.PauliString(cirq.Z(q0))\n\n# Print the Hamiltonian terms\nprint(hamiltonian)\n```\n\n**2. Fermionic Hamiltonians (Using OpenFermion):**\n\nFor systems like molecules where the Hamiltonian is naturally expressed in terms of fermionic creation and annihilation operators, you can use OpenFermion to generate the Hamiltonian and then convert it to a qubit representation using mappings like Jordan-Wigner:\n\n```python\nfrom openfermion import *\nimport cirq\n\n# Generate molecular Hamiltonian (example using H2)\ngeometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))]\nbasis = 'sto-3g'\nmultiplicity = 1\nmolecule = MolecularData(geometry, basis, multiplicity)\nmolecule = run_pyscf(molecule, run_scf=1, run_mp2=0, run_cisd=0, run_ccsd=0, run_fci=0)\nfermionic_hamiltonian = molecule.get_molecular_hamiltonian()\n\n# Convert to qubit Hamiltonian using Jordan-Wigner transformation\nqubit_hamiltonian = jordan_wigner(fermionic_hamiltonian)\n\n# Print the terms of the qubit Hamiltonian\nprint(qubit_hamiltonian)\n```\n\n**3. Custom Hamiltonian Functions:**\n\nYou can also define a function that returns the Hamiltonian as a Cirq `PauliSum` object, allowing for more flexibility in constructing the Hamiltonian terms:\n\n```python\nimport cirq\n\ndef custom_hamiltonian(qubits):\n # Define your Hamiltonian terms using Cirq operations and qubits\n term1 = cirq.X(qubits[0]) * cirq.Y(qubits[1])\n term2 = cirq.Z(qubits[2]) * cirq.Z(qubits[3])\n # Return as a PauliSum\n return cirq.PauliSum([term1, term2])\n\n# Example usage\nqubits = cirq.LineQubit.range(4)\nhamiltonian = custom_hamiltonian(qubits)\n\nprint(hamiltonian)\n```\n\n**Important Considerations:**\n\n* **Mapping:** If you are working with fermionic Hamiltonians, choose an appropriate mapping method (e.g., Jordan-Wigner, Bravyi-Kitaev) to convert them to a qubit representation.\n* **Complexity:** For complex systems, the Hamiltonian might involve many terms, leading to challenges in circuit design and simulation.\n* **Problem-Specific Representation:** The best way to represent the Hamiltonian depends on the specific problem and the quantum algorithm you are using.\n\n**These examples provide a starting point for defining Hamiltonians in Cirq. Remember to adapt and expand upon these based on your specific system and requirements.**"] }, { "role": "user", "parts": ["import cirq# Define qubits and Hamiltonian (replace with your system)qubits = cirq.LineQubit.range(4)hamiltonian = # Define the Hamiltonian of your system# Define simulation time steps and parameterstime_steps = 100time_step_size = 0.01# Construct the simulation circuitcircuit = cirq.Circuit()for step in range(time_steps):    # Implement the Hamiltonian evolution for each time step    circuit.append(cirq.PauliStringPhasor(hamiltonian, exponent=time_step_size))# Simulate the circuitsimulator = cirq.Simulator()results = simulator.simulate(circuit, qubit_order=qubits)# Analyze the simulation results (e.g., expectation values of observables)# ... define the hamiltonian"] }, { "role": "model", "parts": ["## Defining the Hamiltonian within the Cirq Simulation Code\n\nHere's the code with an example of how to define the Hamiltonian within the Cirq simulation framework. We'll use a simple example of a Hamiltonian represented as a sum of Pauli strings:\n\n```python\nimport cirq\n\n# Define qubits\nqubits = cirq.LineQubit.range(4)\n\n# Example Hamiltonian: H = X⊗X + Z⊗I\nhamiltonian = cirq.PauliString(cirq.X(qubits[0]) * cirq.X(qubits[1])) + cirq.PauliString(cirq.Z(qubits[0]))\n\n# Define simulation time steps and parameters\ntime_steps = 100\ntime_step_size = 0.01\n\n# Construct the simulation circuit\ncircuit = cirq.Circuit()\nfor step in range(time_steps):\n # Implement the Hamiltonian evolution for each time step\n circuit.append(cirq.PauliStringPhasor(hamiltonian, exponent=time_step_size))\n\n# Simulate the circuit\nsimulator = cirq.Simulator()\nresults = simulator.simulate(circuit, qubit_order=qubits)\n\n# Analyze the simulation results (e.g., expectation values of observables)\n# ... (add your analysis code here)\n```\n\n**Explanation:**\n\n1. **Hamiltonian Definition:** We define the `hamiltonian` as a sum of two Pauli strings using Cirq's `PauliString` class. The first term represents an interaction between the first two qubits (X⊗X), and the second term represents a single-qubit Z operation on the first qubit (Z⊗I).\n\n2. **Simulation Loop:** The `for` loop iterates over the specified `time_steps`. In each step, it applies the `cirq.PauliStringPhasor` operation to the circuit. This operation simulates the evolution of the system under the given Hamiltonian for a small time step (`time_step_size`).\n\n3. **Simulation and Analysis:** The `cirq.Simulator` is used to simulate the circuit and obtain the results. You can then analyze the results by calculating expectation values of observables or studying other properties of the system's evolution.\n\n**Adapting the Hamiltonian:**\n\n* Replace the example Hamiltonian with your desired Hamiltonian, which could be a more complex combination of Pauli strings, a fermionic Hamiltonian mapped to qubits, or a custom-defined function that returns a `PauliSum` object.\n* Ensure that the number of qubits and the structure of the Hamiltonian are consistent with your problem. \n\n**Remember that this is a basic example. You'll need to modify and expand upon this framework depending on your specific system, chosen Hamiltonian, and simulation goals.**"] }, { "role": "user", "parts": ["add # Analyze the simulation results (e.g., expectation values of observables)\n# ... (add your analysis code here)"] }, { "role": "model", "parts": ["## Adding Analysis Code to the Cirq Simulation\n\nHere's the code with an example of how to analyze the simulation results by calculating the expectation values of observables:\n\n```python\nimport cirq\n\n# ... (Hamiltonian definition and simulation as before) ...\n\n# Analyze the simulation results\n# Example observables: X on qubit 0, Z on qubit 1, and X⊗X on qubits 0 and 1\nobservables = [cirq.X(qubits[0]), cirq.Z(qubits[1]), cirq.X(qubits[0]) * cirq.X(qubits[1])]\n\n# Calculate expectation values for each observable at each time step\nexpectation_values = []\nfor step, state_vector in enumerate(results.final_state_vector):\n step_expectations = []\n for observable in observables:\n expectation = cirq.PauliString(observable).expectation_from_state_vector(state_vector, qubits)\n step_expectations.append(expectation.real)\n expectation_values.append(step_expectations)\n\n# Print or plot the expectation values\n# ... (add code to visualize or analyze the results)\n```\n\n**Explanation:**\n\n1. **Observables Definition:** We define a list of observables that we want to measure. In this example, we choose to measure the X operator on qubit 0, the Z operator on qubit 1, and the X⊗X operator on qubits 0 and 1.\n\n2. **Expectation Value Calculation:** We loop through each time step and each observable. For each combination, we calculate the expectation value of the observable using the state vector at that time step.\n\n3. **Result Analysis:** The `expectation_values` list now contains the expectation values for each observable at each time step. You can further analyze these values by:\n * **Printing them:** Use `print` statements to display the values.\n * **Plotting:** Utilize libraries like Matplotlib or Plotly to visualize the evolution of expectation values over time.\n * **Further Calculations:** Perform additional calculations based on the expectation values, such as calculating correlation functions or other quantities of interest. \n\n**Adapting the Analysis:**\n\n* **Choose Observables:** Select observables that are relevant to your system and the properties you want to study.\n* **Visualization:** Implement appropriate visualization methods to understand the behavior of the expectation values over time.\n* **Advanced Analysis:** Perform more sophisticated analysis based on your specific research goals.\n\n**This example demonstrates a basic way to analyze the results of a Cirq simulation. Remember to adapt the code based on your chosen observables and analysis requirements.**"] }, { "role": "user", "parts": ["add # Print or plot the expectation values\n# ... (add code to visualize or analyze the results)"] }, { "role": "model", "parts": ["## Adding Visualization Code: Plotting Expectation Values\n\nHere's the code with an example of how to visualize the expectation values using Matplotlib:\n\n```python\nimport cirq\nimport matplotlib.pyplot as plt\n\n# ... (Hamiltonian definition, simulation, and expectation value calculation as before) ...\n\n# Plotting\ntime_array = [step * time_step_size for step in range(time_steps)] # Time values for x-axis\n\nplt.figure()\nlabels = [\"X0\", \"Z1\", \"X0X1\"] # Labels for each observable\nfor i, observable_expectations in enumerate(zip(*expectation_values)):\n plt.plot(time_array, observable_expectations, label=labels[i])\n\nplt.xlabel(\"Time\")\nplt.ylabel(\"Expectation Value\")\nplt.title(\"Evolution of Observables\")\nplt.legend()\nplt.show()\n```\n\n**Explanation:**\n\n1. **Import Matplotlib:** We import the `matplotlib.pyplot` module as `plt` for plotting. \n\n2. **Time Array:** We create a `time_array` to store the time values for the x-axis of the plot.\n\n3. **Plotting Loop:** \n * We use `zip(*expectation_values)` to transpose the `expectation_values` list so that we can iterate over the expectation values for each observable across all time steps.\n * For each observable, we plot its expectation values over time using `plt.plot()`. \n * We add labels for each observable using the `label` argument.\n\n4. **Plot Settings:** We set labels for the x and y axes, add a title, and display a legend to identify the different observables.\n\n5. **Show Plot:** `plt.show()` displays the plot. \n\n**Adapting the Visualization:**\n\n* **Plotting Library:** You can use other plotting libraries like Plotly or Seaborn for more advanced visualizations.\n* **Plot Customization:** Adjust plot settings like line styles, colors, markers, and gridlines as needed. \n* **Multiple Plots:** Create multiple plots to compare different observables or simulation results.\n\n**This example demonstrates a basic way to visualize the evolution of expectation values over time using Matplotlib. Remember to adapt the code based on your specific plotting preferences and analysis requirements.**"] }, { "role": "user", "parts": ["# Import necessary libraries\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.opflow import X, Z, I, StateFn, FermionicOp\nfrom qiskit.utils import QuantumInstance\nfrom qiskit.algorithms import VQE, NumPyMinimumEigensolver\nfrom qiskit.circuit.library import EfficientSU2\nfrom qiskit_nature.drivers import PySCFDriver\nfrom qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem\nfrom qiskit_nature.mappers.second_quantization import ParityMapper\n\n# Specify molecule and basis set\nmolecule = \"H .0 .0 -{0}; H .0 .0 {0}\"\ndriver = PySCFDriver(atom=molecule.format(0.7414), basis='sto3g')\n\n# Set up electronic structure problem\nproblem = ElectronicStructureProblem(driver)\nsecond_q_ops = problem.second_q_ops()\nmain_op = second_q_ops[0]\n\n# Choose fermionic to qubit mapping\nmapper = ParityMapper()\nqubit_op = mapper.map(main_op)\n\n# Define ansatz \nansatz = EfficientSU2(num_qubits=qubit_op.num_qubits, entanglement='linear') \n\n# Set up VQE\nbackend = Aer.get_backend('statevector_simulator')\nquantum_instance = QuantumInstance(backend)\noptimizer = 'COBYLA' \n\n# Define the VQE algorithm\nvqe = VQE(ansatz, optimizer, quantum_instance=quantum_instance)\n\n# Run VQE and get the result\nresult = vqe.compute_minimum_eigenvalue(operator=qubit_op)\n\n# Print the ground state energy\nprint(\"Ground state energy:\", result.eigenvalue.real)\nadd\n# Further analysis and calculations ..."] }, { "role": "model", "parts": ["## Expanding \"Further Analysis and Calculations\"\n\nThe specific analysis and calculations you perform after obtaining the ground state energy using VQE will depend on your research goals and the properties of the molecule you are interested in. Here are some potential directions you could explore:\n\n**1. Molecular Properties:**\n\n* **Bond Length:** Calculate the expectation value of the bond length operator to determine the equilibrium bond length of the molecule. \n* **Vibrational Frequencies:** Compute the vibrational frequencies of the molecule to understand its vibrational modes and infrared spectrum.\n* **Dipole Moment:** Calculate the dipole moment to understand the molecule's polarity and interactions with electric fields.\n\n**2. Excited States:**\n\n* **Excited State Energies:** Modify the VQE algorithm or use other quantum algorithms to find the energies of excited electronic states. \n* **Electronic Transitions:** Analyze the energy differences between electronic states to understand possible electronic transitions and the molecule's absorption/emission spectrum. \n\n**3. Potential Energy Surface:**\n\n* **Varying Bond Length:** Run VQE calculations for different bond lengths to map out the potential energy surface of the molecule. \n* **Reaction Pathways:** Explore how the potential energy surface changes as the molecule undergoes a chemical reaction. \n\n**4. Comparison with Classical Methods:**\n\n* **Classical Electronic Structure Calculations:** Compare the VQE results with classical electronic structure methods like Hartree-Fock or Density Functional Theory to assess the accuracy and efficiency of the quantum approach.\n\n**5. Advanced Quantum Algorithms:**\n\n* **Quantum Phase Estimation (QPE):** Use QPE to obtain more precise energy eigenvalues.\n* **Quantum Eigensolver (QE):** Explore the use of QE for finding both ground and excited state energies.\n\n**Example Code Snippet (Bond Length Calculation):**\n\n```python\n# Assuming you have defined the bond length operator as 'bond_length_op'\nbond_length_expectation = bond_length_op.evaluate(result.eigenstate)\nprint(\"Expected Bond Length:\", bond_length_expectation.real) \n```\n\n**Implementation Details:**\n\n* **Operators:** You'll need to define the appropriate operators (e.g., bond length, dipole moment) using Qiskit's operators or by converting them from fermionic representations. \n* **Algorithms:** Choose or adapt quantum algorithms suitable for calculating the desired properties.\n* **Analysis Tools:** Utilize libraries like NumPy, SciPy, and Matplotlib for data analysis and visualization. \n\n**Remember that these are just a few examples. The specific analysis and calculations you choose will depend on your interests and the molecule you are studying. Explore the rich possibilities offered by quantum algorithms and computational chemistry to gain deeper insights into molecular systems!**"] }, { "role": "user", "parts": ["Traceback (most recent call last):\n Cell In[2], line 1\n from qiskit.optimization.applications import Maxcut\nModuleNotFoundError: No module named 'qiskit.optimization'\n\nUse %tb to get the full traceback."] }, { "role": "model", "parts": ["## Resolving `ModuleNotFoundError: qiskit.optimization` \n\nThe error message indicates that the `qiskit.optimization` module is missing from your current Python environment. This module is part of the `qiskit-optimization` package, which provides tools for formulating and solving optimization problems using Qiskit.\n\n**Solution:**\n\n1. **Install `qiskit-optimization`:**\n\n Use pip to install the `qiskit-optimization` package:\n\n ```bash\n pip install qiskit-optimization\n ```\n\n2. **Verify Installation:**\n\n After installation, try importing the module again:\n\n ```python\n from qiskit.optimization.applications import Maxcut\n ```\n\n If this doesn't raise an error, the installation was successful.\n\n**Additional Considerations:**\n\n* **Virtual Environments:** It's recommended to use virtual environments to manage your project's dependencies and avoid conflicts between different Qiskit versions or packages. Ensure you have activated your virtual environment before installing `qiskit-optimization`.\n\n* **Dependencies:** `qiskit-optimization` has several dependencies, including NumPy, SciPy, and docplex. The `pip install` command should automatically install these dependencies. However, if you encounter issues, you might need to install them manually.\n\n* **Installation Issues:** If you face any problems during installation, refer to the Qiskit documentation or online resources for troubleshooting tips. \n\n**Once `qiskit-optimization` is installed, you should be able to use the `Maxcut` application and other optimization-related functionalities within Qiskit.**"] }, { "role": "user", "parts": ["No module named 'qiskit.ml"] }, { "role": "model", "parts": ["## Resolving `ModuleNotFoundError: qiskit.ml`\n\nThe error message indicates that the `qiskit.ml` module is not found in your current Python environment. This module was part of older versions of Qiskit and has been moved to a separate package in newer versions. \n\n**Solution:**\n\n1. **Install `qiskit_machine_learning`:**\n\n The machine learning functionalities of Qiskit are now available in the `qiskit_machine_learning` package. Install it using pip:\n\n ```bash\n pip install qiskit-machine-learning\n ```\n\n2. **Update Import Statements:**\n\n If your code was using import statements like `from qiskit.ml import ...`, you'll need to update them to use the new package:\n\n ```python\n from qiskit_machine_learning.algorithms import QSVM # Example\n # ... other imports ...\n ```\n\n**Additional Considerations:**\n\n* **Version Compatibility:** Ensure that the version of `qiskit_machine_learning` you install is compatible with your Qiskit version. \n* **Documentation:** Refer to the `qiskit_machine_learning` documentation for updated usage instructions and available algorithms. \n\n**With `qiskit_machine_learning` installed and import statements updated, you should be able to use the Qiskit machine learning functionalities in your code.**"] }, ]) convo.send_message("YOUR_USER_INPUT") print(convo.last.text)
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Scheduling/PadDelay passes""" import unittest from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.circuit import Measure from qiskit.circuit.library import CXGate, HGate from qiskit.pulse import Schedule, Play, Constant, DriveChannel from qiskit.test import QiskitTestCase from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes import ( ASAPScheduleAnalysis, ALAPScheduleAnalysis, PadDelay, SetIOLatency, ) from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.target import Target, InstructionProperties @ddt class TestSchedulingAndPaddingPass(QiskitTestCase): """Tests the Scheduling passes""" def test_alap_agree_with_reverse_asap_reverse(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() durations = InstructionDurations( [("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) alap_qc = pm.run(qc) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) def test_alap_agree_with_reverse_asap_with_target(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() target = Target(num_qubits=2, dt=3.5555555555555554) target.add_instruction(HGate(), {(0,): InstructionProperties(duration=200)}) target.add_instruction(CXGate(), {(0, 1): InstructionProperties(duration=700)}) target.add_instruction( Measure(), { (0,): InstructionProperties(duration=1000), (1,): InstructionProperties(duration=1000), }, ) pm = PassManager([ALAPScheduleAnalysis(target=target), PadDelay()]) alap_qc = pm.run(qc) pm = PassManager([ASAPScheduleAnalysis(target=target), PadDelay()]) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_classically_controlled_gate_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌─┐ q_0: ┤M├─────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├─── ║ └─╥─┘ ║ ┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞ 0 └─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├ ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├─────── └─────────────────┘ ║ └─╥─┘ ║ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════ 0 └─────────┘ """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) # x.c_if starts after measure expected.x(1).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── └───┘└╥┘┌─┐ q_1: ──────╫─┤M├ ║ └╥┘ c: 1/══════╩══╩═ 0 0 (scheduled) ┌───┐ ┌─┐┌─────────────────┐ q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├ ┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘ q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩══════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.x(0) expected.measure(0, 0) expected.delay(1200, 1) expected.measure(1, 0) expected.delay(1000, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_c_if_on_different_qubits(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits. (input) ┌─┐ q_0: ┤M├────────────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────────────── ║ └─╥─┘ ┌───┐ q_2: ─╫──────╫────────┤ X ├─── ║ ║ └─╥─┘ ║ ┌────╨────┐┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞ 0 └─────────┘└─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────── ├─────────────────┤ ║ └─╥─┘ ┌───┐ q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├─── └─────────────────┘ ║ ║ └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ 0 └─────────┘ └─────────┘ """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) qc.x(2).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.delay(1000, 2) expected.x(1).c_if(0, True) expected.x(2).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_shorter_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit. (input) ┌─┐ q_0: ┤M├─── └╥┘┌─┐ q_1: ─╫─┤M├ ║ └╥┘ c: 1/═╩══╩═ 0 0 (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(700[dt]) ├ ┌─────────────────┐└╥┘└──────┬─┬───────┘ q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩═════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.measure(1, 0) expected.delay(700, 0) self.assertEqual(expected, scheduled) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_measure_after_c_if(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (scheduled) ┌─┐┌─────────────────┐ q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├────────────────── ┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐ q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├ ├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘ q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├──────── └─────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager([schedule_pass(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.delay(1000, 1) expected.delay(1000, 2) expected.measure(0, 0) expected.x(1).c_if(0, 1) expected.measure(2, 0) expected.delay(1000, 0) expected.delay(800, 1) self.assertEqual(expected, scheduled) def test_parallel_gate_different_length(self): """Test circuit having two parallel instruction with different length. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├ └─────┬───┬──────┘└┬─┬┘└╥┘ q_1: ──────┤ X ├────────┤M├──╫─ └───┘ └╥┘ ║ c: 2/════════════════════╩═══╩═ 1 0 (expected, ASAP) ┌───┐┌─┐┌────────────────┐ q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├ ├───┤└╥┘└──────┬─┬───────┘ q_1: ┤ X ├─╫────────┤M├──────── └───┘ ║ └╥┘ c: 2/══════╩═════════╩═════════ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.x(1) asap_expected.measure(0, 0) # immediately start after X gate asap_expected.measure(1, 1) asap_expected.delay(200, 0) self.assertEqual(qc_asap, asap_expected) def test_parallel_gate_different_length_with_barrier(self): """Test circuit having two parallel instruction with different length with barrier. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐ ░ ┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├─── └─────┬───┬──────┘└───┘ ░ └╥┘┌─┐ q_1: ──────┤ X ├─────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 (expected, ASAP) ┌───┐┌────────────────┐ ░ ┌─┐ q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├─── ├───┤└────────────────┘ ░ └╥┘┌─┐ q_1: ┤ X ├───────────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.barrier() qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()]) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.barrier() alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.delay(200, 0) asap_expected.x(1) asap_expected.barrier() asap_expected.measure(0, 0) asap_expected.measure(1, 1) self.assertEqual(qc_asap, asap_expected) def test_measure_after_c_if_on_edge_locking(self): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. The scheduler is configured to reproduce behavior of the 0.20.0, in which clbit lock is applied to the end-edge of measure instruction. See https://github.com/Qiskit/qiskit-terra/pull/7655 (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (ASAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────────────── └─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐ q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├ ║ ┌────╨────┐ └╥┘└────────────────┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════ 0 └─────────┘ 0 (ALAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) # lock at the end edge actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=1000), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=1000), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) # start times of 2nd measure depends on ASAP/ALAP expected_asap = QuantumCircuit(3, 1) expected_asap.measure(0, 0) expected_asap.delay(1000, 1) expected_asap.x(1).c_if(0, 1) expected_asap.measure(2, 0) expected_asap.delay(200, 0) expected_asap.delay(200, 2) self.assertEqual(expected_asap, actual_asap) expected_alap = QuantumCircuit(3, 1) expected_alap.measure(0, 0) expected_alap.delay(1000, 1) expected_alap.x(1).c_if(0, 1) expected_alap.delay(200, 2) expected_alap.measure(2, 0) expected_alap.delay(200, 0) self.assertEqual(expected_alap, actual_alap) @data([100, 200], [500, 0], [1000, 200]) @unpack def test_active_reset_circuit(self, write_lat, cond_lat): """Test practical example of reset circuit. Because of the stimulus pulse overlap with the previous XGate on the q register, measure instruction is always triggered after XGate regardless of write latency. Thus only conditional latency matters in the scheduling. (input) ┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐ q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├─── └╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘ ║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐ c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞ 0 └─────────┘ 0 └─────────┘ 0 └─────────┘ """ qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)]) actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=write_lat, conditional_latency=cond_lat), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) expected = QuantumCircuit(1, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) self.assertEqual(expected, actual_asap) self.assertEqual(expected, actual_alap) def test_random_complicated_circuit(self): """Test scheduling complicated circuit with control flow. (input) ┌────────────────┐ ┌───┐ ░ ┌───┐ » q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───» └────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ » q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────» ║ ░ ┌─┐ └─╥─┘ ║ » q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────» ┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐» c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞» └─────────┘ 0 └─────────┘└─────────┘» « ┌────────────────┐┌───┐ «q_0: ┤ Delay(300[dt]) ├┤ X ├─────■───── « └────────────────┘└───┘ ┌─┴─┐ «q_1: ────────■─────────────────┤ X ├─── « ┌─┴─┐ ┌─┐ └─╥─┘ «q_2: ──────┤ X ├────────┤M├──────╫───── « └───┘ └╥┘ ┌────╨────┐ «c: 1/════════════════════╩══╡ c_0=0x0 ╞ « 0 └─────────┘ (ASAP scheduled) duration = 2800 dt ┌────────────────┐ ┌───┐ ░ ┌─────────────────┐ » q_0: ┤ Delay(200[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├───────────» ├────────────────┤ └─╥─┘ ░ ├─────────────────┤ ┌───┐ » q_1: ┤ Delay(300[dt]) ├─────╫──────░─┤ Delay(1200[dt]) ├───┤ X ├───» ├────────────────┤ ║ ░ └───────┬─┬───────┘ └─╥─┘ » q_2: ┤ Delay(300[dt]) ├─────╫──────░─────────┤M├─────────────╫─────» └────────────────┘┌────╨────┐ ░ └╥┘ ┌────╨────┐» c: 1/══════════════════╡ c_0=0x1 ╞════════════╩═════════╡ c_0=0x0 ╞» └─────────┘ 0 └─────────┘» « ┌───┐ ┌────────────────┐ ┌───┐ » «q_0: ─────────────────────┤ X ├───┤ Delay(300[dt]) ├──────┤ X ├───────» « └─╥─┘ └────────────────┘┌─────┴───┴──────┐» «q_1: ───────────────────────╫─────────────■─────────┤ Delay(400[dt]) ├» « ┌────────────────┐ ║ ┌─┴─┐ ├────────────────┤» «q_2: ┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────┤ Delay(300[dt]) ├» « └────────────────┘┌────╨────┐ └───┘ └────────────────┘» «c: 1/══════════════════╡ c_0=0x0 ╞════════════════════════════════════» « └─────────┘ » « ┌────────────────┐ «q_0: ─────■─────┤ Delay(700[dt]) ├ « ┌─┴─┐ ├────────────────┤ «q_1: ───┤ X ├───┤ Delay(700[dt]) ├ « └─╥─┘ └──────┬─┬───────┘ «q_2: ─────╫────────────┤M├──────── « ┌────╨────┐ └╥┘ «c: 1/╡ c_0=0x0 ╞════════╩═════════ « └─────────┘ 0 (ALAP scheduled) duration = 3100 ┌────────────────┐ ┌───┐ ░ ┌─────────────────┐ » q_0: ┤ Delay(200[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├───────────» ├────────────────┤ └─╥─┘ ░ ├─────────────────┤ ┌───┐ » q_1: ┤ Delay(300[dt]) ├─────╫──────░─┤ Delay(1200[dt]) ├───┤ X ├───» ├────────────────┤ ║ ░ └───────┬─┬───────┘ └─╥─┘ » q_2: ┤ Delay(300[dt]) ├─────╫──────░─────────┤M├─────────────╫─────» └────────────────┘┌────╨────┐ ░ └╥┘ ┌────╨────┐» c: 1/══════════════════╡ c_0=0x1 ╞════════════╩═════════╡ c_0=0x0 ╞» └─────────┘ 0 └─────────┘» « ┌───┐ ┌────────────────┐ ┌───┐ » «q_0: ─────────────────────┤ X ├───┤ Delay(300[dt]) ├──────┤ X ├───────» « ┌────────────────┐ └─╥─┘ └────────────────┘┌─────┴───┴──────┐» «q_1: ┤ Delay(300[dt]) ├─────╫─────────────■─────────┤ Delay(100[dt]) ├» « ├────────────────┤ ║ ┌─┴─┐ └──────┬─┬───────┘» «q_2: ┤ Delay(600[dt]) ├─────╫───────────┤ X ├──────────────┤M├────────» « └────────────────┘┌────╨────┐ └───┘ └╥┘ » «c: 1/══════════════════╡ c_0=0x0 ╞══════════════════════════╩═════════» « └─────────┘ 0 » « ┌────────────────┐ «q_0: ─────■─────┤ Delay(700[dt]) ├ « ┌─┴─┐ ├────────────────┤ «q_1: ───┤ X ├───┤ Delay(700[dt]) ├ « └─╥─┘ └────────────────┘ «q_2: ─────╫─────────────────────── « ┌────╨────┐ «c: 1/╡ c_0=0x0 ╞══════════════════ « └─────────┘ """ qc = QuantumCircuit(3, 1) qc.delay(100, 0) qc.x(0).c_if(0, 1) qc.barrier() qc.measure(2, 0) qc.x(1).c_if(0, 0) qc.x(0).c_if(0, 0) qc.delay(300, 0) qc.cx(1, 2) qc.x(0) qc.cx(0, 1).c_if(0, 0) qc.measure(2, 0) durations = InstructionDurations( [("x", None, 100), ("measure", None, 1000), ("cx", None, 200)] ) actual_asap = PassManager( [ SetIOLatency(clbit_write_latency=100, conditional_latency=200), ASAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) actual_alap = PassManager( [ SetIOLatency(clbit_write_latency=100, conditional_latency=200), ALAPScheduleAnalysis(durations), PadDelay(), ] ).run(qc) expected_asap = QuantumCircuit(3, 1) expected_asap.delay(200, 0) # due to conditional latency of 200dt expected_asap.delay(300, 1) expected_asap.delay(300, 2) expected_asap.x(0).c_if(0, 1) expected_asap.barrier() expected_asap.delay(1400, 0) expected_asap.delay(1200, 1) expected_asap.measure(2, 0) expected_asap.x(1).c_if(0, 0) expected_asap.x(0).c_if(0, 0) expected_asap.delay(300, 0) expected_asap.x(0) expected_asap.delay(300, 2) expected_asap.cx(1, 2) expected_asap.delay(400, 1) expected_asap.cx(0, 1).c_if(0, 0) expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0) expected_asap.delay( 700, 1 ) # no creg write until 100dt. thus measure can move left by 300dt. expected_asap.delay(300, 2) expected_asap.measure(2, 0) self.assertEqual(expected_asap, actual_asap) self.assertEqual(actual_asap.duration, 3100) expected_alap = QuantumCircuit(3, 1) expected_alap.delay(200, 0) # due to conditional latency of 200dt expected_alap.delay(300, 1) expected_alap.delay(300, 2) expected_alap.x(0).c_if(0, 1) expected_alap.barrier() expected_alap.delay(1400, 0) expected_alap.delay(1200, 1) expected_alap.measure(2, 0) expected_alap.x(1).c_if(0, 0) expected_alap.x(0).c_if(0, 0) expected_alap.delay(300, 0) expected_alap.x(0) expected_alap.delay(300, 1) expected_alap.delay(600, 2) expected_alap.cx(1, 2) expected_alap.delay(100, 1) expected_alap.cx(0, 1).c_if(0, 0) expected_alap.measure(2, 0) expected_alap.delay(700, 0) expected_alap.delay(700, 1) self.assertEqual(expected_alap, actual_alap) self.assertEqual(actual_alap.duration, 3100) def test_dag_introduces_extra_dependency_between_conditionals(self): """Test dependency between conditional operations in the scheduling. In the below example circuit, the conditional x on q1 could start at time 0, however it must be scheduled after the conditional x on q0 in ASAP scheduling. That is because circuit model used in the transpiler passes (DAGCircuit) interprets instructions acting on common clbits must be run in the order given by the original circuit (QuantumCircuit). (input) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├─── └─────┬───┬──────┘ └─╥─┘ q_1: ──────┤ X ├────────────╫───── └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ └─────────┘ └─────────┘ (ASAP scheduled) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├────────────── ├────────────────┤ └─╥─┘ ┌───┐ q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├─── └────────────────┘ ║ └─╥─┘ ┌────╨────┐┌────╨────┐ c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞ └─────────┘└─────────┘ """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(0).c_if(0, True) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 160)]) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.delay(100, 0) expected.delay(100, 1) # due to extra dependency on clbits expected.x(0).c_if(0, True) expected.x(1).c_if(0, True) self.assertEqual(expected, scheduled) def test_scheduling_with_calibration(self): """Test if calibrated instruction can update node duration.""" qc = QuantumCircuit(2) qc.x(0) qc.cx(0, 1) qc.x(1) qc.cx(0, 1) xsched = Schedule(Play(Constant(300, 0.1), DriveChannel(0))) qc.add_calibration("x", (0,), xsched) durations = InstructionDurations([("x", None, 160), ("cx", None, 600)]) pm = PassManager([ASAPScheduleAnalysis(durations), PadDelay()]) scheduled = pm.run(qc) expected = QuantumCircuit(2) expected.x(0) expected.delay(300, 1) expected.cx(0, 1) expected.x(1) expected.delay(160, 0) expected.cx(0, 1) expected.add_calibration("x", (0,), xsched) self.assertEqual(expected, scheduled) def test_padding_not_working_without_scheduling(self): """Test padding fails when un-scheduled DAG is input.""" qc = QuantumCircuit(1, 1) qc.delay(100, 0) qc.x(0) qc.measure(0, 0) with self.assertRaises(TranspilerError): PassManager(PadDelay()).run(qc) def test_no_pad_very_end_of_circuit(self): """Test padding option that inserts no delay at the very end of circuit. This circuit will be unchanged after ASAP-schedule/padding. ┌────────────────┐┌─┐ q_0: ┤ Delay(100[dt]) ├┤M├ └─────┬───┬──────┘└╥┘ q_1: ──────┤ X ├────────╫─ └───┘ ║ c: 1/═══════════════════╩═ 0 """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(1) qc.measure(0, 0) durations = InstructionDurations([("x", None, 160), ("measure", None, 1000)]) scheduled = PassManager( [ ASAPScheduleAnalysis(durations), PadDelay(fill_very_end=False), ] ).run(qc) self.assertEqual(scheduled, qc) @data(ALAPScheduleAnalysis, ASAPScheduleAnalysis) def test_respect_target_instruction_constraints(self, schedule_pass): """Test if DD pass does not pad delays for qubits that do not support delay instructions. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ qc = QuantumCircuit(3) qc.cx(1, 2) target = Target(dt=1) target.add_instruction(CXGate(), {(1, 2): InstructionProperties(duration=1000)}) # delays are not supported pm = PassManager([schedule_pass(target=target), PadDelay(target=target)]) scheduled = pm.run(qc) self.assertEqual(qc, scheduled) if __name__ == "__main__": unittest.main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the pulse Schedule transforms.""" import unittest from typing import List, Set import numpy as np from qiskit import pulse from qiskit.pulse import ( Play, Delay, Acquire, Schedule, Waveform, Drag, Gaussian, GaussianSquare, Constant, ) from qiskit.pulse import transforms, instructions from qiskit.pulse.channels import ( MemorySlot, DriveChannel, AcquireChannel, RegisterSlot, SnapshotChannel, ) from qiskit.pulse.instructions import directives from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q class TestAlignMeasures(QiskitTestCase): """Test the helper function which aligns acquires.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.inst_map = self.backend.defaults().instruction_schedule_map self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) def test_align_measures(self): """Test that one acquire is delayed to match the time of the later acquire.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(11, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) aligned = transforms.align_measures([sched])[0] self.assertEqual(aligned.name, "fake_experiment") ref = pulse.Schedule(name="fake_experiment") ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(19, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) aligned = transforms.align_measures([sched], self.inst_map, align_time=20)[0] ref = pulse.Schedule(name="fake_experiment") ref.insert(10, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(29, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(30, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) def test_align_post_u3(self): """Test that acquires are scheduled no sooner than the duration of the longest X gate.""" sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = transforms.align_measures([sched], self.inst_map)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 4) sched = transforms.align_measures([sched], self.inst_map, max_calibration_duration=10)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 10) def test_multi_acquire(self): """Test that the last acquire is aligned to if multiple acquires occur on the same channel.""" sched = pulse.Schedule() sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(4, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map) ref = pulse.Schedule() ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(26, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(aligned[0], ref) def test_multiple_acquires(self): """Test that multiple acquires are also aligned.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref = pulse.Schedule() ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(15, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map)[0] self.assertEqual(aligned, ref) def test_align_across_schedules(self): """Test that acquires are aligned together across multiple schedules.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(3, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], self.inst_map) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) def test_align_all(self): """Test alignment of all instructions in a schedule.""" sched0 = pulse.Schedule() sched0.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched0.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched1 = pulse.Schedule() sched1.insert(25, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched1.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_aligned = transforms.align_measures([sched0, sched1], self.inst_map, align_all=True) ref1_aligned = pulse.Schedule() ref1_aligned.insert(15, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(all_aligned[0], ref1_aligned) self.assertEqual(all_aligned[1], sched1) ref1_not_aligned = pulse.Schedule() ref1_not_aligned.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_not_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_not_aligned = transforms.align_measures( [sched0, sched1], self.inst_map, align_all=False, ) self.assertEqual(all_not_aligned[0], ref1_not_aligned) self.assertEqual(all_not_aligned[1], sched1) def test_measurement_at_zero(self): """Test that acquire at t=0 works.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(0, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], max_calibration_duration=0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) class TestAddImplicitAcquires(QiskitTestCase): """Test the helper function which makes implicit acquires explicit.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(1), MemorySlot(1))) self.sched = sched def test_add_implicit(self): """Test that implicit acquires are made explicit according to the meas map.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 1]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1}) def test_add_across_meas_map_sublists(self): """Test that implicit acquires in separate meas map sublists are all added.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_dont_add_all(self): """Test that acquires aren't added if no qubits in the sublist aren't being acquired.""" sched = transforms.add_implicit_acquires(self.sched, [[4, 5], [0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_multiple_acquires(self): """Test for multiple acquires.""" sched = pulse.Schedule() acq_q0 = pulse.Acquire(1200, AcquireChannel(0), MemorySlot(0)) sched += acq_q0 sched += acq_q0 << sched.duration sched = transforms.add_implicit_acquires(sched, meas_map=[[0]]) self.assertEqual(sched.instructions, ((0, acq_q0), (2400, acq_q0))) class TestPad(QiskitTestCase): """Test padding of schedule with delays.""" def test_padding_empty_schedule(self): """Test padding of empty schedule.""" self.assertEqual(pulse.Schedule(), transforms.pad(pulse.Schedule())) def test_padding_schedule(self): """Test padding schedule.""" delay = 10 sched = ( Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_schedule_inverse_order(self): """Test padding schedule is insensitive to order in which commands were added. This test is the same as `test_adding_schedule` but the order by channel in which commands were added to the schedule to be padded has been reversed. """ delay = 10 sched = ( Delay(delay, DriveChannel(1)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_until_less(self): """Test padding until time that is less than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(5, DriveChannel(1)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_until_greater(self): """Test padding until time that is greater than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(30, DriveChannel(0)).shift(20) | Delay(40, DriveChannel(1)).shift(10) # pylint: disable=unsupported-binary-operation ) self.assertEqual(transforms.pad(sched, until=50), ref_sched) def test_padding_supplied_channels(self): """Test padding of only specified channels.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(2 * delay, DriveChannel(2)) channels = [DriveChannel(0), DriveChannel(2)] self.assertEqual(transforms.pad(sched, channels=channels), ref_sched) def test_padding_less_than_sched_duration(self): """Test that the until arg is respected even for less than the input schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)).shift(20) ref_sched = sched | pulse.Delay(5, DriveChannel(0)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_prepended_delay(self): """Test that there is delay before the first instruction.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)) ref_sched = ( Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) ) self.assertEqual(transforms.pad(sched, until=30, inplace=True), ref_sched) def test_pad_no_delay_on_classical_io_channels(self): """Test padding does not apply to classical IO channels.""" delay = 10 sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) ref_sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def get_pulse_ids(schedules: List[Schedule]) -> Set[int]: """Returns ids of pulses used in Schedules.""" ids = set() for schedule in schedules: for _, inst in schedule.instructions: ids.add(inst.pulse.id) return ids class TestCompressTransform(QiskitTestCase): """Compress function test.""" def test_with_duplicates(self): """Test compression of schedule.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 2) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_sample_pulse_with_clipping(self): """Test sample pulses with clipping.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 1.001], epsilon=1e-3), drive_channel) schedule += Play(Waveform([0.0, 1.0000000001]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 3) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_no_duplicates(self): """Test with no pulse duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 0.9]), drive_channel) schedule += Play(Waveform([0.0, 0.3]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_parametric_pulses_with_duplicates(self): """Test with parametric pulses.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 8) self.assertEqual(len(compressed_pulse_ids), 4) def test_parametric_pulses_with_no_duplicates(self): """Test parametric pulses with no duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.19, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.3), drive_channel) schedule += Play(Constant(duration=150, amp=0.51, angle=0.3), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.5, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.51, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_with_different_channels(self): """Test with different channels.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_sample_pulses_with_tolerance(self): """Test sample pulses with tolerance.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_multiple_schedules(self): """Test multiple schedules.""" schedules = [] for _ in range(2): schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.2]), drive_channel) schedules.append(schedule) compressed_schedule = transforms.compress_pulses(schedules) original_pulse_ids = get_pulse_ids(schedules) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 6) self.assertEqual(len(compressed_pulse_ids), 2) class TestAlignSequential(QiskitTestCase): """Test sequential alignment transform.""" def test_align_sequential(self): """Test sequential alignment without a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) self.assertEqual(schedule, reference) def test_align_sequential_with_barrier(self): """Test sequential alignment with a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, directives.RelativeBarrier(d0, d1), inplace=True) reference.insert(3, instructions.Delay(5, d1), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) self.assertEqual(schedule, reference) class TestAlignLeft(QiskitTestCase): """Test left alignment transform.""" def test_align_left(self): """Test left alignment without a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_left_with_barrier(self): """Test left alignment with a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference = reference.insert(3, instructions.Delay(5, d1)) # d2 reference = reference.insert(3, instructions.Delay(11, d2)) self.assertEqual(schedule, reference) class TestAlignRight(QiskitTestCase): """Test right alignment transform.""" def test_align_right(self): """Test right alignment without a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(1, instructions.Delay(3, d0), inplace=True) reference.insert(4, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(6, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_right_with_barrier(self): """Test right alignment with a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(7, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(9, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) class TestAlignEquispaced(QiskitTestCase): """Test equispaced alignment transform.""" def test_equispaced_with_short_duration(self): """Test equispaced context with duration shorter than the schedule duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_longer_duration(self): """Test equispaced context with duration longer than the schedule duration.""" context = transforms.AlignEquispaced(duration=50) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) reference.insert(40, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_short_duration(self): """Test equispaced context with multiple channels and duration shorter than the total duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(0, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_longer_duration(self): """Test equispaced context with multiple channels and duration longer than the total duration.""" context = transforms.AlignEquispaced(duration=30) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) class TestAlignFunc(QiskitTestCase): """Test callback alignment transform.""" @staticmethod def _position(ind): """Returns 0.25, 0.5, 0.75 for ind = 1, 2, 3.""" return ind / (3 + 1) def test_numerical_with_short_duration(self): """Test numerical alignment context with duration shorter than the schedule duration.""" context = transforms.AlignFunc(duration=20, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_numerical_with_longer_duration(self): """Test numerical alignment context with duration longer than the schedule duration.""" context = transforms.AlignFunc(duration=80, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(15, Delay(10, d0), inplace=True) reference.insert(35, Delay(10, d0), inplace=True) reference.insert(55, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) class TestFlatten(QiskitTestCase): """Test flattening transform.""" def test_flatten(self): """Test the flatten transform.""" context_left = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += instructions.Delay(3, d0) grouped = pulse.Schedule() grouped += instructions.Delay(5, d1) grouped += instructions.Delay(7, d0) # include a grouped schedule grouped = schedule + grouped # flatten the schedule inline internal groups flattened = transforms.flatten(grouped) # align all the instructions to the left after flattening flattened = context_left.align(flattened) grouped = context_left.align(grouped) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(0, instructions.Delay(5, d1), inplace=True) self.assertEqual(flattened, reference) self.assertNotEqual(grouped, reference) class _TestDirective(directives.Directive): """Pulse ``RelativeBarrier`` directive.""" def __init__(self, *channels): """Test directive""" super().__init__(operands=tuple(channels)) @property def channels(self): return self.operands class TestRemoveDirectives(QiskitTestCase): """Test removing of directives.""" def test_remove_directives(self): """Test that all directives are removed.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += _TestDirective(d0, d1) schedule += instructions.Delay(3, d0) schedule += _TestDirective(d0, d1) schedule = transforms.remove_directives(schedule) reference = pulse.Schedule() # d0 reference += instructions.Delay(3, d0) self.assertEqual(schedule, reference) class TestRemoveTrivialBarriers(QiskitTestCase): """Test scheduling transforms.""" def test_remove_trivial_barriers(self): """Test that trivial barriers are properly removed.""" schedule = pulse.Schedule() schedule += directives.RelativeBarrier() schedule += directives.RelativeBarrier(pulse.DriveChannel(0)) schedule += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) schedule = transforms.remove_trivial_barriers(schedule) reference = pulse.Schedule() reference += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) self.assertEqual(schedule, reference) class TestRemoveSubroutines(QiskitTestCase): """Test removing of subroutines.""" def test_remove_subroutines(self): """Test that nested subroutiens are removed.""" d0 = pulse.DriveChannel(0) nested_routine = pulse.Schedule() nested_routine.insert(10, pulse.Delay(10, d0), inplace=True) subroutine = pulse.Schedule() subroutine.insert(0, pulse.Delay(20, d0), inplace=True) with self.assertWarns(DeprecationWarning): subroutine.insert(20, pulse.instructions.Call(nested_routine), inplace=True) subroutine.insert(50, pulse.Delay(10, d0), inplace=True) main_program = pulse.Schedule() main_program.insert(0, pulse.Delay(10, d0), inplace=True) with self.assertWarns(DeprecationWarning): main_program.insert(30, pulse.instructions.Call(subroutine), inplace=True) target = transforms.inline_subroutines(main_program) reference = pulse.Schedule() reference.insert(0, pulse.Delay(10, d0), inplace=True) reference.insert(30, pulse.Delay(20, d0), inplace=True) reference.insert(60, pulse.Delay(10, d0), inplace=True) reference.insert(80, pulse.Delay(10, d0), inplace=True) self.assertEqual(target, reference) def test_call_in_nested_schedule(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.Schedule() subroutine.insert(10, pulse.Delay(10, d0), inplace=True) nested_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): nested_sched.insert(0, pulse.instructions.Call(subroutine), inplace=True) main_sched = pulse.Schedule() main_sched.insert(0, nested_sched, inplace=True) target = transforms.inline_subroutines(main_sched) # no call instruction reference_nested = pulse.Schedule() reference_nested.insert(0, subroutine, inplace=True) reference = pulse.Schedule() reference.insert(0, reference_nested, inplace=True) self.assertEqual(target, reference) def test_call_in_nested_block(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.ScheduleBlock() subroutine.append(pulse.Delay(10, d0), inplace=True) nested_block = pulse.ScheduleBlock() with self.assertWarns(DeprecationWarning): nested_block.append(pulse.instructions.Call(subroutine), inplace=True) main_block = pulse.ScheduleBlock() main_block.append(nested_block, inplace=True) target = transforms.inline_subroutines(main_block) # no call instruction reference_nested = pulse.ScheduleBlock() reference_nested.append(subroutine, inplace=True) reference = pulse.ScheduleBlock() reference.append(reference_nested, inplace=True) self.assertEqual(target, reference) if __name__ == "__main__": unittest.main()
https://github.com/Jayshah25/Quantum-Algorithms-and-Circuits
Jayshah25
import numpy as np zero_state = np.array([[1],[0]]) one_state = np.array([[0],[1]]) print("The |0> is \n", zero_state) print("The |1> is \n", one_state) print("The shape of the Vector |0> is",zero_state.shape) print("The shape of the Vector |1> is",one_state.shape) !pip install qiskit #Install qiskit on colab !pip install pylatexenc #Required for matplotlib support to render the images of circuit from IPython.display import clear_output #Clear the output after installation clear_output() #QuantumCircuit is the class that we shall use for our circuit #Aer is required to get the required backend support #execute will execute our circuit from qiskit import QuantumCircuit, Aer, execute circuit_es1 = QuantumCircuit(2,2) #initializing our circuit with two qubits and two bits circuit_es1.h(0) #Applying hadamard Gate on the first qubit circuit_es1.cx(0,1) #Applying the CNOT Gate with zeroth qubit as the control qubit #and the first qubit as the target qubit circuit_es1.measure(0,0) #Measuring the zeroth qubit and storing its output to zeroth bit circuit_es1.measure(1,1) #Let's visualize our circuit circuit_es1.draw('mpl') simulator = Aer.get_backend('qasm_simulator') #Using qasm_simulator, we can simulate our circuit on an actual quantum device result = execute(circuit_es1,backend=simulator, shots = 1024).result() #shots = number of time we want to execute the circuit counts = result.get_counts() #Get the results for each simulation from qiskit.visualization import plot_histogram #To visualize our results plot_histogram(counts) circuit_es2 = QuantumCircuit(2,2) circuit_es2.x(0) #Applying the NOT Gate on the first qubit to get the state |01> circuit_es2.h(0) circuit_es2.cx(0,1) circuit_es2.measure(0,0) circuit_es2.measure(1,1) #Let's visualize our circuit circuit_es2.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es2,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) circuit_es3 = QuantumCircuit(2,2) circuit_es3.x(1) #Applying the NOT Gate on the second qubit to get the state |10> circuit_es3.h(0) circuit_es3.cx(0,1) circuit_es3.measure(0,0) circuit_es3.measure(1,1) #Let's visualize our circuit circuit_es3.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es3,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) circuit_es4 = QuantumCircuit(2,2) circuit_es4.x(0) circuit_es4.x(1) #Applying the NOT Gates on the two qubits to get the state |11> circuit_es4.h(0) circuit_es4.cx(0,1) circuit_es4.measure(0,0) circuit_es4.measure(1,1) #Let's visualize our circuit circuit_es4.draw('mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit_es4,backend=simulator, shots = 1024).result() counts = result.get_counts() plot_histogram(counts)
https://github.com/bagmk/Quantum_Machine_Learning_Express
bagmk
# The code below is a hack in case Travis' kernel fails. #import os #os.environ['KMP_DUPLICATE_LIB_OK'] ='True' # Pull in the helper files. import sys sys.path.append('../../Pyfiles') # Pull in the helper files. from experiments import * # Set up the experiment circuitID = 14 epochs = 20 import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) lr_list=[round(((i+1)/10)**2,2) for i in range(20)] ds_list=['0','1a','2a','3c'] for dsID in ds_list: # Run the experiment print('--------dataset',dsID,'is initialized------') lr_acc=[] for lr in lr_list: # Load in the data data = load_data(dsID) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr, train_X, train_y) # Check the validation accuracy. val_accuracy = check_accuracy(model, validate_X, validate_y) lr_acc.append([lr,val_accuracy]) np.savetxt(r"Learning_Rate_Data\circuit{0}_data{1}.txt".format(circuitID,dsID),lr_acc,fmt='%.2f') # Set up the experiment circuitID = 14 epochs = 20 ds_list=['0','1a','2a','3c'] #selected learning rates lr_opt=[0.01,3.61,0.04,0.25] model_list=[] for i in range(4): data = load_data(ds_list[i]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) # Make the feature map feature_map= make_embedding_circuit() # Make the classifier ansatz = make_classifer_circuit(circuitID) # Do the training model = train_model(feature_map, ansatz, epochs, lr_opt[i], train_X, train_y) model_list.append(model) # Check the validation accuracy. val_accuracy = check_accuracy(model, test_X, test_y) import matplotlib.pyplot as plt for lr in range(4): data = load_data(ds_list[lr]) # Generate the splittings train_X, train_y, validate_X, validate_y, test_X, test_y = generate_train_validate_test_data(data) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(4, 2, 2*lr+1) y_predict = [] for x in test_X: output = model_list[lr](Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print(check_accuracy(model_list[lr], test_X, test_y)) # plot results # red == wrongly classified for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') if y_target != y_: ax.scatter(x[0], x[1], s=200, facecolors='none', edgecolors='r', linewidths=2) ax = fig.add_subplot(4, 2, 2*lr+2) for x, y_target, y_ in zip(test_X, test_y, y_predict): if y_target == 1: ax.plot(x[0], x[1], 'bo') else: ax.plot(x[0], x[1], 'go') X1 = np.linspace(0, 1, num=10) Z1 = np.zeros((len(X1), len(X1))) # Contour map for j in range(len(X1)): for k in range(len(X1)): # Fill Z with the labels (numerical values) # the inner loop goes over the columns of Z, # which corresponds to sweeping x-values # Therefore, the role of j,k is flipped in the signature Z1[j, k] = np.argmax(model_list[lr](Tensor([X1[k],X1[j],X1[k],X1[j]])).detach().numpy()) ax.contourf(X1, X1, Z1, cmap='bwr', levels=30)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Basic rescheduling functions which take schedule or instructions and return new schedules.""" import warnings from collections import defaultdict from typing import List, Optional, Iterable, Union, Type import numpy as np from qiskit.pulse import channels as chans, exceptions, instructions from qiskit.pulse.channels import ClassicalIOChannel from qiskit.pulse.exceptions import PulseError from qiskit.pulse.exceptions import UnassignedDurationError from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock, ScheduleComponent def block_to_schedule(block: ScheduleBlock) -> Schedule: """Convert ``ScheduleBlock`` to ``Schedule``. Args: block: A ``ScheduleBlock`` to convert. Returns: Scheduled pulse program. Raises: UnassignedDurationError: When any instruction duration is not assigned. PulseError: When the alignment context duration is shorter than the schedule duration. .. note:: This transform may insert barriers in between contexts. """ if not block.is_schedulable(): raise UnassignedDurationError( "All instruction durations should be assigned before creating `Schedule`." "Please check `.parameters` to find unassigned parameter objects." ) schedule = Schedule.initialize_from(block) for op_data in block.blocks: if isinstance(op_data, ScheduleBlock): context_schedule = block_to_schedule(op_data) if hasattr(op_data.alignment_context, "duration"): # context may have local scope duration, e.g. EquispacedAlignment for 1000 dt post_buffer = op_data.alignment_context.duration - context_schedule.duration if post_buffer < 0: raise PulseError( f"ScheduleBlock {op_data.name} has longer duration than " "the specified context duration " f"{context_schedule.duration} > {op_data.duration}." ) else: post_buffer = 0 schedule.append(context_schedule, inplace=True) # prevent interruption by following instructions. # padding with delay instructions is no longer necessary, thanks to alignment context. if post_buffer > 0: context_boundary = instructions.RelativeBarrier(*op_data.channels) schedule.append(context_boundary.shift(post_buffer), inplace=True) else: schedule.append(op_data, inplace=True) # transform with defined policy return block.alignment_context.align(schedule) def compress_pulses(schedules: List[Schedule]) -> List[Schedule]: """Optimization pass to replace identical pulses. Args: schedules: Schedules to compress. Returns: Compressed schedules. """ existing_pulses = [] new_schedules = [] for schedule in schedules: new_schedule = Schedule.initialize_from(schedule) for time, inst in schedule.instructions: if isinstance(inst, instructions.Play): if inst.pulse in existing_pulses: idx = existing_pulses.index(inst.pulse) identical_pulse = existing_pulses[idx] new_schedule.insert( time, instructions.Play(identical_pulse, inst.channel, inst.name), inplace=True, ) else: existing_pulses.append(inst.pulse) new_schedule.insert(time, inst, inplace=True) else: new_schedule.insert(time, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def flatten(program: Schedule) -> Schedule: """Flatten (inline) any called nodes into a Schedule tree with no nested children. Args: program: Pulse program to remove nested structure. Returns: Flatten pulse program. Raises: PulseError: When invalid data format is given. """ if isinstance(program, Schedule): flat_sched = Schedule.initialize_from(program) for time, inst in program.instructions: flat_sched.insert(time, inst, inplace=True) return flat_sched else: raise PulseError(f"Invalid input program {program.__class__.__name__} is specified.") def inline_subroutines(program: Union[Schedule, ScheduleBlock]) -> Union[Schedule, ScheduleBlock]: """Recursively remove call instructions and inline the respective subroutine instructions. Assigned parameter values, which are stored in the parameter table, are also applied. The subroutine is copied before the parameter assignment to avoid mutation problem. Args: program: A program which may contain the subroutine, i.e. ``Call`` instruction. Returns: A schedule without subroutine. Raises: PulseError: When input program is not valid data format. """ if isinstance(program, Schedule): return _inline_schedule(program) elif isinstance(program, ScheduleBlock): return _inline_block(program) else: raise PulseError(f"Invalid program {program.__class__.__name__} is specified.") def _inline_schedule(schedule: Schedule) -> Schedule: """A helper function to inline subroutine of schedule. .. note:: If subroutine is ``ScheduleBlock`` it is converted into Schedule to get ``t0``. """ ret_schedule = Schedule.initialize_from(schedule) for t0, inst in schedule.children: # note that schedule.instructions unintentionally flatten the nested schedule. # this should be performed by another transformer node. if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() # convert into schedule if block is given if isinstance(subroutine, ScheduleBlock): subroutine = block_to_schedule(subroutine) # recursively inline the program inline_schedule = _inline_schedule(subroutine) ret_schedule.insert(t0, inline_schedule, inplace=True) elif isinstance(inst, Schedule): # recursively inline the program inline_schedule = _inline_schedule(inst) ret_schedule.insert(t0, inline_schedule, inplace=True) else: ret_schedule.insert(t0, inst, inplace=True) return ret_schedule def _inline_block(block: ScheduleBlock) -> ScheduleBlock: """A helper function to inline subroutine of schedule block. .. note:: If subroutine is ``Schedule`` the function raises an error. """ ret_block = ScheduleBlock.initialize_from(block) for inst in block.blocks: if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() if isinstance(subroutine, Schedule): raise PulseError( f"A subroutine {subroutine.name} is a pulse Schedule. " "This program cannot be inserted into ScheduleBlock because " "t0 associated with instruction will be lost." ) # recursively inline the program inline_block = _inline_block(subroutine) ret_block.append(inline_block, inplace=True) elif isinstance(inst, ScheduleBlock): # recursively inline the program inline_block = _inline_block(inst) ret_block.append(inline_block, inplace=True) else: ret_block.append(inst, inplace=True) return ret_block def remove_directives(schedule: Schedule) -> Schedule: """Remove directives. Args: schedule: A schedule to remove compiler directives. Returns: A schedule without directives. """ return schedule.exclude(instruction_types=[directives.Directive]) def remove_trivial_barriers(schedule: Schedule) -> Schedule: """Remove trivial barriers with 0 or 1 channels. Args: schedule: A schedule to remove trivial barriers. Returns: schedule: A schedule without trivial barriers """ def filter_func(inst): return isinstance(inst[1], directives.RelativeBarrier) and len(inst[1].channels) < 2 return schedule.exclude(filter_func) def align_measures( schedules: Iterable[ScheduleComponent], inst_map: Optional[InstructionScheduleMap] = None, cal_gate: str = "u3", max_calibration_duration: Optional[int] = None, align_time: Optional[int] = None, align_all: Optional[bool] = True, ) -> List[Schedule]: """Return new schedules where measurements occur at the same physical time. This transformation will align the first :class:`.Acquire` on every channel to occur at the same time. Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with ``max_calibration_duration``. By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel` will be shifted. If you wish to keep the relative timing of all instructions in the schedule set ``align_all=True``. This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)`` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. .. code-block:: from qiskit import pulse from qiskit.pulse import transforms d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) sched = pulse.Schedule() sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True) sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True) sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True) sched_shifted = sched << 20 aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted]) assert aligned_sched == aligned_sched_shifted If it is desired to only shift acquisition and measurement stimulus instructions set the flag ``align_all=False``: .. code-block:: aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], align_all=False, ) assert aligned_sched != aligned_sched_shifted Args: schedules: Collection of schedules to be aligned together inst_map: Mapping of circuit operations to pulse schedules cal_gate: The name of the gate to inspect for the calibration time max_calibration_duration: If provided, inst_map and cal_gate will be ignored align_time: If provided, this will be used as final align time. align_all: Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If ``False`` only the acquisition and measurement pulse instructions will be shifted. Returns: The input list of schedules transformed to have their measurements aligned. Raises: PulseError: If the provided alignment time is negative. """ def get_first_acquire_times(schedules): """Return a list of first acquire times for each schedule.""" acquire_times = [] for schedule in schedules: visited_channels = set() qubit_first_acquire_times = defaultdict(lambda: None) for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire) and inst.channel not in visited_channels: visited_channels.add(inst.channel) qubit_first_acquire_times[inst.channel.index] = time acquire_times.append(qubit_first_acquire_times) return acquire_times def get_max_calibration_duration(inst_map, cal_gate): """Return the time needed to allow for readout discrimination calibration pulses.""" # TODO (qiskit-terra #5472): fix behavior of this. max_calibration_duration = 0 for qubits in inst_map.qubits_with_instruction(cal_gate): cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi) max_calibration_duration = max(cmd.duration, max_calibration_duration) return max_calibration_duration if align_time is not None and align_time < 0: raise exceptions.PulseError("Align time cannot be negative.") first_acquire_times = get_first_acquire_times(schedules) # Extract the maximum acquire in every schedule across all acquires in the schedule. # If there are no acquires in the schedule default to 0. max_acquire_times = [max(0, *times.values()) for times in first_acquire_times] if align_time is None: if max_calibration_duration is None: if inst_map: max_calibration_duration = get_max_calibration_duration(inst_map, cal_gate) else: max_calibration_duration = 0 align_time = max(max_calibration_duration, *max_acquire_times) # Shift acquires according to the new scheduled time new_schedules = [] for sched_idx, schedule in enumerate(schedules): new_schedule = Schedule.initialize_from(schedule) stop_time = schedule.stop_time if align_all: if first_acquire_times[sched_idx]: shift = align_time - max_acquire_times[sched_idx] else: shift = align_time - stop_time else: shift = 0 for time, inst in schedule.instructions: measurement_channels = { chan.index for chan in inst.channels if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel)) } if measurement_channels: sched_first_acquire_times = first_acquire_times[sched_idx] max_start_time = max( sched_first_acquire_times[chan] for chan in measurement_channels if chan in sched_first_acquire_times ) shift = align_time - max_start_time if shift < 0: warnings.warn( "The provided alignment time is scheduling an acquire instruction " "earlier than it was scheduled for in the original Schedule. " "This may result in an instruction being scheduled before t=0 and " "an error being raised." ) new_schedule.insert(time + shift, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule: """Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones. .. warning:: Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification. Args: schedule: Schedule to be aligned. meas_map: List of lists of qubits that are measured together. Returns: A ``Schedule`` with the additional acquisition instructions. """ new_schedule = Schedule.initialize_from(schedule) acquire_map = {} for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire): if inst.mem_slot and inst.mem_slot.index != inst.channel.index: warnings.warn( "One of your acquires was mapped to a memory slot which didn't match" " the qubit index. I'm relabeling them to match." ) # Get the label of all qubits that are measured with the qubit(s) in this instruction all_qubits = [] for sublist in meas_map: if inst.channel.index in sublist: all_qubits.extend(sublist) # Replace the old acquire instruction by a new one explicitly acquiring all qubits in # the measurement group. for i in all_qubits: explicit_inst = instructions.Acquire( inst.duration, chans.AcquireChannel(i), mem_slot=chans.MemorySlot(i), kernel=inst.kernel, discriminator=inst.discriminator, ) if time not in acquire_map: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map = {time: {i}} elif i not in acquire_map[time]: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map[time].add(i) else: new_schedule.insert(time, inst, inplace=True) return new_schedule def pad( schedule: Schedule, channels: Optional[Iterable[chans.Channel]] = None, until: Optional[int] = None, inplace: bool = False, pad_with: Optional[Type[instructions.Instruction]] = None, ) -> Schedule: """Pad the input Schedule with ``Delay``s on all unoccupied timeslots until ``schedule.duration`` or ``until`` if not ``None``. Args: schedule: Schedule to pad. channels: Channels to pad. Defaults to all channels in ``schedule`` if not provided. If the supplied channel is not a member of ``schedule`` it will be added. until: Time to pad until. Defaults to ``schedule.duration`` if not provided. inplace: Pad this schedule by mutating rather than returning a new schedule. pad_with: Pulse ``Instruction`` subclass to be used for padding. Default to :class:`~qiskit.pulse.instructions.Delay` instruction. Returns: The padded schedule. Raises: PulseError: When non pulse instruction is set to `pad_with`. """ until = until or schedule.duration channels = channels or schedule.channels if pad_with: if issubclass(pad_with, instructions.Instruction): pad_cls = pad_with else: raise PulseError( f"'{pad_with.__class__.__name__}' is not valid pulse instruction to pad with." ) else: pad_cls = instructions.Delay for channel in channels: if isinstance(channel, ClassicalIOChannel): continue if channel not in schedule.channels: schedule = schedule.insert(0, instructions.Delay(until, channel), inplace=inplace) continue prev_time = 0 timeslots = iter(schedule.timeslots[channel]) to_pad = [] while prev_time < until: try: t0, t1 = next(timeslots) except StopIteration: to_pad.append((prev_time, until - prev_time)) break if prev_time < t0: to_pad.append((prev_time, min(t0, until) - prev_time)) prev_time = t1 for t0, duration in to_pad: schedule = schedule.insert(t0, pad_cls(duration, channel), inplace=inplace) return schedule
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/AnkRaw/Quantum-Convolutional-Neural-Network
AnkRaw
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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 the SetLayout pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passes import SetLayout, ApplyLayout, FullAncillaAllocation from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager, TranspilerError class TestSetLayout(QiskitTestCase): """Tests the SetLayout pass""" def assertEqualToReference(self, result_to_compare): """Compare result_to_compare to a reference ┌───┐ ░ ┌─┐ q_0 -> 0 ┤ H ├─░─┤M├─────────────── ├───┤ ░ └╥┘┌─┐ q_1 -> 1 ┤ H ├─░──╫─┤M├──────────── ├───┤ ░ ║ └╥┘ ┌─┐ q_4 -> 2 ┤ H ├─░──╫──╫───────┤M├─── ├───┤ ░ ║ ║ ┌─┐ └╥┘ q_2 -> 3 ┤ H ├─░──╫──╫─┤M├────╫──── └───┘ ░ ║ ║ └╥┘ ║ ancilla_0 -> 4 ─────────╫──╫──╫─────╫──── ┌───┐ ░ ║ ║ ║ ┌─┐ ║ q_3 -> 5 ┤ H ├─░──╫──╫──╫─┤M├─╫──── ├───┤ ░ ║ ║ ║ └╥┘ ║ ┌─┐ q_5 -> 6 ┤ H ├─░──╫──╫──╫──╫──╫─┤M├ └───┘ ░ ║ ║ ║ ║ ║ └╥┘ meas: 6/═════════╩══╩══╩══╩══╩══╩═ 0 1 2 3 4 5 """ qr = QuantumRegister(6, "q") ancilla = QuantumRegister(1, "ancilla") cl = ClassicalRegister(6, "meas") reference = QuantumCircuit(qr, ancilla, cl) reference.h(qr) reference.barrier(qr) reference.measure(qr, cl) pass_manager = PassManager() pass_manager.append( SetLayout( Layout({qr[0]: 0, qr[1]: 1, qr[4]: 2, qr[2]: 3, ancilla[0]: 4, qr[3]: 5, qr[5]: 6}) ) ) pass_manager.append(ApplyLayout()) self.assertEqual(result_to_compare, pass_manager.run(reference)) def test_setlayout_as_Layout(self): """Construct SetLayout with a Layout.""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.h(qr) circuit.measure_all() pass_manager = PassManager() pass_manager.append( SetLayout(Layout.from_intlist([0, 1, 3, 5, 2, 6], QuantumRegister(6, "q"))) ) pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7))) pass_manager.append(ApplyLayout()) result = pass_manager.run(circuit) self.assertEqualToReference(result) def test_setlayout_as_list(self): """Construct SetLayout with a list.""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.h(qr) circuit.measure_all() pass_manager = PassManager() pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6])) pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7))) pass_manager.append(ApplyLayout()) result = pass_manager.run(circuit) self.assertEqualToReference(result) def test_raise_when_layout_len_does_not_match(self): """Test error is raised if layout defined as list does not match the circuit size.""" qr = QuantumRegister(42, "q") circuit = QuantumCircuit(qr) pass_manager = PassManager() pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6])) pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7))) pass_manager.append(ApplyLayout()) with self.assertRaises(TranspilerError): pass_manager.run(circuit) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Module to simulate spin circuits.""" import math from typing import List, Union, Optional from fractions import Fraction import numpy as np from scipy.sparse import csc_matrix from qiskit import QuantumCircuit from qiskit_nature.second_q.operators import SpinOp from qiskit_cold_atom.base_circuit_solver import BaseCircuitSolver from qiskit_cold_atom.exceptions import QiskitColdAtomError class SpinCircuitSolver(BaseCircuitSolver): """Performs numerical simulations of spin systems by exactly computing the time evolution under unitary operations generated by exponentiating spin Hamiltonians.""" def __init__( self, spin: Union[float, Fraction] = Fraction(1, 2), shots: Optional[int] = None, seed: Optional[int] = None, ): """ Initialize a spin circuit solver. Args: spin: The length of the spin of each wire in the circuit. shots: Amount of shots for the measurement simulation; if not None, measurements are performed. seed: The seed for the RNG for the measurement simulation. Raises: QiskitColdAtomError: if the spin is not a positive integer or half-integer. """ self.spin = Fraction(spin) if self.spin.denominator not in (1, 2): raise QiskitColdAtomError( f"spin must be a positive half-integer (integer or half-odd-integer), " f"not {self.spin}." ) super().__init__(shots=shots, seed=seed) def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix: """ Return the initial state as a sparse column vector. Args: circuit: A circuit that tells us the dimension of the initial state to return. Returns: initial state: A sparse column vector of the initial state. """ dim = int((2 * self.spin + 1) ** circuit.num_qubits) initial_state = csc_matrix(([1 + 0j], ([0], [0])), shape=(dim, 1), dtype=complex) return initial_state def _embed_operator(self, operator: SpinOp, num_wires: int, qargs: List[int]) -> SpinOp: """ Turning a SpinOp operator that acts onto the wires given in qargs into an operator that acts on the entire register of the circuit by manipulating the indices of the sparse labels of the SpinOps. Args: operator: SpinOp describing the generating Hamiltonian of a gate num_wires: The total number of wires in which the operator should be embedded into qargs: The wire indices the gate acts on Returns: A SpinOp acting on the entire quantum register of the Circuit Raises: QiskitColdAtomError: - If the given operator is not a SpinOp - If the size of the operator does not match the given qargs """ if not isinstance(operator, SpinOp): raise QiskitColdAtomError(f"Expected SpinOp; got {type(operator).__name__} instead") if operator.num_spins != len(qargs): raise QiskitColdAtomError( f"operator size {operator.num_spins} does not match qargs {qargs} of the gates." ) embedded_op_dict = {} for label, factor in operator._data.items(): old_labels = label.split() new_labels = [term[:2] + str(qargs[int(term[2])]) + term[3:] for term in old_labels] embedded_op_dict[" ".join(map(str, new_labels))] = factor return SpinOp(embedded_op_dict, spin=self.spin, num_spins=num_wires) def operator_to_mat(self, operator: SpinOp) -> csc_matrix: """ Convert a SpinOp describing a gate generator to a sparse matrix. Args: operator: spin operator of which to compute the matrix representation Returns: scipy.sparse matrix of the Hamiltonian """ return csc_matrix(operator.to_matrix()) def preprocess_circuit(self, circuit: QuantumCircuit): r""" Compute the Hilbert space dimension of the given quantum circuit as :math:`(2S+1)^N` where :math:`S` is the length of the spin and :math:`N` is the number of spins in the quantum circuit. Args: circuit: The circuit to pre-process. """ self._dim = int((2 * self.spin + 1) ** circuit.num_qubits) def draw_shots(self, measurement_distribution: List[float]) -> List[str]: r"""A helper function to draw counts from a given distribution of measurement outcomes. Args: measurement_distribution: List of probabilities of the individual measurement outcomes. Returns: outcome_memory: A list of individual measurement results, e.g. ["12 3 4", "0 4 9", ...] The outcome of each shot is denoted by a space-delimited string "a1 a2 a3 ..." where :math:`a_i` is the measured level of the spin with possible values ranging from 0 to 2S The :math:`a_i` are in reverse order of the spins of the register to comply with qiskit's little endian convention. Raises: QiskitColdAtomError: - If the length of the given probabilities does not math the expected Hilbert space dimension. - If the dimension is not a power of the spin length of the solver. - If the number of shots self.shots has not been specified. """ meas_dim = len(measurement_distribution) if meas_dim != self.dim: raise QiskitColdAtomError( f"Dimension of the measurement probabilities {meas_dim} does not " f"match the dimension expected by the solver, {self.dim}" ) if self.shots is None: raise QiskitColdAtomError( "The number of shots has to be set before drawing measurements" ) # Draw measurements as the indices of the basis states: meas_results = np.random.choice(range(meas_dim), self.shots, p=measurement_distribution) base = int(2 * self.spin + 1) num_wires = math.log(meas_dim, base) if num_wires.is_integer(): num_wires = int(num_wires) else: raise QiskitColdAtomError( "The length of given measurement distribution it not compatible with " "the spin-length of the solver." ) outcome_memory = [] for meas_idx in meas_results: digits = [0] * num_wires for i in range(num_wires): digits[i] = meas_idx % base meas_idx //= base outcome_memory.append(" ".join(map(str, digits))) return outcome_memory
https://github.com/parton-quark/RLSB-CongX-Qiskit
parton-quark
!pip install qiskit !pip install CongX from tfc_to_qiskit import tfc_to_qiskit tfc_to_qiskit('test.tfc.txt') import RLSBCQ_test RLSBCQ_test.qc.draw(output='mpl') from qiskit.compiler import transpile transpiled = transpile(RLSBCQ_test.qc, backend=None, basis_gates=None, coupling_map=None, backend_properties=None, initial_layout=None, seed_transpiler=None, optimization_level=None, pass_manager=None, callback=None, output_name=None) transpiled.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits to represent the uncertainty num_uncertainty_qubits = 3 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high) ) # plot probability distribution x = uncertainty_model.values y = uncertainty_model.probabilities plt.bar(x, y, width=0.2) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.grid() plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15) plt.ylabel("Probability ($\%$)", size=15) plt.show() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) plt.plot(x, y, "ro-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Spot Price", size=15) plt.ylabel("Payoff", size=15) plt.xticks(x, size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value (normalized to the [0, 1] interval) exact_value = np.dot(uncertainty_model.probabilities, y) exact_delta = sum(uncertainty_model.probabilities[x >= strike_price]) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/emad-boosari/QuEST_Group
emad-boosari
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, Operator from qiskit.visualization import plot_histogram # let me consider an arbitrary quantum circuit with 4 qubits and 4 classical bits qc = QuantumCircuit(4,4) # I apply some initial single quantum gates # These gates are also arbitrary without a particular purpose qc.h(range(4)) qc.barrier() qc.draw('mpl',initial_state=True) # To build a gate we define a quantum circuit without classical bit like below gate1 = QuantumCircuit(2, name = 'gate1') # Then we can use a bunch of the Qiskit gates in order to build an arbitrary gate. gate1.cz(0,1) gate1.x(0) gate1.barrier() gate1.h(1) gate1.barrier() gate1.cx(0,1) # Make this circuit as a gate for qiskit gate1.to_gate gate1.draw('mpl') # Now we can apply our gate on the qc circuit qc.append(gate1,[0,1]) qc.append(gate1,[0,2]) qc.append(gate1,[1,3]) qc.append(gate1,[0,3]) display(qc.draw('mpl'),Statevector(qc).draw('latex')) import numpy as np # you can write any unitary gate that you need. In the following I am trying to build one uni = np.zeros((4,4)) uni[0,0] = 1 uni[3,3] = 1 uni[1,2] = 1 uni[2,1] = 1 print(uni) # test of being unitary np.dot(np.transpose(uni),uni) from qiskit.quantum_info import Operator gate2 = Operator(uni) qc.barrier() qc.unitary(gate2,(2,3),label='gate2') qc.draw('mpl') for i in range(4): qc.measure(i,i) qc.draw('mpl',cregbundle=False) from qiskit import transpile from qiskit.visualization import plot_histogram from qiskit.providers.aer import QasmSimulator backend = QasmSimulator() job = transpile(qc,backend) result = backend.run(job,shots=1024).result() counts = result.get_counts() plot_histogram(counts) counts
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/Pitt-JonesLab/clonk_transpilation
Pitt-JonesLab
"""Define circuits to test.""" from supermarq.benchmarks.ghz import GHZ from supermarq.benchmarks.hamiltonian_simulation import HamiltonianSimulation from supermarq.benchmarks.qaoa_vanilla_proxy import QAOAVanillaProxy from supermarq.converters import cirq_to_qiskit class CircuitTranspilerBenchmark: # TODO: circuit_lambda could take multiple params if desired def __init__(self, circuit_lambda, q_range, label): self.circuit_lambda = circuit_lambda # self.q_range = q_range self.label = label # FIXME should this be a class, q_range is a parameter, instead of dict use get methods circuits = {} depth = 10 q_range = None # deprecated, move to backendbenchmark object # Random # from qiskit.circuit.random import random_circuit # random_lambda = lambda q: random_circuit(q, depth, measure=False, max_operands=2) # label = "Randomized_QC" # circuits[label] = CircuitTranspilerBenchmark(random_lambda, q_range, label=label) # # Quantum Volume from qiskit.circuit.library import QuantumVolume def qv_lambda(q): return QuantumVolume(num_qubits=q, depth=q) label = "Quantum_Volume" circuits[label] = CircuitTranspilerBenchmark(qv_lambda, q_range, label=label) # QFT from qiskit.circuit.library.basis_change import QFT def qft_lambda(q): return QFT(q) label = "QFT" circuits[label] = CircuitTranspilerBenchmark(qft_lambda, q_range, label=label) # # Inverse QFT # inverse_qft_lambda = lambda q: QFT(q, inverse=True) # label = "IQFT" # circuits[label] = CircuitTranspilerBenchmark(inverse_qft_lambda, q_range, label=label) # QAOA, takes a long time to generate - consider capping max size before 20 # qaoa_lambda = lambda q: cirq_to_qiskit(QAOAFermionicSwapProxy(q).circuit()) # label = "QAOA_Fermionic_Swap" # circuits[label] = CircuitTranspilerBenchmark(qaoa_lambda, q_range, label=label) # # QAOA vanilla def qaoa_vanilla_lambda(q): return cirq_to_qiskit(QAOAVanillaProxy(q).circuit()) label = "QAOA_Vanilla" circuits[label] = CircuitTranspilerBenchmark(qaoa_vanilla_lambda, q_range, label=label) # VQE - very slow to generate # vqe_lambda = lambda q: cirq_to_qiskit(VQEProxy(q, 4).circuit()[0]) # label = "VQE" # circuits[label] = CircuitTranspilerBenchmark(vqe_lambda, q_range, label=label) # Simulation def hamiltonian_lambda(q): return cirq_to_qiskit(HamiltonianSimulation(q, 1 / depth, 0.5).circuit()) label = "TIM_Hamiltonian" circuits[label] = CircuitTranspilerBenchmark(hamiltonian_lambda, q_range, label=label) from qiskit import QuantumCircuit # weighted adder or ripple carry adder from qiskit.circuit.library.arithmetic.adders.cdkm_ripple_carry_adder import ( CDKMRippleCarryAdder, ) # using trick of composing into an empty circuit so that it builds everything into a single quantumregister def adder_lambda(q): return ( QuantumCircuit(q) .compose(CDKMRippleCarryAdder(num_state_qubits=int((q - 1) / 2)), inplace=False) .decompose() .decompose() .decompose() ) label = "Adder" circuits[label] = CircuitTranspilerBenchmark(adder_lambda, q_range, label=label) # multiplier # from qiskit.circuit.library.arithmetic.multipliers import RGQFTMultiplier # multiplier_lambda = ( # lambda q: QuantumCircuit(q) # .compose(RGQFTMultiplier(num_state_qubits=int(q / 4)), inplace=False) # .decompose() # .decompose() # .decompose() # ) # label = "Multiplier" # circuits[label] = CircuitTranspilerBenchmark(multiplier_lambda, q_range, label=label) # # GHZ def ghz_lambda(q): return cirq_to_qiskit(GHZ(q).circuit()) label = "GHZ" circuits[label] = CircuitTranspilerBenchmark(ghz_lambda, q_range, label=label)
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/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
print('\nDevice Monitor') print('----------------') from qiskit import IBMQ from qiskit.tools.monitor import backend_overview IBMQ.enable_account('Insert API token here') # Insert your API token in to here provider = IBMQ.get_provider(hub='ibm-q') backend_overview() # Function to get all information back about each quantum device print('\nPress any key to close') input()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
with open('in-exemplo.txt', 'r') as f: print(f.read()) with open('out-exemplo.txt', 'r') as f: print(f.read()) import time import matplotlib.pyplot as plt import pandas as pd import os import subprocess %matplotlib inline #Roda entradas def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'): with open(arquivo_in) as f: start = time.perf_counter() a = f.read() proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ)) end = time.perf_counter() f.close() ret = '' for i in a: if i == "\n": break ret += i return (proc.stdout, end - start, int(ret)) #retorna tamanho do tour apartir do stdout def tamanho_tour(out): buf = '' for i in out: if i == " ": return float(buf) buf += i #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] resultados1 = [] resultados2 = [] resultados3 = [] #Usando as mesmas entradas for i in range(8): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt') c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tamanho_entradas.append(a[2]) resultados1.append(tamanho_tour(a[0])) resultados2.append(tamanho_tour(b[0])) resultados3.append(tamanho_tour(c[0])) #Teste com entrada um pouco maior print("Rodando entrada: 8") tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1]) tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1]) tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1]) tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2]) resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0])) resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0])) resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0])) plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-exaustiva", "busca-local","heuristico"]) plt.show() plt.title("Comparacao Desempenho") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_2) plt.legend(["busca-local","heuristico"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-tempo"] = pd.Series(tempos) df["busca-exaustiva-tempo"] = pd.Series(tempos_1) df["heuristica-tempo"] = pd.Series(tempos_2) df["busca-local-resultado"] = pd.Series(resultados1) df["busca-exaustiva-resultado"] = pd.Series(resultados2) df["heuristica-resultado"] = pd.Series(resultados3) df df.describe() #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] tempos_2 = [] tempos_3 = [] tempos_4 = [] tempos_5 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt') b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2') c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3') d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4') e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt') f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt') tempos.append(a[1]) tempos_1.append(b[1]) tempos_2.append(c[1]) tempos_3.append(d[1]) tempos_4.append(e[1]) tempos_5.append(f[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.plot(tamanho_entradas, tempos_2) plt.plot(tamanho_entradas, tempos_3) plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos_3) plt.plot(tamanho_entradas, tempos_5) plt.legend(["4 thread otimizado", "GPU"]) plt.show() plt.title("Comparacao Desempenho Busca Local") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_4) plt.legend(["1 thread otimizado", "Sem otimizações"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-local-1-thread"] = pd.Series(tempos) df["busca-local-2-threads"] = pd.Series(tempos_1) df["busca-local-3-threads"] = pd.Series(tempos_2) df["busca-local-4-threads"] = pd.Series(tempos_3) df["busca-local-gpu"] = pd.Series(tempos_5) df["busca-local-semopt"] = pd.Series(tempos_4) df #Cria resultados tamanho_entradas = [] tempos = [] tempos_1 = [] #Usando as mesmas entradas for i in range(7): print("Rodando entrada: "+str(i)) a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1') b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '0') tempos.append(a[1]) tempos_1.append(b[1]) tamanho_entradas.append(a[2]) plt.title("Comparacao Desempenho Busca Exaustiva") plt.ylabel("Tempo (s)") plt.xlabel("Tamanho entradas") plt.plot(tamanho_entradas, tempos) plt.plot(tamanho_entradas, tempos_1) plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"]) plt.show() df = pd.DataFrame() df["Tamanho Entrada"] = pd.Series(tamanho_entradas) df["busca-exaustiva-simples"] = pd.Series(tempos) df["busca-exaustiva-branchnbound"] = pd.Series(tempos_1) df
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, execute, transpile, assemble ) from qiskit.circuit import Gate, Instruction from qiskit.quantum_info.operators import Operator from qiskit.extensions import ZGate, YGate, XGate, IGate from scipy.optimize import ( minimize, basinhopping, differential_evolution, shgo, dual_annealing ) import random import numpy as np import cmath from typing import List, Set, Dict, Tuple, Optional, Union # import the params object of the GlobalParameters class # this provides the parameters used to desribed and model # the problem the minimizer is supposed to use. from GlobalParameters_IBMQ import params # import the vqls algorithm and corresponding code from vqls_IBMQ import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_YZ, _U_adjoint_YZ ) # The user input for the VQLS-algorithm has to be given # when params is initialized within GlobalParameters.py # The decomposition for $A$ has to be manually # inserted into the code of # the class GlobalParameters. print( "This program will execute the VQLS-algorithm on the IBMQ-Manila quantum computer " + "with 4 qubits, 2 layers in the Ansatz and an Id gate acting" + " on the third qubit (qubit_2).\n" + "|x_0> is defined by Hadamard gates acting on qubits 0, 2, 3." ) # Executing the actual VQLS-algorithm alpha_min = minimize_local_cost_function(params.method_minimization) """ Circuit with the $\vec{alpha}$ generated by the minimizer. """ # Create a circuit for the vqls-result qr_min = QuantumRegister(params.n_qubits) circ_min = QuantumCircuit(qr_min) # generate $V(\vec{alpha})$ ansatz = generate_ansatz(alpha_min).to_gate() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in the state $\ket{b}$ circ_min.append(ansatz, qr_min) # as $A$ is Id nothing happens # apply post correction to fix for sign errors and a "mirroring" # of the result circ_min = postCorrection(circ_min) """ Reference circuit based on the definition of $\ket{b}$. """ circ_ref = _U_YZ() """ Simulate both circuits. """ # the minimizations result backend = Aer.get_backend( 'statevector_simulator') t_circ = transpile(circ_min, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "This is the result of the execution on a real quantum computer.\n" + "Reminder: 4 qubits and an Id-gate on the third qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0, 2 and 3.\n" + "The list returned by the minimizer (alpha_min):\n" + str(alpha_min) + "\nWith it a circuit is built and simulated. The resulting statevector is" + ", with V(alpha_min) and A and the post correction applied:\n" + str(result.get_statevector()) ) # the reference t_circ = transpile(circ_ref, backend) qobj = assemble(t_circ) job = backend.run(qobj) result = job.result() print( "And this is the statevector for the reference circuit: A |x_0>\n" + str(result.get_statevector()) )
https://github.com/nicomeyer96/qiskit-torch-module
nicomeyer96
# This code is part of the Qiskit-Torch-Module. # # If used in your project please cite this work as described in the README file. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import numpy as np import torch import torch.nn as nn from collections.abc import Sequence from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression, ParameterVector from qiskit.quantum_info.operators.base_operator import BaseOperator from .quantum_neural_network import QNN from .quantum_autograd import QuantumAutograd class QuantumModule(nn.Module): """ This class implements a quantum torch-module, based on a underlying quantum neural network args: circuit: Quantum circuit ansatz encoding_params: Parameters used for data encoding, must be present in circuit | None if the circuit does not use data encoding variational_params: Parameters used for training, must be present in circuit variational_params_names: Names for the trainable parameter sets (default: `variational_#`) variational_params_initial: Initializers for the trainable parameter sets (default: 'uniform') choices: constant(val=1.0) | uniform(a=0.0, b=2*pi) | normal(mean=0.0, std=1.0) seed_init: Generate initial parameters with fixed seed (default: None) observables: Observables to evaluate on the circuit (default: Pauli-Z on all qubits) num_threads_forward: Number of parallel threads for forward computation (default: all available threads) num_threads_backward: Number of parallel threads for backward computation (default: all available threads) encoding_gradients_flag: Whether to compute gradients w.r.t. encoding parameters (necessary for nested modules, default: False) """ def __init__( self, circuit: QuantumCircuit, encoding_params: Sequence[Parameter] | ParameterVector | None, variational_params: Sequence[Sequence[Parameter]] | Sequence[ParameterVector] | Sequence[Parameter] | ParameterVector, variational_params_names: Sequence[str] | str = None, variational_params_initial: str | tuple[str, dict[str: float]] | Sequence[float, np.floating] | Sequence[str | tuple[str, dict[str: float]] | Sequence[float]] = 'uniform', seed_init: int = None, observables: Sequence[BaseOperator] | BaseOperator | str = 'individualZ', num_threads_forward: int = 0, num_threads_backward: int = 0, encoding_gradients_flag: bool = False, ): super(QuantumModule, self).__init__() variational_params, self._variational_params_names, variational_params_initial = ( self._preprocess_and_validate_variational_params_sets(variational_params, variational_params_names, variational_params_initial)) # whether to compute gradients w.r.t. input (necessary for Hybrid networks) self._encoding_gradients_flag = encoding_gradients_flag # whether to compute the gradients w.r.t. a specific parameter set, can be changed with # the method `set_variational_gradients_flag()` to safe compute # BE CAREFUL, as this might lead to unexpected behaviour if computing of gradients is de-activated for a # parameter set that is bound to an optimizer (as respective gradients return as `None`) self._variational_gradients_flag = [True for _ in variational_params] # set up quantum neural network self.qnn = QNN( circuit=circuit, encoding_params=encoding_params, variational_params=variational_params, observables=observables, num_threads_forward=num_threads_forward, num_threads_backward=num_threads_backward, ) self._input_size = self.qnn.num_input_parameters() self._output_size = self.qnn.num_observables() # save torch.random state from before torch_random_state_ = torch.random.get_rng_state() if seed_init is not None: torch.random.manual_seed(seed_init) # initialize torch parameter sets self._initialize_parameter_sets(variational_params, self._variational_params_names, variational_params_initial) # re-set seed to restore previous behaviour (i.e. don't interfere with potential other (un)set seeds) if seed_init is not None: torch.random.set_rng_state(torch_random_state_) def forward( self, input_tensor: torch.Tensor | None = None ) -> torch.Tensor: """ Calls into QuantumAutograd (instance of torch`s autograd functionality) to compute forward pass and constructs tree for backward pass. Args: input_tensor: Input to the quantum module, or None if there is no input data Returns: Result of forward pass """ # Allow for scenarios where no encoding parameters are used if input_tensor is not None: # Make sure everything is realized as Tensor (dtype=torch.float32 to enhance efficiency) if isinstance(input_tensor, list): # conversion list -> np.array -> torch.tensor is faster than directly list -> torch.tensor input_tensor = np.array(input_tensor) if not torch.is_tensor(input_tensor): input_tensor = torch.FloatTensor(input_tensor) else: input_tensor = input_tensor.to(dtype=torch.float32) input_tensor = QuantumAutograd.apply( self.qnn, self._encoding_gradients_flag, self._variational_gradients_flag, input_tensor, *self._trainable_parameters ) return input_tensor def set_variational_gradients_flag( self, variational_gradients_flag: Sequence[bool] | bool ) -> None: """ Manually set flags whether to compute the gradients w.r.t. specific parameter sets BE CAREFUL, as this might lead to unexpected behaviour if computing of gradients is de-activated for a parameter set that is bound to an optimizer (as respective gradients return as `None`) Args: variational_gradients_flag: Whether to compute gradients w.r.t. the parameter sets Raises: ValueError: Invalid (number of) flags were provided """ if isinstance(variational_gradients_flag, bool): self._variational_gradients_flag = [variational_gradients_flag for _ in self._variational_gradients_flag] else: if len(variational_gradients_flag) != len(self._variational_gradients_flag): raise ValueError('Mismatch, provided {} flags for {} parameter sets.' .format(variational_gradients_flag, self._variational_gradients_flag)) self._variational_gradients_flag = variational_gradients_flag def set_num_threads_forward( self, number_threads_forward: int ) -> None: """ Set number of threads for forward pass after initialization (`0` means all available). """ self.qnn.set_num_threads_forward(number_threads_forward) def set_num_threads_backward( self, number_threads_backward: int ) -> None: """ Set number of threads for backward pass after initialization (`0` means all available). """ self.qnn.set_num_threads_backward(number_threads_backward) @property def num_threads_forward(self): """ Return number of threads used for forward pass (`0` means all available) """ return self.qnn.num_threads_forward() @property def num_threads_backward(self): """ Return number of threads used for backward pass (`0` means all available) """ return self.qnn.num_threads_backward() @property def variational_(self) -> Sequence[nn.Parameter]: """ Returns a handle of the trainable parameters in the quantum module. Can be used to initialize a torch optimizer, e.g.: torchQNN = QuantumModule(...) opt = torch.optim.SGD(torchQNN.variational_, lr=0.1) This is equivalent to: opt = torch.optim.SGD(torchQNN.parameters(), lr=0.1) One can also use the class members to access the individual parameter sets (names user-defined or auto-generated): opt = torch.optim.SGD([{'params': qtmModel.variational_0}, {'params': qtmModel.variational_1}], lr=0.1) or opt = torch.optim.SGD([{'params': qtmModel.variational_[0]}, {'params': qtmModel.variational_[0]}], lr=0.1) In this case equivalent to above, but can be used to set e.g. different learning rates for parameter sets. A summary of all available parameter sets can also be visualized: print(torchQNN) """ return self._trainable_parameters @property def num_trainable_parameters(self) -> int: """ Returns number of trainable parameters in the quantum module. """ return sum([len(_tp) for _tp in self._trainable_parameters]) @property def input_size(self) -> int: """ Returns the input size of the quantum module (i.e. number of encoding parameters) """ return self._input_size @property def output_size(self) -> int: """ Returns the output size of the quantum module (i.e. number of observables) """ return self._output_size @property def circuit(self) -> QuantumCircuit: """ Returns the underlying (pre-processed and alphabetically ordered) circuit """ return self.qnn.circuit() @property def encoding_parameters(self) -> Sequence[Parameter]: """ Returns the underlying (pre-processed and alphabetically ordered) encoding parameters """ return self.qnn.input_parameters() @property def variational_parameters(self) -> Sequence[Sequence[Parameter]]: """ Returns the underlying (pre-processed and alphabetically ordered) variational parameters """ return self.qnn.trainable_parameters() def extra_repr(self) -> str: """ String-representation if the circuit. Gets returned when calling torchQNN = QuantumModule(...) print(torchQNN) """ trainable_sets_metadata = [] for _vpm, _tp in zip(self._variational_params_names, self._trainable_parameters): trainable_sets_metadata.append('({}) `{}`'.format(len(_tp), _vpm)) print_sum_trainable = '' if 1 == len(trainable_sets_metadata) else '({}) '.format(self.num_trainable_parameters) metadata = ('input_size={}, output_size={}, num_qubits={}\n{}trainable: {}' .format(self.input_size, self.output_size, self.qnn.circuit().num_qubits, print_sum_trainable, trainable_sets_metadata[0])) for tsm in trainable_sets_metadata[1:]: metadata += '\n {}'.format(tsm) # metadata += 'output_size={}'.format(self.output_size) return metadata # Alternative short representation # return f'input_size={self.input_size}, output_size={self.output_size}, trainable_parameters={self.num_trainable_parameters}' def _initialize_parameter_sets( self, variational_params: Sequence[Sequence[Parameter]], variational_params_names: Sequence[str], variational_params_initial: Sequence[tuple[str, dict[str: float]] | Sequence[float]], ) -> None: """ Sets up the actual trainable torch Parameters that are tracked via autograd Args: variational_params: Parameters used for training, must be present in circuit variational_params_names: Names for the trainable parameter sets variational_params_initial: Initializers for the trainable parameter sets Raises: ValueError: Wrong / inconclusive initializer instructions """ self._trainable_parameters = [] for set_index, (variational_params_, variational_params_names_, variational_params_initial_) \ in enumerate(zip(variational_params, variational_params_names, variational_params_initial)): if isinstance(variational_params_initial_, tuple): # initialization via (method, setup dictionary) # choices and defaults: constant(val=1.0) | uniform(a=0.0, b=2*pi) | normal(mean=0.0, std=1.0) if 'constant' == variational_params_initial_[0]: trainable_params_ = nn.init.constant_(torch.empty(len(variational_params_)), val=variational_params_initial_[1].get('val', 1.0)) elif 'uniform' == variational_params_initial_[0]: trainable_params_ = nn.init.uniform_(torch.empty(len(variational_params_)), a=variational_params_initial_[1].get('a', 0.0), b=variational_params_initial_[1].get('b', 2*np.pi)) elif 'normal' == variational_params_initial_[0]: trainable_params_ = nn.init.normal_(torch.empty(len(variational_params_)), mean=variational_params_initial_[1].get('mean', 0.0), std=variational_params_initial_[1].get('std', 1.0)) else: raise ValueError('The initialization method `{}` for parameter set #{} is not available.' .format(variational_params_initial_[0], set_index)) else: # initialization with explicit values if len(variational_params_initial_) != len(variational_params_): raise ValueError('Tried to initialize Parameter set #{} of length {} with Sequence of length {}.' .format(set_index, len(variational_params_), len(variational_params_initial_))) trainable_params_ = torch.FloatTensor(variational_params_initial_) # set up and register trainable parameter container with name `variational_params_names_` trainable_params_ = nn.Parameter(trainable_params_) self.register_parameter(variational_params_names_, trainable_params_) # setattr(self, name, value) is equivalent to self.name = value; this allows to retrieve the respective # parameter sets via QuantumModule.name (i.e. for passing them to an optimizer) setattr(self, variational_params_names_, trainable_params_) # put into one collection of trainable parameter sets self._trainable_parameters.append(getattr(self, variational_params_names_)) @ staticmethod def _preprocess_and_validate_variational_params_sets( variational_params: Sequence[Sequence[Parameter]] | Sequence[Parameter], variational_params_names: Sequence[str] | str, variational_params_initial: str | tuple[str, dict[str: float]] | Sequence[float, np.floating] | Sequence[str | tuple[str, dict[str: float]] | Sequence[float]] ) -> tuple[Sequence[Sequence[Parameter]], Sequence[str], Sequence[tuple[str, dict[str: float]] | Sequence[float]]]: """ Validate and pre-process parameters and associated metadata (names and initializer instructions) Args: variational_params: Parameters used for training, must be present in circuit variational_params_names: Names for the trainable parameter sets variational_params_initial: Initializers for the trainable parameter sets Returns: Cleaned-up version of parameters and associated metadata, ready to construct QNN and torch Parameters Raises: Value Error: Invalid naming or initialization instructions """ if (isinstance(variational_params[0], (Parameter, ParameterExpression)) or isinstance(variational_params, ParameterVector)): # singleton variational_params set variational_params = (variational_params, ) # preprocess variational_params_names if variational_params_names is None: variational_params_names = ('variational', ) elif isinstance(variational_params_names, str): # singleton variational_params_names if 'variational_' == variational_params_names: raise ValueError('The name `variational_` is already occupied and can not be used for parameter set' ' naming.') variational_params_names = (variational_params_names, ) else: raise ValueError('A singleton parameter set was given, but multiple naming instructions.') # preprocess variational_params_initial if isinstance(variational_params_initial, str): variational_params_initial = (variational_params_initial, {}) if isinstance(variational_params_initial, tuple) and isinstance(variational_params_initial[1], dict): # singleton variational_params_initial (tuple) variational_params_initial = (variational_params_initial, ) elif isinstance(variational_params_initial, Sequence) and isinstance(variational_params_initial[0], (float, np.floating)): # singleton variational_params_initial (explicit Sequence) variational_params_initial = (variational_params_initial, ) else: raise ValueError('A singleton parameter set was given, but multiple initializer instructions.') else: # multiple variational_params set # preprocess variational_params_names if variational_params_names is None: variational_params_names = ['variational_{}'.format(set_index) for set_index in range(len(variational_params))] elif isinstance(variational_params_names, str): if 'variational_' == variational_params_names: raise ValueError('The name `variational_` is already occupied and can not be used for parameter set naming.') variational_params_names = ['{}_{}'.format(variational_params_names, set_index) for set_index in range(len(variational_params))] else: if len(variational_params_names) != len(variational_params): raise ValueError('A different number of variational_params sets ({}) and naming instructions ({}) ' 'were provided.'.format(len(variational_params), len(variational_params_names))) if 'variational_' in variational_params_names: raise ValueError('The name `variational_` is already occupied and can not be used for parameter set naming.') variational_params_names_ = np.unique(variational_params_names) if len(variational_params_names_) != len(variational_params): raise ValueError('The elements in variational_params_names have to be unique.') # preprocess variational_params_input if isinstance(variational_params_initial, str): variational_params_initial = (variational_params_initial, {}) if isinstance(variational_params_initial, tuple) and isinstance(variational_params_initial[1], dict): # singleton variational_params_initial (tuple) -> copy for each variational_params set variational_params_initial = [variational_params_initial for _ in variational_params] elif isinstance(variational_params_initial, Sequence) and isinstance(variational_params_initial[0], (float, np.floating)): # singleton variational_params_initial (explicit Sequence) -> copy for each variational_params set variational_params_initial = [variational_params_initial for _ in variational_params] elif isinstance(variational_params_initial, np.ndarray): raise ValueError('Initial parameter values must be provided as a Sequence / list, not a numpy array.') else: # Sequence of variational_params_initial if len(variational_params_initial) != len(variational_params): raise ValueError('A different number of variational_params sets ({}) and initializer instructions ({}) ' 'were provided.'.format(len(variational_params), len(variational_params_initial))) for set_index, variational_params_initial_ in enumerate(variational_params_initial): if isinstance(variational_params_initial_, str): variational_params_initial_ = (variational_params_initial_, {}) if isinstance(variational_params_initial_, tuple) and isinstance(variational_params_initial_[1], dict): pass elif isinstance(variational_params_initial_, Sequence) and isinstance(variational_params_initial_[0], (float, np.floating)): pass elif isinstance(variational_params_initial_, np.ndarray): raise ValueError('Initial parameter values must be provided as a Sequence / list, not a numpy array.') else: raise ValueError('A unknown initializer instruction was provided.') variational_params_initial[set_index] = variational_params_initial_ return variational_params, variational_params_names, variational_params_initial
https://github.com/draentropia/Qiskit_PyLadiesBCN
draentropia
from qiskit import QuantumCircuit, assemble, Aer from qiskit.visualization import plot_histogram # create quantum circuit qc = QuantumCircuit(1) # 1 quantum register, 1 classical register qc.x(0) # add a gate to the circuit qc.measure_all() # add measurement at the end # run sim = Aer.get_backend('aer_simulator') qobj = assemble(qc) # Assemble a list of circuits or pulse schedules into a Qobj result = sim.run(qobj).result() # run circuit, get results # output statistics counts = result.get_counts() # extract statistics from results print(counts) plot_histogram(counts) qc.draw("mpl") from qiskit.visualization import plot_bloch_vector vector = [0, 1, 0] # coordinates [x, y, z] plot_bloch_vector(vector) # plot in the Bloch sphere qc = QuantumCircuit(1) qc.x(0) qc.y(0) qc.z(0) qc.draw("mpl") from qiskit import QuantumCircuit, assemble, Aer from qiskit.visualization import plot_bloch_multivector import numpy as np # create quantum circuit qc = QuantumCircuit(1) qc.x(0) # add gate x(qubit) # run sim = Aer.get_backend('aer_simulator') qc.save_statevector() # we want to use statevector later qobj = assemble(qc) result = sim.run(qobj).result() # run circuit, get results final_state = result.get_statevector() # get the final state from the result # visualize plot_bloch_multivector(final_state) # display final state directly on Bloch sphere from qiskit import QuantumCircuit, assemble, Aer from qiskit.visualization import plot_bloch_multivector import numpy as np # create quantum circuit qc = QuantumCircuit(1) init_state = [1. / np.sqrt(2), 1. / np.sqrt(2)] # define initial state [a,b] like a**2 + b**2 = 1 (normalization) qc.initialize(init_state, 0) # initialize qubit 0 to init_state qc.z(0) # add gate z(qubit) # run sim = Aer.get_backend('aer_simulator') qc.save_statevector() # we want to use statevector later qobj = assemble(qc) result = sim.run(qobj).result() # run circuit, get results final_state = result.get_statevector() # get the final state from the result # visualize plot_bloch_multivector(final_state) # display final state directly on Bloch sphere
https://github.com/AislingHeanue/Quantum-Computing-Circuits
AislingHeanue
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, execute, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram def binary(num,length): #converts an integer to a binary number with defined length b = bin(num)[2:] return "0"*(length-len(b))+str(b) ncon = 4 controlreg = QuantumRegister(ncon,"control") hreg = QuantumRegister(1,"y") cc = ClassicalRegister(ncon,"cc") #xi = np.random.randint(0,2**ncon-1) #xi as in the greek letter xi = 7 R = int(np.pi/4*np.sqrt(2**ncon)) qc = QuantumCircuit(controlreg,hreg,cc) def Uf(controlreg,hreg,xi,ncon): #the oracle gate, a multi=controlled x gate which is one iff the input = xi hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" return circ def ccz(controls=2): #multi controlled Z gate (decomposed here as a multi controlled X with H gates placed either side) circ = QuantumCircuit(controls+1) circ.h(controls) circ.mct(list(range(controls)),[controls]) circ.h(controls) circ.name = "c"*controls+"z" return circ def diffusion(ncon): #https://rdcu.be/cLzsq circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.append(ccz(ncon-1),list(range(ncon))) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" return circ Ufgate = Uf(controlreg,hreg,xi,ncon) qc.x(hreg[0]) qc.h(hreg[0]) qc.h(range(ncon)) for e in range(R): qc.barrier() qc.append(Ufgate,controlreg[:]+hreg[:]) qc.barrier() qc.append(diffusion(ncon).decompose(),controlreg[:ncon]) qc.barrier() qc.measure([controlreg[i] for i in range(ncon-1,-1,-1)],cc,) print(xi) qc.draw(plot_barriers=False,fold = -1,output = "latex") ?aersim aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() plot_histogram(results.get_counts()) aersim = Aer.get_backend('aer_simulator') #set memory=True to see measurements tqc = transpile(qc,aersim) results = aersim.run(tqc,shots=10000).result() d = results.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = np.arange(0,2**ncon-1,1) y = np.zeros(len(x)) for i,xi in enumerate(x): if str(xi) in d.keys(): y[i] = d[str(xi)] plt.xlim(-1,2**ncon) plt.bar(x,y,color=(0.4,0.6,1)) controlreg,hreg = QuantumRegister(4,"control"),QuantumRegister(1,"y") xi = 7 hcirc = QuantumCircuit(hreg) circ = QuantumCircuit(controlreg,hreg) xiBin = binary(xi,ncon) zerolist = [i for i in range(ncon) if (xiBin[i] == "0")] circ.x(zerolist) circ.mct(list(range(ncon)),ncon) circ.x(zerolist) circ.name = "Uf" circ.draw(output="latex") circ = QuantumCircuit(ncon) circ.h(range(ncon)) circ.x(range(ncon)) circ.h(ncon-1) circ.mct(list(range(ncon-1)),[ncon-1]) circ.h(ncon-1) circ.barrier() circ.x(range(ncon)) circ.h(range(ncon)) circ.name = "Diffusion" circ.draw(output="latex",plot_barriers=False) from qiskit import IBMQ IBMQ.enable_account("") provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_quito") res = backend.retrieve_job("622a012c9e029c54a90deedc").result() plot_histogram(res.get_counts()) nbits = 4 d = res.get_counts() oldkeys = list(d.keys()) for key in oldkeys: d[str(int(key,2))] = d[key] del d[key] x = list(range(0,7))+list(range(8,16)) xi, yi = 7,d["7"]/10000 del d["7"] y = [d[str(xi)]/10000 for xi in x] plt.xlim(-1,15.9) plt.bar(x,y,color=(0.4,0.6,1)) plt.bar(xi,yi,color=(1,0,0)) plt.ylabel("Probability") plt.xlabel("x")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization of circuit with Latex drawer.""" import os import unittest import math import numpy as np from qiskit.visualization import circuit_drawer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers.fake_provider import FakeTenerife from qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate, CPhaseGate from qiskit.extensions import HamiltonianGate from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import IQP from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals from .visualization import QiskitVisualizationTestCase pi = np.pi @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") class TestLatexSourceGenerator(QiskitVisualizationTestCase): """Qiskit latex source generator tests.""" def _get_resource_path(self, filename): reference_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(reference_dir, filename) def test_empty_circuit(self): """Test draw an empty circuit""" filename = self._get_resource_path("test_latex_empty.tex") circuit = QuantumCircuit(1) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_tiny_circuit(self): """Test draw tiny circuit.""" filename = self._get_resource_path("test_latex_tiny.tex") circuit = QuantumCircuit(1) circuit.h(0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_multi_underscore_reg_names(self): """Test multi-underscores in register names display properly""" filename1 = self._get_resource_path("test_latex_multi_underscore_true.tex") filename2 = self._get_resource_path("test_latex_multi_underscore_false.tex") q_reg1 = QuantumRegister(1, "q1_re__g__g") q_reg3 = QuantumRegister(3, "q3_re_g__g") c_reg1 = ClassicalRegister(1, "c1_re_g__g") c_reg3 = ClassicalRegister(3, "c3_re_g__g") circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3) circuit_drawer(circuit, cregbundle=True, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=False, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_normal_circuit(self): """Test draw normal size circuit.""" filename = self._get_resource_path("test_latex_normal.tex") circuit = QuantumCircuit(5) for qubit in range(5): circuit.h(qubit) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_4597(self): """Test cregbundle and conditional gates. See: https://github.com/Qiskit/qiskit-terra/pull/4597""" filename = self._get_resource_path("test_latex_4597.tex") qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[2]).c_if(cr, 2) circuit.draw(output="latex_source", cregbundle=True) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_deep_circuit(self): """Test draw deep circuit.""" filename = self._get_resource_path("test_latex_deep.tex") circuit = QuantumCircuit(1) for _ in range(100): circuit.h(0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_huge_circuit(self): """Test draw huge circuit.""" filename = self._get_resource_path("test_latex_huge.tex") circuit = QuantumCircuit(40) for qubit in range(39): circuit.h(qubit) circuit.cx(qubit, 39) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_teleport(self): """Test draw teleport circuit.""" filename = self._get_resource_path("test_latex_teleport.tex") qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) # Prepare an initial state circuit.u(0.3, 0.2, 0.1, [qr[0]]) # Prepare a Bell pair circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) # Barrier following state preparation circuit.barrier(qr) # Measure in the Bell basis circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) # Apply a correction circuit.z(qr[2]).c_if(cr, 1) circuit.x(qr[2]).c_if(cr, 2) circuit.measure(qr[2], cr[2]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_global_phase(self): """Test circuit with global phase""" filename = self._get_resource_path("test_latex_global_phase.tex") circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393""" filename = self._get_resource_path("test_latex_no_ops.tex") circuit = QuantumCircuit(2, 3) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_long_name(self): """Test to see that long register names can be seen completely As reported in #2605 """ filename = self._get_resource_path("test_latex_long_name.tex") # add a register with a very long name qr = QuantumRegister(4, "veryLongQuantumRegisterName") # add another to make sure adjustments are made based on longest qrr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr, qrr) # check gates are shifted over accordingly circuit.h(qr) circuit.h(qr) circuit.h(qr) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_conditional(self): """Test that circuits with conditionals draw correctly""" filename = self._get_resource_path("test_latex_conditional.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) # check gates are shifted over accordingly circuit.h(qr) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr, 2) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_plot_partial_barrier(self): """Test plotting of partial barriers.""" filename = self._get_resource_path("test_latex_plot_partial_barriers.tex") # generate a circuit with barrier and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier(0) circuit.h(q[0]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_plot_barriers(self): """Test to see that plotting barriers works. If it is set to False, no blank columns are introduced""" filename1 = self._get_resource_path("test_latex_plot_barriers_true.tex") filename2 = self._get_resource_path("test_latex_plot_barriers_false.tex") # generate a circuit with barriers and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier() # check for other barrier like commands circuit.h(q[1]) # this import appears to be unused, but is actually needed to get snapshot instruction import qiskit.extensions.simulator # pylint: disable=unused-import circuit.snapshot("sn 1") # check the barriers plot properly when plot_barriers= True circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True) self.assertEqualToReference(filename1) circuit_drawer(circuit, filename=filename2, output="latex_source", plot_barriers=False) self.assertEqualToReference(filename2) def test_no_barriers_false(self): """Generate the same circuit as test_plot_barriers but without the barrier commands as this is what the circuit should look like when displayed with plot barriers false""" filename = self._get_resource_path("test_latex_no_barriers_false.tex") q1 = QuantumRegister(2, "q") c1 = ClassicalRegister(2, "c") circuit = QuantumCircuit(q1, c1) circuit.h(q1[0]) circuit.h(q1[1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_barrier_label(self): """Test the barrier label""" filename = self._get_resource_path("test_latex_barrier_label.tex") qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_big_gates(self): """Test large gates with params""" filename = self._get_resource_path("test_latex_big_gates.tex") qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2]) desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]]) circuit.unitary([[1, 0], [0, 1]], [qr[0]]) matrix = np.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]]) circuit = circuit.bind_parameters({theta: 1}) circuit.isometry(np.eye(4, 4), list(range(3, 5)), []) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cnot(self): """Test different cnot gates (ccnot, mcx, etc)""" filename = self._get_resource_path("test_latex_cnot.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]]) circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_pauli_clifford(self): """Test Pauli(green) and Clifford(blue) gates""" filename = self._get_resource_path("test_latex_pauli_clifford.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(0) circuit.z(0) circuit.id(0) circuit.h(1) circuit.cx(1, 2) circuit.cy(1, 2) circuit.cz(1, 2) circuit.swap(3, 4) circuit.s(3) circuit.sdg(3) circuit.iswap(3, 4) circuit.dcx(3, 4) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_u_gates(self): """Test U 1, 2, & 3 gates""" filename = self._get_resource_path("test_latex_u_gates.tex") from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(U1Gate(3 * pi / 2), [0]) circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1]) circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2]) circuit.append(CU1Gate(pi / 4), [0, 1]) circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3]) circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_creg_initial(self): """Test cregbundle and initial state options""" filename1 = self._get_resource_path("test_latex_creg_initial_true.tex") filename2 = self._get_resource_path("test_latex_creg_initial_false.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.h(0) circuit.x(1) circuit_drawer( circuit, filename=filename1, output="latex_source", cregbundle=True, initial_state=True ) self.assertEqualToReference(filename1) circuit_drawer( circuit, filename=filename2, output="latex_source", cregbundle=False, initial_state=False, ) self.assertEqualToReference(filename2) def test_r_gates(self): """Test all R gates""" filename = self._get_resource_path("test_latex_r_gates.tex") qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.r(3 * pi / 4, 3 * pi / 8, 0) circuit.rx(pi / 2, 1) circuit.ry(-pi / 2, 2) circuit.rz(3 * pi / 4, 3) circuit.rxx(pi / 2, 0, 1) circuit.ryy(3 * pi / 4, 2, 3) circuit.rzx(-pi / 2, 0, 1) circuit.rzz(pi / 2, 2, 3) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cswap_rzz(self): """Test controlled swap and rzz gates""" filename = self._get_resource_path("test_latex_cswap_rzz.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.x(1) circuit.cswap(0, 1, 2) circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_ghz_to_gate(self): """Test controlled GHZ to_gate circuit""" filename = self._get_resource_path("test_latex_ghz_to_gate.tex") qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) ghz_circuit = QuantumCircuit(3, name="Ctrl-GHZ Circuit") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="10") circuit.append(ccghz, [4, 0, 1, 3, 2]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_scale(self): """Tests scale See: https://github.com/Qiskit/qiskit-terra/issues/4179""" filename1 = self._get_resource_path("test_latex_scale_default.tex") filename2 = self._get_resource_path("test_latex_scale_half.tex") filename3 = self._get_resource_path("test_latex_scale_double.tex") circuit = QuantumCircuit(5) circuit.unitary(random_unitary(2**5), circuit.qubits) circuit_drawer(circuit, filename=filename1, output="latex_source") self.assertEqualToReference(filename1) circuit_drawer(circuit, filename=filename2, output="latex_source", scale=0.5) self.assertEqualToReference(filename2) circuit_drawer(circuit, filename=filename3, output="latex_source", scale=2.0) self.assertEqualToReference(filename3) def test_pi_param_expr(self): """Text pi in circuit with parameter expression.""" filename = self._get_resource_path("test_latex_pi_param_expr.tex") x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" filename = self._get_resource_path("test_latex_partial_layout.tex") circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, backend=FakeTenerife(), optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, ) circuit_drawer(transpiled, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_init_reset(self): """Test reset and initialize with 1 and 2 qubits""" filename = self._get_resource_path("test_latex_init_reset.tex") circuit = QuantumCircuit(2) circuit.initialize([0, 1], 0) circuit.reset(1) circuit.initialize([0, 1, 0, 0], [0, 1]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_iqx_colors(self): """Tests with iqx color scheme""" filename = self._get_resource_path("test_latex_iqx.tex") circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_reverse_bits(self): """Tests reverse_bits parameter""" filename = self._get_resource_path("test_latex_reverse_bits.tex") circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.ccx(2, 1, 0) circuit_drawer(circuit, filename=filename, output="latex_source", reverse_bits=True) self.assertEqualToReference(filename) def test_meas_condition(self): """Tests measure with a condition""" filename = self._get_resource_path("test_latex_meas_condition.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_inst_with_cbits(self): """Test custom instructions with classical bits""" filename = self._get_resource_path("test_latex_inst_with_cbits.tex") qinst = QuantumRegister(2, "q") cinst = ClassicalRegister(2, "c") inst = QuantumCircuit(qinst, cinst, name="instruction").to_instruction() qr = QuantumRegister(4, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]]) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cif_single_bit(self): """Tests conditioning gates on single classical bit""" filename = self._get_resource_path("test_latex_cif_single_bit.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[1], 0) circuit.x(qr[1]).c_if(cr[0], 1) circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_cif_single_bit_cregbundle(self): """Tests conditioning gates on single classical bit with cregbundle""" filename = self._get_resource_path("test_latex_cif_single_bit_bundle.tex") qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[1], 0) circuit.x(qr[1]).c_if(cr[0], 1) circuit_drawer(circuit, cregbundle=True, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_registerless_one_bit(self): """Text circuit with one-bit registers and registerless bits.""" filename = self._get_resource_path("test_latex_registerless_one_bit.tex") qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) circuit_drawer(circuit, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_measures_with_conditions(self): """Test that a measure containing a condition displays""" filename1 = self._get_resource_path("test_latex_meas_cond_false.tex") filename2 = self._get_resource_path("test_latex_meas_cond_true.tex") qr = QuantumRegister(2, "qr") cr1 = ClassicalRegister(2, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr1, cr2) circuit.h(0) circuit.h(1) circuit.measure(0, cr1[1]) circuit.measure(1, cr2[0]).c_if(cr1, 1) circuit.h(0).c_if(cr2, 3) circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_measures_with_conditions_with_bits(self): """Condition and measure on single bits cregbundle true""" filename1 = self._get_resource_path("test_latex_meas_cond_bits_false.tex") filename2 = self._get_resource_path("test_latex_meas_cond_bits_true.tex") bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source") circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source") self.assertEqualToReference(filename1) self.assertEqualToReference(filename2) def test_conditions_with_bits_reverse(self): """Test that gates with conditions and measures work with bits reversed""" filename = self._get_resource_path("test_latex_cond_reverse.tex") bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) circuit_drawer( circuit, cregbundle=False, reverse_bits=True, filename=filename, output="latex_source" ) self.assertEqualToReference(filename) def test_sidetext_with_condition(self): """Test that sidetext gates align properly with a condition""" filename = self._get_resource_path("test_latex_sidetext_condition.tex") qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_idle_wires_barrier(self): """Test that idle_wires False works with barrier""" filename = self._get_resource_path("test_latex_idle_wires_barrier.tex") circuit = QuantumCircuit(4, 4) circuit.x(2) circuit.barrier() circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source") self.assertEqualToReference(filename) def test_wire_order(self): """Test the wire_order option to latex drawer""" filename = self._get_resource_path("test_latex_wire_order.tex") qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 12) circuit_drawer( circuit, cregbundle=False, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7], filename=filename, output="latex_source", ) self.assertEqualToReference(filename) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/ColibrITD-SAS/mpqp
ColibrITD-SAS
"""The main object used to perform quantum computations in Qiskit is the ``QuantumCircuit``. Qiskit naturally supports OpenQASM 2.0 to instantiate a circuit. One can remark that few remote devices also support OpenQASM 3.0 code, this is not generalized yet to the whole library and device. We call the function :func:`qasm2_to_Qiskit_Circuit` to generate the circuit from the qasm code. """ from typing import TYPE_CHECKING from typeguard import typechecked if TYPE_CHECKING: from qiskit import QuantumCircuit @typechecked def qasm2_to_Qiskit_Circuit(qasm_str: str) -> "QuantumCircuit": """Converting a OpenQASM 2.0 code into a Qiskit QuantumCircuit. Args: qasm_str: A string representing the OpenQASM 2.0 code. Returns: A QuantumCircuit equivalent to the QASM code in parameter. """ from qiskit import QuantumCircuit return QuantumCircuit.from_qasm_str(qasm_str)
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg filename = './schrodin_yang.png' im = mpimg.imread(filename) fig, ax = plt.subplots() ax.imshow(im) from skimage.transform import resize n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) fig, ax = plt.subplots() ax.imshow(im) data = im[:,:,0].ravel() from qiskit_aqua.components.initial_states import Custom n_qubits = np.int_(np.log2(len(data))) init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs from copy import deepcopy circ_init = deepcopy(circ) circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_even = np.real(final_state_vector) n_rows = int(np.sqrt(len(edge_even))) edge_even = edge_even.reshape(n_rows, -1) edge_even[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_even) ax[1].imshow(im) def qft(c, q, n): """n-qubit QFT on q in c.""" for j in range(n): for k in range(j): c.cu1(pi/float(2**(j-k)), q[j], q[k]) c.h(q[j]) def iqft(c, q, n): """n-qubit IQFT on q in c.""" for j in range(n): for k in range(j): c.cu1(-pi/float(2**(j-k)), q[int(n-j-1)], q[int(n-k-1)]) c.h(q[int(n-j-1)]) def shiftBases(c, q, n, p): """Shift the register q by p positions""" iqft(c,q,n) for k in range(n): c.u1(-p*2*pi/float(2**(n-k)), q[int(n-k-1)]) qft(c,q,n) from qiskit import QuantumRegister, QuantumCircuit n = 2 q = QuantumRegister(n,'q') c = QuantumCircuit(q) iqft(c,q,n) shiftBases(c,q,n,1) qft(c,q,n) c.draw(output='mpl') circ = deepcopy(circ_init) qr = circ.qregs shiftBases(circ,qr[0],n_qubits,1) circ.h(qr[0][0]) shiftBases(circ,qr[0],n_qubits,-1) simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_odd = np.real(final_state_vector) n_rows = np.int_(np.sqrt(len(edge_odd))) edge_odd = edge_odd.reshape(n_rows, -1) edge_odd[:,1::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_odd) ax[1].imshow(im) edge = edge_even + edge_odd fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
# # your solution is here #
https://github.com/daimurat/qiskit-implementation
daimurat
import numpy as np import matplotlib.pyplot as plt # %matplotlib notebook from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import StateFn, PauliSumOp def generate_2qubit_qnn(label): circuit = QuantumCircuit(2) circuit.ry(np.pi / 4.0, 0) circuit.ry(np.pi / 4.0, 1) circuit.barrier() for i in range(2): if label[i] == 'x': circuit.rx(Parameter('theta'+str(i)), i) elif label[i] == 'y': circuit.ry(Parameter('theta'+str(i)), i) elif label[i] == 'z': circuit.rz(Parameter('theta'+str(i)), i) circuit.barrier() # Add CZ ladder. circuit.cz(0, 1) return circuit # # RealAmplitudesの場合 # from qiskit.circuit.library import RealAmplitudes # qc_test = RealAmplitudes(num_qubits=2, reps=1, # entanglement='linear').decompose() qc_test = generate_2qubit_qnn('xy') qc_test.draw('mpl') # 期待値の計算 from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.opflow import CircuitSampler from qiskit.opflow.expectations import PauliExpectation hamiltonian = PauliSumOp.from_list([('ZZ', 1.0)]) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(qc_test) aerpauli_basis = PauliExpectation().convert(expectation) quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'), shots = 32768) sampler = CircuitSampler(quantum_instance) # 期待値の評価 def calculate_exp_val(params): value_dict = dict(zip(qc_test.parameters, params)) result = sampler.convert(aerpauli_basis, params=value_dict).eval() return np.real(result) # コスト関数の可視化 X = np.linspace(0, 2*np.pi, 30) Y = np.linspace(0, 2*np.pi, 30) Z = np.array([[calculate_exp_val([x, y]) for x in X] for y in Y]).reshape(len(X), len(Y)) xx, yy = np.meshgrid(X, Y) fig = plt.figure(figsize=plt.figaspect(1)) ax = fig.add_subplot(projection="3d") ax.plot_surface(xx, yy, Z, cmap=plt.cm.jet) plt.show() from qiskit.opflow import Gradient gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) # 勾配の評価 def calculate_gradient(params): value_dict = dict(zip(qc_test.parameters, params)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() return np.real(result) # initial_point = 2*np.pi*np.random.random(qc_test.num_parameters) # アニメーション用初期値 initial_point = np.array([np.pi, 2.0]) from qiskit.algorithms.optimizers import GradientDescent gd_loss= [] xx_op= [] yy_op= [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) xx_op.append(x[0]) yy_op.append(x[1]) gd = GradientDescent(maxiter=100,learning_rate=0.05, callback=gd_callback) x_opt, fx_opt, nfevs = ( gd.optimize(initial_point.size, calculate_exp_val, gradient_function=calculate_gradient, initial_point=initial_point) ) from qiskit.algorithms.optimizers import SPSA spsa_loss= [] xx_op_spsa= [] yy_op_spsa= [] # コールバック処理の定義 def spsa_callback(nfevs, x, fx, stepsize, accepted): spsa_loss.append(fx) xx_op_spsa.append(x[0]) yy_op_spsa.append(x[1]) # インスタンス化 spsa = SPSA(maxiter=100,learning_rate=0.05,perturbation=0.05, callback=spsa_callback) # 最適化処理の実行 x_opt_spsa, fx_opt_spsa, nfevs_spsa = ( spsa.optimize(initial_point.size, calculate_exp_val, initial_point=initial_point) ) # from qiskit.opflow import NaturalGradient # ng = NaturalGradient().convert(expectation) # ng_in_pauli_basis = PauliExpectation().convert(ng) # def calculate_natural_gradient(params): # value_dict = dict(zip(qc_test.parameters, params)) # result = sampler.convert(ng_in_pauli_basis, params=value_dict).eval() # return np.real(result) # ngd_loss= [] # xx_op_ng= [] # yy_op_ng= [] # def ngd_callback(nfevs, x, fx, stepsize): # ngd_loss.append(fx) # xx_op_ng.append(x[0]) # yy_op_ng.append(x[1]) # qng = GradientDescent(maxiter=50,learning_rate=0.1, callback=ngd_callback) # x_opt_ng, fx_opt_ng, nfevs_ng = ( # qng.optimize(initial_point.size, # calculate_exp_val, # gradient_function=calculate_natural_gradient, # initial_point=initial_point) # ) # from qiskit.algorithms.optimizers import QNSPSA # qnspsa_loss = [] # xx_op_qnspsa= [] # yy_op_qnspsa= [] # def qnspsa_callback(nfev, x, fx, stepsize, accepted): # qnspsa_loss.append(fx) # xx_op_qnspsa.append(x[0]) # yy_op_qnspsa.append(x[1]) # fidelity = QNSPSA.get_fidelity(qc_test, # quantum_instance, # expectation=PauliExpectation()) # qnspsa = QNSPSA(fidelity, maxiter=50, learning_rate=0.1, # perturbation=0.1, # callback=qnspsa_callback) # x_opt_qnspsa, fx_opt_qnspsa, nfevs = qnspsa.optimize(initial_point.size, # calculate_exp_val, # initial_point=initial_point) from matplotlib.animation import FuncAnimation fig = plt.figure() ax = fig.add_subplot(projection="3d") ax.plot_surface(xx, yy, Z, cmap=plt.cm.jet, alpha=0.6) gd, = ax.plot([], [], [], '.-k', label='Gradient Descent') spsa, = ax.plot([], [], [], '.-r', label='SPSA') # ngd, = ax.plot([], [], [], '.-b', label='Quantum Natural Gradient') # spsa_ngd, = ax.plot([], [], [], '.-y', label='QN-SPSA') ax.set_xlabel('theta_1') ax.set_ylabel('theta_2') ax.set_zlabel('loss') def update(f): gd.set_data(xx_op[:f], yy_op[:f]) gd.set_3d_properties(gd_loss[:f]) spsa.set_data(xx_op_spsa[:f], yy_op_spsa[:f]) spsa.set_3d_properties(spsa_loss[:f]) # ngd.set_data(xx_op_ng[:f], yy_op_ng[:f]) # ngd.set_3d_properties(ngd_loss[:f]) # spsa_ngd.set_data(xx_op_qnspsa[:f], yy_op_qnspsa[:f]) # spsa_ngd.set_3d_properties(qnspsa_loss[:f]) anim = FuncAnimation(fig, update, interval=200) plt.legend(loc='upper left') plt.show() # 結果のプロット plt.figure(figsize=(7, 3)) plt.plot(gd_loss, 'C0', label='vanilla gradient descent') plt.plot(spsa_loss, 'C0', ls='--', label='SPSA') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plt.show() anim.save("spsa.gif") import qiskit.tools.jupyter %qiskit_version_table
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGLongestPath from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestDAGLongestPathPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag longest path of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGLongestPath() pass_.run(dag) self.assertListEqual(pass_.property_set["dag_longest_path"], []) def test_nonempty_dag_false(self): """Test the dag longest path non-empty dag. path length = 11 = 9 ops + 2 qubits at start and end of path """ # ┌───┐┌───┐┌───┐ # q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■── # ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐ # q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├ # └───┘ └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) circuit.y(qr[1]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGLongestPath() pass_.run(dag) self.assertEqual(len(pass_.property_set["dag_longest_path"]), 11) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test library of phase estimation circuits.""" import unittest import numpy as np from qiskit.test.base import QiskitTestCase from qiskit import BasicAer, execute from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PhaseEstimation, QFT from qiskit.quantum_info import Statevector class TestPhaseEstimation(QiskitTestCase): """Test the phase estimation circuit.""" def assertPhaseEstimationIsCorrect( self, pec: QuantumCircuit, eigenstate: QuantumCircuit, phase_as_binary: str ): r"""Assert that the phase estimation circuit implements the correct transformation. Applying the phase estimation circuit on a target register which holds the eigenstate :math:`|u\rangle` (say the last register), the final state should be .. math:: |\phi_1\rangle \cdots |\phi_t\rangle |u\rangle where the eigenvalue is written as :math:`e^{2\pi i \phi}` and the angle is represented in binary fraction, i.e. :math:`\phi = 0.\phi_1 \ldots \phi_t`. Args: pec: The circuit implementing the phase estimation circuit. eigenstate: The eigenstate as circuit. phase_as_binary: The phase of the eigenvalue in a binary fraction. E.g. if the phase is 0.25, the binary fraction is '01' as 0.01 = 0 * 0.5 + 1 * 0.25 = 0.25. """ # the target state eigenstate_as_vector = Statevector.from_instruction(eigenstate).data reference = eigenstate_as_vector zero, one = [1, 0], [0, 1] for qubit in phase_as_binary[::-1]: reference = np.kron(reference, zero if qubit == "0" else one) # the simulated state circuit = QuantumCircuit(pec.num_qubits) circuit.compose( eigenstate, list(range(pec.num_qubits - eigenstate.num_qubits, pec.num_qubits)), inplace=True, ) circuit.compose(pec, inplace=True) # TODO use Statevector for simulation once Qiskit/qiskit-terra#4681 is resolved # actual = Statevector.from_instruction(circuit).data backend = BasicAer.get_backend("statevector_simulator") actual = execute(circuit, backend).result().get_statevector() np.testing.assert_almost_equal(reference, actual) def test_phase_estimation(self): """Test the standard phase estimation circuit.""" with self.subTest("U=S, psi=|1>"): unitary = QuantumCircuit(1) unitary.s(0) eigenstate = QuantumCircuit(1) eigenstate.x(0) # eigenvalue is 1j = exp(2j pi 0.25) thus phi = 0.25 = 0.010 = '010' # using three digits as 3 evaluation qubits are used phase_as_binary = "0100" pec = PhaseEstimation(4, unitary) self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary) with self.subTest("U=SZ, psi=|11>"): unitary = QuantumCircuit(2) unitary.z(0) unitary.s(1) eigenstate = QuantumCircuit(2) eigenstate.x([0, 1]) # eigenvalue is -1j = exp(2j pi 0.75) thus phi = 0.75 = 0.110 = '110' # using three digits as 3 evaluation qubits are used phase_as_binary = "110" pec = PhaseEstimation(3, unitary) self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary) with self.subTest("a 3-q unitary"): # ┌───┐ # q_0: ┤ X ├──■────■─────── # ├───┤ │ │ # q_1: ┤ X ├──■────■─────── # ├───┤┌───┐┌─┴─┐┌───┐ # q_2: ┤ X ├┤ H ├┤ X ├┤ H ├ # └───┘└───┘└───┘└───┘ unitary = QuantumCircuit(3) unitary.x([0, 1, 2]) unitary.cz(0, 1) unitary.h(2) unitary.ccx(0, 1, 2) unitary.h(2) # ┌───┐ # q_0: ┤ H ├──■────■── # └───┘┌─┴─┐ │ # q_1: ─────┤ X ├──┼── # └───┘┌─┴─┐ # q_2: ──────────┤ X ├ # └───┘ eigenstate = QuantumCircuit(3) eigenstate.h(0) eigenstate.cx(0, 1) eigenstate.cx(0, 2) # the unitary acts as identity on the eigenstate, thus the phase is 0 phase_as_binary = "00" pec = PhaseEstimation(2, unitary) self.assertPhaseEstimationIsCorrect(pec, eigenstate, phase_as_binary) def test_phase_estimation_iqft_setting(self): """Test default and custom setting of the QFT circuit.""" unitary = QuantumCircuit(1) unitary.s(0) with self.subTest("default QFT"): pec = PhaseEstimation(3, unitary) expected_qft = QFT(3, inverse=True, do_swaps=False) self.assertEqual( pec.decompose().data[-1].operation.definition, expected_qft.decompose() ) with self.subTest("custom QFT"): iqft = QFT(3, approximation_degree=2).inverse() pec = PhaseEstimation(3, unitary, iqft=iqft) self.assertEqual(pec.decompose().data[-1].operation.definition, iqft.decompose()) if __name__ == "__main__": unittest.main()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import random for n in range(5): print('Flip '+str(n+1)) if random.random()<0.5: print('HEADS\n') else: print('TAILS\n') import time for n in range(5): t = str(time.time()) print('Flip '+str(n+1)+' (system time = ' + t + ')') if int(t[-1])%2==0: print('HEADS\n') else: print('TAILS\n') from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) circ = QuantumCircuit(q, c) circ.h(q) circ.measure(q, c) from qiskit import BasicAer, execute backend = BasicAer.get_backend('qasm_simulator') job = execute(circ, backend, shots=5, memory=True) data = job.result().get_memory() print(data) for output in data: print('Flip with output bit value ' +output) if output=='0': print('HEADS\n') else: print('TAILS\n') from qiskit import IBMQ IBMQ.load_accounts() backend = IBMQ.get_backend('ibmq_5_tenerife') job = execute(circ, backend, shots=5, memory=True) for output in job.result().get_memory(): print('Flip with output bit value ' +output) if output=='0': print('HEADS\n') else: print('TAILS\n') job.result().get_memory() n = 3 q = QuantumRegister(n) c = ClassicalRegister(n) circ = QuantumCircuit(q, c) for j in range(n): circ.h(q[j]) circ.measure(q,c) job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=8192) # get the histogram of bit string results, convert it to one of integers and plot it bit_counts = job.result().get_counts() int_counts = {} for bitstring in bit_counts: int_counts[ int(bitstring,2) ] = bit_counts[bitstring] from qiskit.tools.visualization import plot_histogram plot_histogram(int_counts) q = QuantumRegister(n) c = ClassicalRegister(n) circ = QuantumCircuit(q, c) for j in range(n): circ.rx(3.14159/(2.5+j),q[j]) circ.measure(q,c) job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=8192) bit_counts = job.result().get_counts() int_counts = {} for bitstring in bit_counts: int_counts[ int(bitstring,2) ] = bit_counts[bitstring] plot_histogram(int_counts) job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=10, memory=True) data = job.result().get_memory() print(data) int_data = [] for bitstring in data: int_data.append( int(bitstring,2) ) print(int_data)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
n1,n2,n3 = 3,-4,6 print(n1,n2,n3) r1 = (2 * n1 + 3 * n2)*2 - 5 *n3 print(r1) n1,n2,n3 = 3,-4,6 up = (n1-n2) * (n2-n3) down = (n3-n1) * (n3+1) result = up/down print (result) N = "Abuzer" S = "Yakaryilmaz" print("hello from the quantum world to",N,S)
https://github.com/Qiskit/qiskit-qasm3-import
Qiskit
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license # in the LICENSE.txt file in the root directory of this source tree or at # http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this copyright notice, and modified # files need to carry a notice indicating that they have been altered from the originals. import openqasm3 from qiskit import QuantumCircuit from .converter import ConvertVisitor def convert(node: openqasm3.ast.Program) -> QuantumCircuit: """Convert a parsed OpenQASM 3 program in AST form, into a Qiskit :class:`~qiskit.circuit.QuantumCircuit`.""" return ConvertVisitor().convert(node).circuit def parse(string: str, /) -> QuantumCircuit: """Wrapper around :func:`.convert`, which first parses the OpenQASM 3 program into AST form, and then converts the output to Qiskit format.""" return convert(openqasm3.parse(string))
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/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/qiskit-community/qiskit-aqt-provider
qiskit-community
# This code is part of Qiskit. # # (C) Copyright Alpine Quantum Technologies GmbH 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. from collections.abc import Iterator, Mapping from typing import Any, Optional import annotated_types import pydantic as pdt from typing_extensions import Self, override class AQTOptions(pdt.BaseModel, Mapping[str, Any]): """Options for AQT resources. This is a typed drop-in replacement for :class:`qiskit.providers.Options`. Options can be set on a backend globally or on a per-job basis. To update an option globally, set the corresponding attribute in the backend's :attr:`options <qiskit_aqt_provider.aqt_resource._ResourceBase.options>` attribute: >>> import qiskit >>> from qiskit_aqt_provider import AQTProvider >>> >>> backend = AQTProvider("").get_backend("offline_simulator_no_noise") >>> >>> qc = qiskit.QuantumCircuit(1) >>> _ = qc.rx(3.14, 0) >>> _ = qc.measure_all() >>> qc = qiskit.transpile(qc, backend) >>> >>> backend.options.shots = 50 >>> result = backend.run(qc).result() >>> sum(result.get_counts().values()) 50 Option overrides can also be applied on a per-job basis, as keyword arguments to :meth:`AQTResource.run <qiskit_aqt_provider.aqt_resource.AQTResource.run>` or :meth:`AQTDirectAccessResource.run <qiskit_aqt_provider.aqt_resource.AQTDirectAccessResource.run>`: >>> backend.options.shots 50 >>> result = backend.run(qc, shots=100).result() >>> sum(result.get_counts().values()) 100 """ model_config = pdt.ConfigDict(extra="forbid", validate_assignment=True) # Qiskit generic: shots: int = pdt.Field(ge=1, le=2000, default=100) """Number of repetitions per circuit.""" memory: bool = False """Whether to return the sequence of memory states (readout) for each shot. See :meth:`qiskit.result.Result.get_memory` for details.""" # AQT-specific: query_period_seconds: float = pdt.Field(ge=0.1, default=1.0) """Elapsed time between queries to the cloud portal when waiting for results, in seconds.""" query_timeout_seconds: Optional[float] = None """Maximum time to wait for results of a single job, in seconds.""" with_progress_bar: bool = True """Whether to display a progress bar when waiting for results from a single job. When enabled, the progress bar is written to :data:`sys.stderr`. """ @pdt.field_validator("query_timeout_seconds") @classmethod def validate_timeout(cls, value: Optional[float], info: pdt.ValidationInfo) -> Optional[float]: """Enforce that the timeout, if set, is strictly positive.""" if value is not None and value <= 0.0: raise ValueError(f"{info.field_name} must be None or > 0.") return value def update_options(self, **kwargs: Any) -> Self: """Update options by name. .. tip:: This is exposed for compatibility with :class:`qiskit.providers.Options`. The preferred way of updating options is by direct (validated) assignment. """ update = self.model_dump() update.update(kwargs) for key, value in self.model_validate(update).model_dump().items(): setattr(self, key, value) return self # Mapping[str, Any] implementation, for compatibility with qiskit.providers.Options @override def __len__(self) -> int: """Number of options.""" return len(self.model_fields) @override def __iter__(self) -> Iterator[Any]: # type: ignore[override] """Iterate over option names.""" return iter(self.model_fields) @override def __getitem__(self, name: str) -> Any: """Get the value for a given option.""" return self.__dict__[name] # Convenience methods @classmethod def max_shots(cls) -> int: """Maximum number of repetitions per circuit.""" for metadata in cls.model_fields["shots"].metadata: if isinstance(metadata, annotated_types.Le): return int(str(metadata.le)) if isinstance(metadata, annotated_types.Lt): # pragma: no cover return int(str(metadata.lt)) - 1 raise ValueError("No upper bound found for 'shots'.") # pragma: no cover class AQTDirectAccessOptions(AQTOptions): """Options for AQT direct-access resources.""" shots: int = pdt.Field(ge=1, le=200, default=100) """Number of repetitions per circuit."""
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl')
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
Juan-Varela11
import warnings from qiskit.tools.jupyter import * from qiskit import IBMQ from qiskit import assemble from qiskit import pulse from qiskit.pulse import pulse_lib import numpy as np import matplotlib.pyplot as plt warnings.filterwarnings('ignore') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-internal',group='dev-qiskit') backend = provider.get_backend('ibmq_johannesburg') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support OpenPulse" backend_defaults = backend.defaults() dt = backend_config.dt print(f"Sampling time: {dt} ns") # The configuration returns dt in seconds cmd_def = pulse.CmdDef.from_defaults(backend.defaults().cmd_def, backend.defaults().pulse_library) qubit = 0 x_gate = cmd_def.get('u3', [qubit], P0=np.pi, P1=0.0, P2=np.pi) measure_gate = cmd_def.get('measure', qubits=backend_config.meas_map[qubit]) drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) measure_time = 40 schedule = pulse.Schedule(name='Distribution Comparisons') schedule += x_gate schedule += measure_gate << measure_time schedule.draw(plot_range=[0,150],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=10.0) meas_schedule = pulse.Schedule(name='Distribution Comparisons') meas_schedule += cmd_def.get('measure', qubits=backend_config.meas_map[qubit]) << measure_time meas_schedule.draw(plot_range=[0,150],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0) num_shots_per_frequency = 8192 readout_cal = assemble([schedule,meas_schedule], backend=backend, meas_level=1, meas_return='single', shots=num_shots_per_frequency) job = backend.run(readout_cal) print (job.job_id()) distribution_compare = backend.retrieve_job('5e2f6ca31663de0019d01c3a') distribution_compare_result = distribution_compare.result(timeout=3600) ground = [shot[0] for shot in distribution_compare_result.get_memory(1)] excited = [shot[0] for shot in distribution_compare_result.get_memory(0)] plt.figure(figsize=(10,10)) plt.scatter(np.real(ground)/1e15, np.imag(ground)/1e15,s=5, cmap='viridis', c='grey',alpha=1.0, label='state_0_mean') plt.scatter(np.real(excited)/1e15, np.imag(excited)/1e15,s=5, cmap='viridis', c='blue',alpha=1.0, label='state_1_mean') plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.legend(["|0>","|1>"],fontsize=25) plt.show() mean_gnd = np.mean(ground) # takes mean of both real and imaginary parts mean_exc = np.mean(excited) import math def classify(point: complex): """Classify the given state as |0> or |1>.""" def distance(a, b): return math.sqrt((np.real(a) - np.real(b))**2 + (np.imag(a) - np.imag(b))**2) return int(distance(point, mean_exc) < distance(point, mean_gnd)) fidelity_g = [] fidelity_e = [] for i in range(len(excited)): fidelity_g.append(classify(ground[i])) fidelity_e.append(classify(excited[i])) def get_closest_multiple_of_16(num): return (int(num) - (int(num)%16)) # Find out which group of qubits need to be acquired with this qubit meas_map_idx = None for i, measure_group in enumerate(backend_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" meas_samples_us = 4.0 meas_sigma_us = 1.0 # The width of the gaussian part of the rise and fall meas_risefall_us = 0.1 # and the truncating parameter: how many samples to dedicate to the risefall meas_samples = get_closest_multiple_of_16(meas_samples_us * 1e-6/dt) meas_sigma = get_closest_multiple_of_16(meas_sigma_us * 1e-6/dt) # The width of the gaussian part of the rise and fall meas_risefall = get_closest_multiple_of_16(meas_risefall_us * 1e-6/dt) meas_amp = 0.2 acq_cmd = pulse.Acquire(duration=meas_samples) meas_pulse = pulse_lib.gaussian_square(duration=meas_samples, sigma=meas_sigma, amp=meas_amp, risefall=meas_risefall, name='measurement_pulse') measure_schedule = meas_pulse(meas_chan)<<measure_time measure_schedule += acq_cmd([pulse.AcquireChannel(i) for i in backend_config.meas_map[meas_map_idx]], [pulse.MemorySlot(i) for i in backend_config.meas_map[meas_map_idx]]) measure_schedule.draw(plot_range=[0,1250],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0) schedule = pulse.Schedule(name='Readout_Discrim') schedule += x_gate schedule += measure_schedule << measure_time schedule.draw(plot_range=[0,1250],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0) num_shots_per_frequency = 8192 readout_cal = assemble([schedule,measure_schedule], backend=backend, meas_level=1, meas_return='single', shots=num_shots_per_frequency) job = backend.run(readout_cal) print (job.job_id()) readout_tune = backend.retrieve_job('5e2f6d496d9b6d001c2cd56b') #amp is 0.2 4us pulse readout_tune_result = readout_tune.result(timeout=3600) ground = [shot[0] for shot in readout_tune_result.get_memory(1)] excited = [shot[0] for shot in readout_tune_result.get_memory(0)] plt.figure(figsize=(10,10)) plt.scatter(np.real(ground)/1e15, np.imag(ground)/1e15,s=5, cmap='viridis', c='grey',alpha=1.0, label='state_0_mean') plt.scatter(np.real(excited)/1e15, np.imag(excited)/1e15,s=5, cmap='viridis', c='blue',alpha=1.0, label='state_1_mean') plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.legend(["|0>","|1>"],fontsize=25) plt.show() mean_gnd = np.mean(ground) # takes mean of both real and imaginary parts mean_exc = np.mean(excited) fidelity_g = [] fidelity_e = [] for i in range(len(excited)): fidelity_g.append(classify(ground[i])) fidelity_e.append(classify(excited[i])) print (np.sum(fidelity_g)/len(fidelity_g)) print (np.sum(fidelity_e)/len(fidelity_e)) GHz = 1.0e9 MHz = 1.0e6 # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.meas_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 2 * MHz # in steps of 1 MHz. frequency_step_Hz = 0.1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min, frequency_max, frequency_step_Hz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") qubit = 0 x_gate = cmd_def.get('u3', [qubit], P0=np.pi, P1=0.0, P2=np.pi) measure_gate = cmd_def.get('measure', qubits=backend_config.meas_map[qubit]) schedule0 = pulse.Schedule(name='Readout Frequency sweep') schedule0 += measure_gate <<measure_time schedule1 = pulse.Schedule(name='Readout Frequency sweep') schedule1 += x_gate schedule1 += measure_gate <<measure_time schedule_frequencies = [{meas_chan: freq} for freq in frequencies_GHz] schedule1.draw(plot_range=[0,100],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0) num_shots_per_frequency = 8192 ground_resonator_freq_sweep = assemble(schedule0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_frequencies) job = backend.run(ground_resonator_freq_sweep) print (job.job_id()) num_shots_per_frequency = 8192 excited_resonator_freq_sweep = assemble(schedule1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_frequencies) job = backend.run(excited_resonator_freq_sweep) print (job.job_id()) # chi_test_codes = ["5e2f1fbf3648b10018931256","5e2f1fc56840bc0018a436f6"] #codes for singapore backend # chi_test_codes = ["5e2f2cd851c04c0018c7d86d","5e2f2cdaf5a50800187c237d"] #codes for johannesburg backend # chi_test_codes = ["5e2f2d8df5a50800187c2380","5e2f2d9051c04c0018c7d877"] #codes for johannesburg backend # chi_test_codes = ["5e2f302f6840bc0018a437a0","5e2f30323648b10018931300"] #codes for johannesburg backend chi_test_codes = ["5e2f3e9151c04c0018c7d91a","5e2f3e94c4ffc4001882be47"] #codes for johannesburg backend qubit=0 all_vals = [] for i in range(len(chi_test_codes)): sweep_values = [] job = backend.retrieve_job(chi_test_codes[i]) frequency_sweep_results = job.result(timeout=120) for j in range(len(frequency_sweep_results.results)): res = frequency_sweep_results.get_memory(j) sweep_values.append(res[qubit]) all_vals.append(sweep_values) plt.figure(figsize=(10,5)) for i in range(len(chi_test_codes)): plt.plot(frequencies_GHz, all_vals[i],"*--") plt.axvline(center_frequency_Hz) plt.legend(["|0>","|1>"],fontsize=15) plt.show()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/QPower-Research/QPowerAlgo
QPower-Research
#!pip install qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute, dagcircuit import numpy as np from qiskit.visualization import plot_histogram from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister """ we need to input how many steps the quantum system will take in total similar to CRW if no of qubits is n then then the graph will have 2^(n-1) nodes or points to shift. here the first qubit will play the role of coin as in CRW. """ n_steps = 1 #Number of iterations qubits= QuantumRegister(4, name = 'qubits') cbits= ClassicalRegister(4, name= 'cbits') #increment gate print(len(qubits)) inc = QuantumCircuit (qubits,name='inc') #Circuit for inc operator inc.rcccx( qubits[0],qubits[1],qubits[2],qubits[3]) inc.ccx(qubits[0],qubits[1],qubits[2]) inc.cx(qubits[0],qubits[1]) inc.draw() inc= inc.to_instruction() #decrement gate dec= QuantumCircuit (qubits,name='dec') #Circuit for dec operator dec.x(qubits[0]) dec.x(qubits[1]) dec.x(qubits[2]) dec.rcccx( qubits[0],qubits[1],qubits[2],qubits[3]) dec.x(qubits[2]) dec.ccx(qubits[0],qubits[1],qubits[2]) dec.x(qubits[1]) dec.cx(qubits[0],qubits[1]) dec.x(qubits[0]) dec.draw() dec= dec.to_instruction() #Main Circuit circ = QuantumCircuit (qubits, cbits) #Main circuit #Fixing the coin spin either 0 or 1 #circ.x(qubits[0]) for i in range(n_steps): circ.h (qubits[0]) #Coin step circ.append (inc, [qubits[0],qubits[1],qubits[2],qubits[3]]) #Shift step circ.append (dec, [qubits[0],qubits[1],qubits[2],qubits[3]]) #Shift step circ.measure ([qubits[0],qubits[1],qubits[2],qubits[3]], [cbits[0],cbits[1],cbits[2],cbits[3]]) # Draw the circuit circ.draw() simulator = Aer.get_backend('qasm_simulator') job = execute(circ, simulator, shots=1000) result = job.result() counts = result.get_counts(circ) print("\nTotal counts are:",counts) # Plot a histogram plot_histogram(counts)
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer import AerSimulator from qiskit.circuit.library import TwoLocal from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import EfficientSU2 # opflow is Qiskit's module for creating operators like yours from qiskit import * from qiskit.opflow import OperatorBase from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity import pylab import matplotlib.pyplot as plt import numpy as np %matplotlib inline counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) def run(B_X = 1, J_z = 1, B_Z = 1): master_counts = [] master_values = [] # for h in range (1,5,1): # h=+h # Initialization B_X = B_X J_z = J_z B_Z = B_Z # or whatever value you have for h H = - B_X * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) + J_z * ((Z ^ Z ^ I ^ I ) + (I ^ Z ^ Z ^ I) + (I ^ I ^ Z ^ Z) + (Z ^ I ^ I ^ Z)) - B_Z * ((Z ^ I ^ I ^ I) + (I ^ Z ^ I ^ I) + (I ^ I ^ Z ^ I ) + (I ^ I ^ I ^ Z)) # you can swap this for a real quantum device and keep the rest of the code the same! backend = QasmSimulator() # COBYLA usually works well for small problems like this one optimizer = COBYLA(maxiter=200) # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library ansatz = EfficientSU2(4, reps=1) # set the algorithm vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result) # run it with the Hamiltonian we defined above result = vqe.compute_minimum_eigenvalue(H) # print the result (it contains lot's of information) # print(result) run() plt.figure(figsize=(15,15)) plt.plot(counts,values) plt.xlabel('optimization step') plt.ylabel('E') plt.show() import pickle counts_values = {} for i in range(0, 20, 1): for j in range(0, 20, 1): print(f"Running VQE for BX : {i/10} & BZ : {j/10}") counts = [] values = [] run(B_X = i/10, J_z = 1, B_Z = j/10) counts_values[f"BX_{i/10} BZ_{j/10}"] = {"counts": counts, "values": values} print("Saving Optimization History") with open('optimization_data.pickle', 'wb') as handle: pickle.dump(counts_values, handle, protocol=pickle.HIGHEST_PROTOCOL) with open('optimization_data.pickle', 'rb') as handle: counts_values = pickle.load(handle) data = [] for keys, values in counts_values.items(): data += dict( [ zip(values['counts'], values['values']) ] ) # arr = np.asarray(data) # print(data) # importing libraries from mpl_toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt # defining surface and axes x = np.outer(np.linspace(-2, 2, 10), np.ones(10)) y = x.copy().T z = np.cos(x ** 2 + y ** 3) fig = plt.figure(figsize=(15,15)) # syntax for 3-D plotting ax = plt.axes(projection ='3d') # syntax for plotting ax.plot_surface(x, y, z, cmap ='viridis', edgecolor ='green') ax.set_title('Surface plot geeks for geeks') plt.show() x[3] # for x in data: # print(len(x)) data
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,3),"b=",round(b,3)) print("a*a=",round(a**2,3),"b*b=",round(b**2,3)) print() mycircuit.ry(2*theta,qreg[0]) # creating an entanglement between the second and third qubits mycircuit.h(qreg[1]) mycircuit.cx(qreg[1],qreg[2]) # CNOT operator by Asja on her qubits where the first qubit is the control qubit mycircuit.cx(qreg[0],qreg[1]) # Hadamard operator by Asja on the first qubit mycircuit.h(qreg[0]) # measurement done by Asja mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) # read the state vector job = execute(mycircuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit) print("the state vector is") for i in range(len(current_quantum_state)): print(current_quantum_state[i].real) print() # reverse the order def get_state(i): if i==0: return "000" if i==1: return "100" if i==2: return "010" if i==3: return "110" if i==4: return "001" if i==5: return "101" if i==6: return "011" if i==7: return "111" balvis_state = "" for i in range(len(current_quantum_state)): if current_quantum_state[i].real!=0: if abs(current_quantum_state[i].real-a)<0.000001: balvis_state += "+a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+a)<0.000001: balvis_state += "-a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real-b)<0.000001: balvis_state += "+b|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+b)<0.000001: balvis_state += "-b|"+ get_state(i)+">" print("which is",balvis_state) mycircuit.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from . import circuit_constructor, circuit_eq def test_circuit_constructor(): gates_list = ["h", "hs", "hs", "i", "i", "h"] result = circuit_constructor(gates_list) result_dag = circuit_constructor(gates_list, True) expected = QuantumCircuit(6) expected.h(0) _ = expected.s(1), expected.h(1) _ = expected.s(2), expected.h(2) expected.h(5) expected_dag = QuantumCircuit(6) expected_dag.h(0) _ = expected_dag.h(1), expected_dag.sdg(1) _ = expected_dag.h(2), expected_dag.sdg(2) expected_dag.h(5) assert circuit_eq(result, expected) assert circuit_eq(result_dag, expected_dag)
https://github.com/MAI-cyber/QIT
MAI-cyber
# ! pip install qiskit # ! pip install numpy from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit.quantum_info import Statevector import numpy as np ground_state = np.array([1, 0]) excited_state = np.array([0, 1]) # Making an arbitary state alpha = 2+ 4j beta = -2 normalization_factor = np.sqrt(abs(alpha**2)+ abs(beta**2)) arbitrary_state = np.array([alpha, beta]) / normalization_factor print("ground_state=", ground_state) print("excited_state=", excited_state) print("Arbitary_state=", arbitrary_state) plot_bloch_multivector(ground_state) plot_bloch_multivector(excited_state) plot_bloch_multivector(arbitrary_state) # Defining the matrices I_matrix = np.identity(2) Pauli_x = np.array([[0, 1], [1, 0]]) Pauli_y = np.array([[0, -1j], [1j, 0]]) Pauli_z = np.array([[1, 0], [0, 1]]) Hadamard_transform = np.sqrt(1/2) * np.array([[1, 1], [1, -1]]) print("\n Identity Matrix \n" , I_matrix ) print("\n Pauli X \n" , Pauli_x ) print("\n Pauli Y \n" , Pauli_y ) print("\n Pauli Z \n" , Pauli_z ) print("\n Hadamard Transform \n" , Hadamard_transform ) plus_state = np.dot(Hadamard_transform, ground_state) plot_bloch_multivector(plus_state) # Defining the Quantum Circuit with a Quantum Register of size 1 quantum_circuit = QuantumCircuit(1) # Applyign the hadamrad gate to the first Qubit quantum_circuit.h(0) # Measuring the Circuit #quantum_circuit.measure(0,0) # DRwaing the quantum circuit quantum_circuit.draw('mpl') initial_state = Statevector.from_label('0') plot_bloch_multivector(initial_state) evolved_state = initial_state.evolve(quantum_circuit) plot_bloch_multivector(evolved_state) backend=Aer.get_backend('qasm_simulator') counts = execute(quantum_circuit,backend, shots = 10).result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.mappers.second_quantization import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(2) from qiskit_nature.second_q.mappers import LogarithmicMapper mapper = LogarithmicMapper(padding=2) from qiskit_nature.circuit.library import HartreeFock from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) from qiskit_nature.second_q.circuit.library import HartreeFock from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter converter = QubitConverter(JordanWignerMapper()) init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter) print(init_state.draw()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['mathtext.fontset'] = 'stix' matplotlib.rcParams['font.family'] = 'STIXGeneral' width=0.75 color='black' fontsize=28 ticksize=22 figsize=(10,8) def f_x(x): return np.arctan(x) phase = True nx = 5 nintx = 3 npresx = nx - nintx if phase: npresx -= 1 xmin = -2.**(nintx) xmax = 2.**(nintx) - 2.**(-npresx) xs = np.linspace(xmin,xmax,2**nx) print(xmin, xmax) print(npresx,qt.get_npres(xs)) m = 3 bounds = np.linspace(xmin, xmax, (2**m)) norder = 1 coeffs = qt.get_bound_coeffs(f_x, bounds, norder, reterr=False).T ys = qt.piecewise_poly(xs, coeffs.T, bounds) fig = plt.figure(figsize=figsize) ax = fig.gca() for bound in bounds: ax.axvline(bound, ls=':', color='black') ax.plot(xs, f_x(xs), color='black'); ax.plot(xs, ys, color='black', ls='--', lw=3); ax.set_xlabel(r'$x$', fontsize=fontsize); ax.set_ylabel(r'$f(x)$', fontsize=fontsize); ax.set_xlim(xmin,xmax); ax.tick_params(axis='both', labelsize=ticksize); # The number of integer bits of A1, A0 and the result nint0 = qt.get_nint(coeffs[0]) nint1 = qt.get_nint(coeffs[1]) nint = nintx + nint0 # The number of precision bits of A1, A0 and the result npres0 = qt.get_npres(coeffs[0]) npres1 = qt.get_npres(coeffs[1]) npres = npresx + npres0 # The total number of bits of A1, A0 and the result n0 = npres0 + nint0 + 1 n1 = npres1 + nint1 + 1 n = npres + nint + 1 print('A0 bits:', n0) print('A1 bits:', n1) print('Result bits:', n) nsig0, nsig1 = 5, 5 coeffs[0] = qt.round_sig(coeffs[0], nsig0) coeffs[1] = qt.round_sig(coeffs[1], nsig1) # The number of integer bits of A1, A0 and the result nint0 = qt.get_nint(coeffs[0]) nint1 = qt.get_nint(coeffs[1]) nint = nintx + nint0 # The number of precision bits of A1, A0 and the result npres0 = qt.get_npres(coeffs[0]) npres1 = qt.get_npres(coeffs[1]) npres = npresx + npres0 # The total number of bits of A1, A0 and the result n0 = npres0 + nint0 + 1 n1 = npres1 + nint1 + 1 n = npres + nint + 1 print('A0 bits:', n0) print('A1 bits:', n1) print('Result bits:', n) npres0, npres1 = 4, 4 n0 = npres0 + nint0 + 1 n1 = npres1 + nint1 + 1 rcoeffs = [] for coeff in coeffs[0]: # Convert coefficient to binary string of new length n0, then calculate the corresponding decimal value rcoeff = qt.bin_to_dec(qt.my_binary_repr(coeff, n0, nint=nint0, phase=phase), nint=nint0, phase=phase) rcoeffs.append(rcoeff) coeffs[0] = np.array(rcoeffs) # Calculate the differences between the f(x) and A1x over all x fdifs = f_x(xs) - qt.piecewise_poly(xs, np.array([coeffs[0],np.zeros(len(coeffs[1]))]).T, bounds) coeffs_ = [] bounds__ = bounds bounds__[-1] = np.inf for i in np.arange(len(bounds__))[:-1]: # Calculate the mean differences in each domain to be the new bias A0 coeffs_.append(np.mean(fdifs[np.greater_equal(xs,bounds__[i])&np.greater(bounds__[i+1],xs)])) coeffs[1] = np.array(coeffs_) nint1 = qt.get_nint(coeffs[1]) print(nint1) rcoeffs = [] for coeff in coeffs[1]: # Convert coefficient to binary string of new length n1, then calculate the corresponding decimal value rcoeff = qt.bin_to_dec(qt.my_binary_repr(coeff, n1, nint=nint1, phase=phase), nint=nint1, phase=phase) rcoeffs.append(rcoeff) coeffs[1] = np.array(rcoeffs) # The number of integer bits of A1, A0 and the result nint0 = qt.get_nint(coeffs[0]) nint1 = qt.get_nint(coeffs[1]) nint = nintx + nint0 # The number of precision bits of the result npres = npresx + npres0 # The total number of bits of A1, A0 and the result n0 = npres0 + nint0 + 1 n1 = npres1 + nint1 + 1 n = npres + nint + 1 print('A0 bits:', n0) print('A1 bits:', n1) print('Result bits:', n) ys_rnd = qt.piecewise_poly(xs, coeffs.T, bounds) fig = plt.figure(figsize=figsize) ax = fig.gca() for bound in bounds: ax.axvline(bound, ls=':', color='black') ax.plot(xs, f_x(xs), color='black'); ax.plot(xs, ys, color='black', ls='--', lw=3); ax.plot(xs, ys_rnd, color='black', ls=':', lw=3); ax.set_xlabel(r'$x$', fontsize=fontsize); ax.set_ylabel(r'$f(x)$', fontsize=fontsize); ax.set_xlim(xmin,xmax); ax.tick_params(axis='both', labelsize=ticksize); A1x = qt.piecewise_poly(xs, np.array([coeffs[0],np.zeros(len(coeffs[1]))]).T, bounds) nint = qt.get_nint([A1x, ys_rnd]) n = npres + nint + 1 print(nint, npres, n) n, n0, nint, nintcs, coeffs, bounds = qt.optimize_coeffs_qubits(f_x, xs, m, npres0, npres1, norder=norder, phase=phase)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl')
https://github.com/quantumjim/Qiskit-PyConDE
quantumjim
run controller.py
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit import Aer from qiskit.utils import algorithm_globals, QuantumInstance from qiskit.algorithms import QAOA, NumPyMinimumEigensolver import numpy as np val = [5,6,7,8,9] wt = [4,5,6,7,8] W = 18 def dp(W, wt, val, n): k = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: k[i][w] = 0 elif wt[i-1] <= w: k[i][w] = max(val[i-1] + k[i-1][w-wt[i-1]], k[i-1][w]) else: k[i][w] = k[i-1][w] picks=[0 for x in range(n)] volume=W for i in range(n,-1,-1): if (k[i][volume]>k[i-1][volume]): picks[i-1]=1 volume -= wt[i-1] return k[n][W],picks n = len(val) print("optimal value:", dp(W, wt, val, n)[0]) print('\n index of the chosen items:') for i in range(n): if dp(W, wt, val, n)[1][i]: print(i,end=' ') # import packages necessary for application classes. from qiskit_optimization.applications import Knapsack def knapsack_quadratic_program(): # Put values, weights and max_weight parameter for the Knapsack() ############################## # Provide your code here prob = Knapsack(val, wt, W) # ############################## # to_quadratic_program generates a corresponding QuadraticProgram of the instance of the knapsack problem. kqp = prob.to_quadratic_program() return prob, kqp prob,quadratic_program=knapsack_quadratic_program() quadratic_program # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(quadratic_program) print('result:\n', result) print('\n index of the chosen items:', prob.interpret(result)) # QAOA seed = 123 algorithm_globals.random_seed = seed qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed) meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) result = meo.solve(quadratic_program) print('result:\n', result) print('\n index of the chosen items:', prob.interpret(result)) # Check your answer and submit using the following code from qc_grader import grade_ex4a grade_ex4a(quadratic_program) L1 = [5,3,3,6,9,7,1] L2 = [8,4,5,12,10,11,2] C1 = [1,1,2,1,1,1,2] C2 = [3,2,3,2,4,3,3] C_max = 16 def knapsack_argument(L1, L2, C1, C2, C_max): ############################## # Provide your code here values = [j-i for i,j in zip(L1,L2)] weights = [j-i for i,j in zip(C1,C2)] max_weight = max([i+j for i,j in zip(L1, L2)]) # ############################## return values, weights, max_weight values, weights, max_weight = knapsack_argument(L1, L2, C1, C2, C_max) print(values, weights, max_weight) prob = Knapsack(values = values, weights = weights, max_weight = max_weight) qp = prob.to_quadratic_program() qp # Check your answer and submit using the following code from qc_grader import grade_ex4b grade_ex4b(knapsack_argument) # QAOA seed = 123 algorithm_globals.random_seed = seed qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed) meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins)) result = meo.solve(qp) print('result:', result.x) item = np.array(result.x) revenue=0 for i in range(len(item)): if item[i]==0: revenue+=L1[i] else: revenue+=L2[i] print('total revenue:', revenue) instance_examples = [ { 'L1': [3, 7, 3, 4, 2, 6, 2, 2, 4, 6, 6], 'L2': [7, 8, 7, 6, 6, 9, 6, 7, 6, 7, 7], 'C1': [2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2], 'C2': [4, 3, 3, 4, 4, 5, 3, 4, 4, 3, 4], 'C_max': 33 }, { 'L1': [4, 2, 2, 3, 5, 3, 6, 3, 8, 3, 2], 'L2': [6, 5, 8, 5, 6, 6, 9, 7, 9, 5, 8], 'C1': [3, 3, 2, 3, 4, 2, 2, 3, 4, 2, 2], 'C2': [4, 4, 3, 5, 5, 3, 4, 5, 5, 3, 5], 'C_max': 38 }, { 'L1': [5, 4, 3, 3, 3, 7, 6, 4, 3, 5, 3], 'L2': [9, 7, 5, 5, 7, 8, 8, 7, 5, 7, 9], 'C1': [2, 2, 4, 2, 3, 4, 2, 2, 2, 2, 2], 'C2': [3, 4, 5, 4, 4, 5, 3, 3, 5, 3, 5], 'C_max': 35 } ] from typing import List, Union import math from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, assemble from qiskit.compiler import transpile from qiskit.circuit import Gate from qiskit.circuit.library.standard_gates import * from qiskit.circuit.library import QFT def phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qc = QuantumCircuit(qr_index) ############################## ### U_1(gamma * (lambda2 - lambda1)) for each qubit ### # Provide your code here ############################## return qc.to_gate(label=" phase return ") if to_gate else qc def subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]: qc = QuantumCircuit(data_qubits) ############################## ### Phase Rotation ### # Provide your code here ############################## return qc.to_gate(label=" [+"+str(const)+"] ") if to_gate else qc def const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qc = QuantumCircuit(qr_data) ############################## ### QFT ### # Provide your code here ############################## ############################## ### Phase Rotation ### # Use `subroutine_add_const` ############################## ############################## ### IQFT ### # Provide your code here ############################## return qc.to_gate(label=" [ +" + str(const) + "] ") if to_gate else qc def cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qr_data = QuantumRegister(data_qubits, "data") qc = QuantumCircuit(qr_index, qr_data) for i, (val1, val2) in enumerate(zip(list1, list2)): ############################## ### Add val2 using const_adder controlled by i-th index register (set to 1) ### # Provide your code here ############################## qc.x(qr_index[i]) ############################## ### Add val1 using const_adder controlled by i-th index register (set to 0) ### # Provide your code here ############################## qc.x(qr_index[i]) return qc.to_gate(label=" Cost Calculation ") if to_gate else qc def constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_data, qr_f) ############################## ### Set the flag register for indices with costs larger than C_max ### # Provide your code here ############################## return qc.to_gate(label=" Constraint Testing ") if to_gate else qc def penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_data, qr_f) ############################## ### Phase Rotation ### # Provide your code here ############################## return qc.to_gate(label=" Penalty Dephasing ") if to_gate else qc def reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qr_data = QuantumRegister(data_qubits, "data") qr_f = QuantumRegister(1, "flag") qc = QuantumCircuit(qr_index, qr_data, qr_f) ############################## ### Reinitialization Circuit ### # Provide your code here ############################## return qc.to_gate(label=" Reinitialization ") if to_gate else qc def mixing_operator(index_qubits: int, beta: float, to_gate = True) -> Union[Gate, QuantumCircuit]: qr_index = QuantumRegister(index_qubits, "index") qc = QuantumCircuit(qr_index) ############################## ### Mixing Operator ### # Provide your code here ############################## return qc.to_gate(label=" Mixing Operator ") if to_gate else qc def solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit: # the number of qubits representing answers index_qubits = len(L1) # the maximum possible total cost max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)]) # the number of qubits representing data values can be defined using the maximum possible total cost as follows: data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c & (max_c - 1) == 0 else math.ceil(math.log(max_c, 2)) + 2 ### Phase Operator ### # return part def phase_return(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def subroutine_add_const(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def const_adder(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def cost_calculation(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def constraint_testing(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def penalty_dephasing(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## # penalty part def reinitialization(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## ### Mixing Operator ### def mixing_operator(): ############################## ### TODO ### ### Paste your code from above cells here ### ############################## qr_index = QuantumRegister(index_qubits, "index") # index register qr_data = QuantumRegister(data_qubits, "data") # data register qr_f = QuantumRegister(1, "flag") # flag register cr_index = ClassicalRegister(index_qubits, "c_index") # classical register storing the measurement result of index register qc = QuantumCircuit(qr_index, qr_data, qr_f, cr_index) ### initialize the index register with uniform superposition state ### qc.h(qr_index) ### DO NOT CHANGE THE CODE BELOW p = 5 alpha = 1 for i in range(p): ### set fixed parameters for each round ### beta = 1 - (i + 1) / p gamma = (i + 1) / p ### return part ### qc.append(phase_return(index_qubits, gamma, L1, L2), qr_index) ### step 1: cost calculation ### qc.append(cost_calculation(index_qubits, data_qubits, C1, C2), qr_index[:] + qr_data[:]) ### step 2: Constraint testing ### qc.append(constraint_testing(data_qubits, C_max), qr_data[:] + qr_f[:]) ### step 3: penalty dephasing ### qc.append(penalty_dephasing(data_qubits, alpha, gamma), qr_data[:] + qr_f[:]) ### step 4: reinitialization ### qc.append(reinitialization(index_qubits, data_qubits, C1, C2, C_max), qr_index[:] + qr_data[:] + qr_f[:]) ### mixing operator ### qc.append(mixing_operator(index_qubits, beta), qr_index) ### measure the index ### ### since the default measurement outcome is shown in big endian, it is necessary to reverse the classical bits in order to unify the endian ### qc.measure(qr_index, cr_index[::-1]) return qc # Execute your circuit with following prepare_ex4c() function. # The prepare_ex4c() function works like the execute() function with only QuantumCircuit as an argument. from qc_grader import prepare_ex4c job = prepare_ex4c(solver_function) result = job.result() # Check your answer and submit using the following code from qc_grader import grade_ex4c grade_ex4c(job)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/AsishMandoi/VRP-explorations
AsishMandoi
import utility %config InlineBackend.figure_format = 'svg' from full_qubo_solver import FullQuboSolver as FQS from average_partition_solver import AveragePartitionSolver as APS from qiskit_native_solver import QiskitNativeSolver as QNS from route_activation_solver import RouteActivationSolver as RAS from solution_partition_solver import SolutionPartitionSolver as SPS from dbscan_solver import DBSCANSolver as DBSCANS from clustered_tsp_solver import ClusteredTspSolver as CTS n = 5 m = 2 seed = 891 instance, xc, yc = utility.generate_vrp_instance(n, seed) sps = FQS(n, m, instance) sps.solve(solver='neal') sps.visualize(xc, yc)
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from dell_runtime import DellRuntimeProvider from qiskit import QuantumCircuit import os RUNTIME_PROGRAM_METADATA = { "max_execution_time": 600, "description": "Qiskit test program" } # PROGRAM_PREFIX = 'qiskit-test' def main(): provider = DellRuntimeProvider() here = os.path.dirname(os.path.realpath(__file__)) program_id = provider.runtime.upload_program(here + "/dirtest", metadata=RUNTIME_PROGRAM_METADATA) qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) program_inputs = { 'circuits': qc, } job = provider.runtime.run(program_id, options=None, inputs=program_inputs) job.result(timeout=120) if __name__ == "__main__": main()
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/taalexander/IEEE-Quantum-Week-2021
taalexander
"""Helper methods for running OpenQASM3 programs. (C) Copyright IBM 2021. """ from typing import List, Union from qiskit import QuantumCircuit from qiskit.providers.ibmq import IBMQJob, IBMQBackend, RunnerResult QASM3_INPUT = Union[QuantumCircuit, str] def run_openqasm3(circuits: Union[QASM3_INPUT, List[QASM3_INPUT]], backend: IBMQBackend, verbose: bool = True, draw: bool = True) -> List[IBMQJob]: """Run an OpenQASM3 job through the circuit runner. Args: circuits: A single(list) of :class:`qiskit.QuantumCircuit` or QASM3 source strings to be run. backend: Target backend to run on. verbose: Verbose execution mode. draw: Draw the circuit as part of verbose mode. Note: Cannot draw QASM3 source string. """ if isinstance(circuits, (QuantumCircuit, str)): circuits = [circuits] config = backend.configuration() provider = backend.provider() for circuit_idx, circuit in enumerate(circuits): if verbose: if isinstance(circuit, QuantumCircuit): print(f"======{circuit.name}======") try: from qiskit import qasm3 print("=======QASM3======") print(qasm3.Exporter(includes=[], basis_gates=config.basis_gates).dumps(circuit)) except ImportError: print('The QASM3 exporter is unavailable. Please install the "main" branch of Qiskit.') print("==================") if draw: print(circuit.draw()) print("==================") else: print("==================") print(circuit) print("==================") runtime_params = { 'circuits': circuits, 'exporter_config': { "disable_constants": True } } options = {'backend_name': backend.name()} job = provider.runtime.run( program_id="qasm3-runner", options=options, inputs=runtime_params, result_decoder=RunnerResult, image="qiskit-program-qasm3:latest" ) if verbose: print(f"Running: {job.job_id()}") if verbose: result = job.result() for circuit_idx, circuit in enumerate(circuits): counts = result.get_counts(circuit_idx) if isinstance(circuit, QuantumCircuit): print(f"======={circuit.name}=======") print (counts) return job
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """ Exception for errors raised by Qiskit Aer noise module. """ from qiskit import QiskitError class NoiseError(QiskitError): """Class for errors raised in qiskit_aer.noise package.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
import pytest from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, XGate, CXGate from .gate_count import gate_count circuits = [ [(HGate, [1]), (XGate, [1]), (CXGate, [0, 1])], ] count_objs = [{"h": 1, "x": 1, "cx": 1}] qubit_counts = [2] @pytest.mark.parametrize("gates,count, qubit", zip(circuits, count_objs, qubit_counts)) def test_gate_count_simple(gates, count, qubit): circ = QuantumCircuit(qubit) for gate, qubits in gates: circ.append(gate(), qubits) result = gate_count(circ) assert result == count
https://github.com/AmanSinghBhogal/NasaNEO_Classification
AmanSinghBhogal
# In this code we use Classical Computing Gaussian Naive Bayes Algorithm on Nasa Nearst Earth Object Data Set import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import statistics as st from sklearn.metrics import recall_score, precision_score, confusion_matrix import math import seaborn as samandar # Loaded the Dataset data = pd.read_csv('neo_v2.csv') # Lets drop unwated attributes such as Orbiting Body and Name data = data.drop("orbiting_body", axis = 1) data = data.drop("name", axis = 1) data = data.drop("sentry_object", axis = 1) data = data.drop("id", axis = 1) # Splitted the Dataset into Training and Testing train_input, test_input = train_test_split(data, test_size=0.3, random_state=0) # Printing the Number of True and False Records in Train and Test Dataset print("Train Dataset: No of True: {}, No. False: {}".format(len(train_input[train_input['hazardous'] == True]), len(train_input[train_input['hazardous'] == False]))) print("Test Dataset: No of True: {}, No. False: {}".format(len(test_input[test_input['hazardous'] == True]), len(test_input[test_input['hazardous'] == False]))) # Printing Number of records in training and testing print("There are {} Training Records and {} Testing Records".format(train_input.shape[0], test_input.shape[0])) # Calculating Probability of Hazardious true And false p_hazard_true = len(train_input[train_input['hazardous'] == True])/len(train_input) p_hazard_false = len(train_input[train_input['hazardous'] == False])/len(train_input) # Printing the target class probility print("P[True]: {:.3f}".format(p_hazard_true)) print("P[False]: {:.3f}".format(p_hazard_false)) # Calculating probabilities for Hazardous = True row1 = [] # Calculating Mean and variance for est_diameter_min for hazardous = true row1.append(st.mean(train_input[train_input['hazardous'] == True]['est_diameter_min'])) row1.append(st.variance(train_input[train_input['hazardous'] == True]['est_diameter_min'])) row1.append(st.mean(train_input[train_input['hazardous'] == True]['est_diameter_max'])) row1.append(st.variance(train_input[train_input['hazardous'] == True]['est_diameter_max'])) row1.append(st.mean(train_input[train_input['hazardous'] == True]['relative_velocity'])) row1.append(st.variance(train_input[train_input['hazardous'] == True]['relative_velocity'])) row1.append(st.mean(train_input[train_input['hazardous'] == True]['miss_distance'])) row1.append(st.variance(train_input[train_input['hazardous'] == True]['miss_distance'])) row1.append(st.mean(train_input[train_input['hazardous'] == True]['absolute_magnitude'])) row1.append(st.variance(train_input[train_input['hazardous'] == True]['absolute_magnitude'])) # Calculating Probabilities for Hazardous = False row2 = [] # Calculating Mean and variance for est_diameter_min for hazardous = false row2.append(st.mean(train_input[train_input['hazardous'] == False]['est_diameter_min'])) row2.append(st.variance(train_input[train_input['hazardous'] == False]['est_diameter_min'])) row2.append(st.mean(train_input[train_input['hazardous'] == False]['est_diameter_max'])) row2.append(st.variance(train_input[train_input['hazardous'] == False]['est_diameter_max'])) row2.append(st.mean(train_input[train_input['hazardous'] == False]['relative_velocity'])) row2.append(st.variance(train_input[train_input['hazardous'] == False]['relative_velocity'])) row2.append(st.mean(train_input[train_input['hazardous'] == False]['miss_distance'])) row2.append(st.variance(train_input[train_input['hazardous'] == False]['miss_distance'])) row2.append(st.mean(train_input[train_input['hazardous'] == False]['absolute_magnitude'])) row2.append(st.variance(train_input[train_input['hazardous'] == False]['absolute_magnitude'])) calculated_fields = pd.DataFrame([row1,row2], columns= ['Mean_est_diameter_min','Var_est_diameter_min', 'Mean_est_diameter_max','Var_est_diameter_max', 'Mean_relative_velocity','Var_relative_velocity', 'Mean_miss_distance', 'Var_miss_distance', 'Mean_absolute_magnitude', 'Var_absolute_magnitude']) # Saving the Calculated fields to get a better view calculated_fields.to_csv('calculated_fields.csv') # Calculating Posterior Probability Function F(x) = (1/2πσ2)e(-(x-x̄)/2σ2) def post_prob(mean, var, input_x): return ((1.0/math.sqrt(2.0*np.pi*var))*math.exp((-1.0*((input_x-mean)**2.0))/(2.0*var))) # Writing the Estimation function: def cnb(input): # Post_T = (p_hazard_true*def()*) Post_T = p_hazard_true Post_F = p_hazard_false # print("For Hazardous = True") # Calculating Posterior Probability for Hazardous = True for i in range(len(input)-1): t1 = i*2 t2 = t1+1 val = post_prob(calculated_fields.iloc[0,t1],calculated_fields.iloc[0,t2], input[i]) # print(val) # print("Post_T: {}".format(Post_T)) Post_T *= val # print("For hazardous = False") # Calculating Posterior Probability for Hazardous = False for i in range(len(input)-1): t1 = i*2 t2 = t1+1 val = post_prob(calculated_fields.iloc[1,t1],calculated_fields.iloc[1,t2], input[i]) # print(val) # print("Post_F: {}".format(Post_F)) Post_F *= val # print("Posterior Probability for Hazardous = True is: {}".format(Post_T)) # print("Posterior Probability for Hazardous = False is: {}".format(Post_F)) if Post_T > Post_F: return True else: return False # Specificity def specificity(matrix): return matrix[0][0]/(matrix[0][0]+ matrix[0][1]) if (matrix[0][0]+matrix[0][1]>0) else 0 # Negative Predictive Value(NPV) def npv(matrix): return matrix[0][0]/(matrix[0][1]+ matrix[1][0]) if (matrix[0][1]+ matrix[1][0] > 0) else 0 # Logic for testing the algorithm actual_outputs = test_input['hazardous'] predicted_outputs = [] for i in range(len(test_input)): predicted_outputs.append(cnb(test_input.iloc[i].values.flatten().tolist())) # Creating Classifier Report function def classifier_report(): name = 'Classical Guassian Naive Bayes Algorithm' cr_prediction = predicted_outputs labels = actual_outputs cr_cm = confusion_matrix(labels, cr_prediction) print("Confusion Matrix") print(cr_cm) cr_precision = precision_score(labels, cr_prediction) cr_recall = recall_score(labels, cr_prediction) cr_specificity = specificity(cr_cm) cr_npv = npv(cr_cm) cr_level = 0.25 * (cr_precision + cr_recall + cr_specificity + cr_npv) print('The precision score of the {} classifier is {:.2f}' .format(name, cr_precision)) print('The recall score of the {} classifier is {:.2f}' .format(name, cr_recall)) print('The specificity score of the {} classifier is {:.2f}' .format(name, cr_specificity)) print('The npv score of the {} classifier is {:.2f}' .format(name, cr_npv)) print('The information level is: {:.2f}' .format(cr_level)) classifier_report() # Visualisation correlation = train_input.corr() # plot the heatmap samandar.heatmap(correlation, xticklabels = correlation.columns, yticklabels = correlation.columns, annot=True) # plot the clustermap samandar.clustermap(correlation, xticklabels = correlation.columns, yticklabels = correlation.columns, annot=True)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import os import shutil import time from random_lp.lp_random_gen import RandomLP DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") def getPath(filename = "", directory = ""): return DIR + "/" + directory + "/" + filename DIR shutil.rmtree(DIR, ignore_errors=True) os.makedirs(getPath(directory = "DENSE")) # create dense random binary Linear Programs # we want up to 33 qubits since ibmq_qasm_simulator has 32 max_qubits = 32 var = 3 while True: cstr = int(var / 2) lp_bin = RandomLP.create_random_binary_prog("test_" + str(var), cstr, var) lp_bin.write_to_lp_file(getPath(lp_bin.name, directory = "DENSE")) if lp_bin.complexity() > max_qubits : print(var) break var = var + 2 lp_bin.qubo.to_docplex().prettyprint()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor IBMQ.load_accounts() backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None) shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots. max_credits = 3 # Maximum number of credits to spend on executions. def DJ_N3(qc): qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[2]) qc.z(q[0]) qc.cx(q[1], q[2]) qc.h(q[2]) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.measure(q,c) # Create a Quantum Register with 3 qubits. q = QuantumRegister(3, 'q') c = ClassicalRegister(3,'c') # Create a Quantum Circuit acting on the q register qc = QuantumCircuit(q,c) DJ_N3(qc) qc.draw() job_hpc = execute(qc, backend=backend, shots=shots, max_credits=max_credits) result_hpc = job_hpc.result() counts_hpc = result_hpc.get_counts(qc) plot_histogram(counts_hpc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/Qiskit/feedback
Qiskit
from qiskit.transpiler import AnalysisPass class IJustShout(AnalysisPass): """Pass that just prints a message.""" def __init__(self, important_message): super().__init__() self.important_message = important_message def run(self, dag): print(self.important_message) return dag from qiskit.transpiler import PassManager step1_pm = PassManager(IJustShout("Calling step 1!")) step2_pm = PassManager(IJustShout("Calling step 2!")) from qiskit.providers.aer import AerSimulator from qiskit.utils import QuantumInstance sim = AerSimulator() quantum_instance = QuantumInstance(sim, pass_manager=step1_pm, bound_pass_manager=step2_pm) from qiskit.circuit import QuantumCircuit, Parameter x = Parameter("x") circuit = QuantumCircuit(2) circuit.ry(x, 0) circuit.cx(0, 1) circuit.draw("mpl", style="iqx") from qiskit.opflow import CircuitSampler, AerPauliExpectation, StateFn, H expectation = StateFn(H ^ H, is_measurement=True) @ StateFn(circuit) expectation = AerPauliExpectation().convert(expectation) sampler = CircuitSampler(quantum_instance) sampler.convert(expectation, {x: 1}).eval() sampler.convert(expectation, {x: 0.6}).eval() sampler.convert(expectation, {x: 0.2}).eval() from qiskit.test.mock import FakeBelem from qiskit.transpiler import PassManagerConfig from qiskit.transpiler.preset_passmanagers import level_1_pass_manager backend = FakeBelem() unbound_pm = level_1_pass_manager(PassManagerConfig.from_backend(FakeBelem())) unbound_pm += PassManager(IJustShout("Level 1 pass manager")) from qiskit.circuit.library.standard_gates.equivalence_library import StandardEquivalenceLibrary as std_eqlib from qiskit.transpiler.passes import ( Collect2qBlocks, ConsolidateBlocks, Optimize1qGatesDecomposition, RZXCalibrationBuilderNoEcho, UnrollCustomDefinitions, BasisTranslator ) from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import EchoRZXWeylDecomposition # Build the pass manager for the parameterized circuit rzx_basis = ['rzx', 'rz', 'x', 'sx'] # Build a pass manager for the CX decomposition (works only on bound circuits) bound_pm = PassManager([ IJustShout("Pulse-efficient pass manager"), # Consolidate consecutive two-qubit operations. Collect2qBlocks(), ConsolidateBlocks(basis_gates=['rz', 'sx', 'x', 'rxx']), # Rewrite circuit in terms of Weyl-decomposed echoed RZX gates. EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map), # Attach scaled CR pulse schedules to the RZX gates. RZXCalibrationBuilderNoEcho(backend), # Simplify single-qubit gates. UnrollCustomDefinitions(std_eqlib, rzx_basis), BasisTranslator(std_eqlib, rzx_basis), Optimize1qGatesDecomposition(rzx_basis), ]) from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.opflow import Z quantum_instance = QuantumInstance( backend, pass_manager=unbound_pm, bound_pass_manager=bound_pm ) vqe = VQE(optimizer=L_BFGS_B(), quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(Z ^ Z) print(result)
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from IPython.display import Image, display Image('lights_out_prob.png') Image('lights_out_circuit.jpg') from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister tile = QuantumRegister(9) flip = QuantumRegister(9) oracle = QuantumRegister(1) auxiliary = QuantumRegister(7) result = ClassicalRegister(9) #26 qubit qc = QuantumCircuit(tile, flip, oracle, auxiliary, result) lights = [0, 1, 1, 1, 0, 0, 1, 1, 1] def map_board(lights, qc, qr): j = 0 for i in lights: if i==1: qc.x(qr[j]) j+=1 else: j+=1 def initialize(): map_board(lights, qc, tile) qc.h(flip[0:10]) qc.x(oracle[0]) qc.h(oracle[0]) # Subroutine for oracle # Calculate what the light state will be after pressing each solution candidate. def flip_tile(qc,flip,tile): qc.cx(flip[0], tile[0]) qc.cx(flip[0], tile[1]) qc.cx(flip[0], tile[3]) qc.cx(flip[1], tile[0]) qc.cx(flip[1], tile[1]) qc.cx(flip[1], tile[2]) qc.cx(flip[1], tile[4]) qc.cx(flip[2], tile[1]) qc.cx(flip[2], tile[2]) qc.cx(flip[2], tile[5]) qc.cx(flip[3], tile[0]) qc.cx(flip[3], tile[3]) qc.cx(flip[3], tile[4]) qc.cx(flip[3], tile[6]) qc.cx(flip[4], tile[1]) qc.cx(flip[4], tile[3]) qc.cx(flip[4], tile[4]) qc.cx(flip[4], tile[5]) qc.cx(flip[4], tile[7]) qc.cx(flip[5], tile[2]) qc.cx(flip[5], tile[4]) qc.cx(flip[5], tile[5]) qc.cx(flip[5], tile[8]) qc.cx(flip[6], tile[3]) qc.cx(flip[6], tile[6]) qc.cx(flip[6], tile[7]) qc.cx(flip[7], tile[4]) qc.cx(flip[7], tile[6]) qc.cx(flip[7], tile[7]) qc.cx(flip[7], tile[8]) qc.cx(flip[8], tile[5]) qc.cx(flip[8], tile[7]) qc.cx(flip[8], tile[8]) initialize() for i in range(17): # oracle flip_tile(qc,flip,tile) qc.x(tile[0:9]) qc.mct(tile[0:9], oracle[0], auxiliary[0:7], mode='basic') qc.x(tile[0:9]) flip_tile(qc,flip,tile) # diffusion qc.h(flip) qc.x(flip) qc.h(flip[8]) qc.mct(flip[0:8], flip[8], auxiliary[0:7], mode='basic') qc.h(flip[8]) qc.x(flip) qc.h(flip) # Uncompute qc.h(oracle[0]) qc.x(oracle[0]) # Measuremnt qc.measure(flip,result) # Make the Out put order the same as the input. qc = qc.reverse_bits() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroll the circuit pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) # obtain gates gates=new_circuit.count_ops() print(gates) %%time from qiskit import IBMQ, execute provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:40] final_score Image('lights_out_optimal.png') Image('lights_out_optimal_circuit.jpg') tile = QuantumRegister(9) flip = QuantumRegister(9) oracle = QuantumRegister(1) auxiliary = QuantumRegister(1) result = ClassicalRegister(9) # 20 qubit qc = QuantumCircuit(tile, flip, oracle, auxiliary, result) # Initialize def initialize_smart(l,qc,tile): map_board(l, qc, tile) qc.h(flip[:3]) qc.x(oracle[0]) qc.h(oracle[0]) def flip_1(qc,flip,tile): # push 0 qc.cx(flip[0], tile[0]) qc.cx(flip[0], tile[1]) qc.cx(flip[0], tile[3]) # push 1 qc.cx(flip[1], tile[0]) qc.cx(flip[1], tile[1]) qc.cx(flip[1], tile[2]) qc.cx(flip[1], tile[4]) # push 2 qc.cx(flip[2], tile[1]) qc.cx(flip[2], tile[2]) qc.cx(flip[2], tile[5]) def inv_1(qc,flip,tile): # copy 0,1,2 qc.cx(tile[0], flip[3]) qc.cx(tile[1], flip[4]) qc.cx(tile[2], flip[5]) def flip_2(qc,flip,tile): # apply flip[3,4,5] qc.cx(flip[3], tile[0]) qc.cx(flip[3], tile[3]) qc.cx(flip[3], tile[4]) qc.cx(flip[3], tile[6]) qc.cx(flip[4], tile[1]) qc.cx(flip[4], tile[3]) qc.cx(flip[4], tile[4]) qc.cx(flip[4], tile[5]) qc.cx(flip[4], tile[7]) qc.cx(flip[5], tile[2]) qc.cx(flip[5], tile[4]) qc.cx(flip[5], tile[5]) qc.cx(flip[5], tile[8]) def inv_2(qc,flip,tile1): # copy 3,4,5 qc.cx(tile[3], flip[6]) qc.cx(tile[4], flip[7]) qc.cx(tile[5], flip[8]) def flip_3(qc,flip,tile): qc.cx(flip[6], tile[3]) qc.cx(flip[6], tile[6]) qc.cx(flip[6], tile[7]) qc.cx(flip[7], tile[4]) qc.cx(flip[7], tile[6]) qc.cx(flip[7], tile[7]) qc.cx(flip[7], tile[8]) qc.cx(flip[8], tile[5]) qc.cx(flip[8], tile[7]) qc.cx(flip[8], tile[8]) def lights_out_oracle(qc,tile,oracle,auxiliary): qc.x(tile[6:9]) qc.mct(tile[6:9], oracle[0], auxiliary, mode='basic') qc.x(tile[6:9]) def diffusion(qc,flip): qc.h(flip[:3]) qc.x(flip[:3]) qc.h(flip[2]) qc.ccx(flip[0],flip[1],flip[2]) qc.h(flip[2]) qc.x(flip[:3]) qc.h(flip[:3]) initialize_smart(lights,qc,tile) for i in range(2): flip_1(qc,flip,tile) inv_1(qc,flip,tile) flip_2(qc,flip,tile) inv_2(qc,flip,tile) flip_3(qc,flip,tile) lights_out_oracle(qc,tile,oracle,auxiliary) flip_3(qc,flip,tile) inv_2(qc,flip,tile) flip_2(qc,flip,tile) inv_1(qc,flip,tile) flip_1(qc,flip,tile) diffusion(qc,flip) # Uncompute qc.h(oracle[0]) qc.x(oracle[0]) # get the whole solution from the top row of the solution # If you get a solution, you don't need to erase the board, so you don't need the flip_3 function. flip_1(qc,flip,tile) inv_1(qc,flip,tile) flip_2(qc,flip,tile) inv_2(qc,flip,tile) # Measuremnt qc.measure(flip,result) # Make the Out put order the same as the input. qc = qc.reverse_bits() # Unroll the circuit pass_ = Unroller(['u3', 'cx']) pm = PassManager(pass_) new_circuit = pm.run(qc) # obtain gates gates=new_circuit.count_ops() print(gates) %%time backend = provider.get_backend('ibmq_qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() score_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True) final_score = score_sorted[0:40] final_score
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
Soumyo2121
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector ### Creating 3 qubit and 2 classical bits in each separate register qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, crz, crx) ### A third party eve helps to create an entangled state def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a, b) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, a, b): qc.cx(a, b) qc.h(a) teleportation_circuit.barrier() alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): qc.barrier() qc.measure(a,0) qc.measure(b,1) teleportation_circuit.barrier() measure_and_send(teleportation_circuit, 0, 1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) qc.z(qubit).c_if(crz, 1) teleportation_circuit.barrier() bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() from qiskit.extensions import Initialize import math qc = QuantumCircuit(1) initial_state = [0,1] init_gate = Initialize(initial_state) # qc.append(initialize_qubit, [0]) qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical registers crx = ClassicalRegister(1) qc = QuantumCircuit(qr, crz, crx) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) # Bob decodes qubits bob_gates(qc, 2, crz, crx) qc.draw() backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() qc.append(inverse_init_gate, [2]) qc.draw() cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw() backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts) def bob_gates(qc, a, b, c): qc.cz(a, c) qc.cx(b, c) qc = QuantumCircuit(3,1) # First, let's initialise Alice's q0 qc.append(init_gate, [0]) qc.barrier() # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) qc.barrier() # Alice sends classical bits to Bob bob_gates(qc, 0, 1, 2) # We undo the initialisation process qc.append(inverse_init_gate, [2]) # See the results, we only care about the state of qubit 2 qc.measure(2,0) # View the results: qc.draw() from qiskit import IBMQ IBMQ.save_account('### IMB TOKEN ') IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) job_exp = execute(qc, backend=backend, shots=8192) exp_result = job_exp.result() exp_measurement_result = exp_result.get_counts(qc) print(exp_measurement_result) plot_histogram(exp_measurement_result) error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \ * 100./ sum(list(exp_measurement_result.values())) print("The experimental error rate : ", error_rate_percent, "%")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})