repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb S = Matrix([[1,0],[0,1j]]); Sd = Matrix([[1,0],[0,-1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]])#; S, H S*H*S from qiskit import * def qc_mzi_sim(ph): # quantum circuit for the Mach-Zehnder interferometer qr = QuantumRegister(1); qc = QuantumCircuit(qr) qc.u(math.pi/2, math.pi/2, -math.pi/2, qr[0]); # DF #qc.s(qr[0]); qc.h(qr[0]); qc.s(qr[0]) # DF qc.z(qr[0]); qc.y(qr[0]) # espelho qc.p(ph, qr[0]); # fase qc.u(math.pi/2, math.pi/2, -math.pi/2, qr[0]) # DF #qc.s(qr[0]); qc.h(qr[0]); qc.s(qr[0]) # DF return qc qcmzi = qc_mzi_sim(math.pi/8); qcmzi.draw() def state_prep(th, ph): qr = QuantumRegister(1); qc = QuantumCircuit(qr) qc.u(th, ph, 0, qr[0]) return qc from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter nshots = 8192 qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') from qiskit.tools.monitor import job_monitor # for error mitigation from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter qr = qiskit.QuantumRegister(1) qubit_list = [0] # os qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend = device, shots = nshots); job_monitor(job) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph)#; ph d = ph.shape[0]; PD0teo = np.zeros(d); PD0sim = np.zeros(d); PD0exp = np.zeros(d) for j in range(0, d): PD0teo[j] = (1+math.cos(ph[j]))/2 # theoretical qr = QuantumRegister(1); qc = QuantumCircuit(qr) qc_sp = state_prep(0, 0); qc.append(qc_sp, [qr[0]]) # state preparation (estado |0>) qc_mzi = qc_mzi_sim(ph[j]); qc.append(qc_mzi, [qr[0]]) # apply sim mzi qstc = state_tomography_circuits(qc, qr[0]) # circuit for state tomography job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0sim[j] = rho[0,0].real # 1º fiz as simulações, só depois adicionei o código para os experimentos job = qiskit.execute(qstc, backend = device, shots = nshots) print(job.job_id()); job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0exp[j] = rho[0,0].real matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(ph, PD0teo, label = r'$P_{teo}(D_{0})$') plt.plot(ph, PD0sim, 'o', label = r'$P_{sim}(D_{0})$') plt.plot(ph, PD0exp, '*', label = r'$P_{exp}(D_{0})$') plt.legend(); plt.xlabel(r'$\phi$'); plt.show() # gráfico para estado inicial |+> phmax = 2*math.pi; dph = phmax/20; ph = np.arange(0, phmax+dph, dph)#; ph d = ph.shape[0]; PD0teo = np.zeros(d); PD0sim = np.zeros(d); PD0exp = np.zeros(d) for j in range(0, d): c0 = 1/math.sqrt(2); c1 = c0; PD0teo[j] = (abs(c0)**2*(1+math.cos(ph[j])) + abs(c1)**2*(1-math.cos(ph[j]))\ - 2*((c0*np.conjugate(c1)).real)*math.sin(ph[j]))/2 qr = QuantumRegister(1); qc = QuantumCircuit(qr) qc_sp = state_prep(math.pi/2, 0); qc.append(qc_sp, [qr[0]]) # state preparation (estado |+>) qc_mzi = qc_mzi_sim(ph[j]); qc.append(qc_mzi, [qr[0]]) # apply sim phase damping qstc = state_tomography_circuits(qc, qr[0]) # circuit for state tomography job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') PD0sim[j] = rho[0,0].real matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(ph, PD0teo, label = r'$P_{teo}(D_{0})$') plt.plot(ph, PD0sim, 'o', label = r'$P_{sim}(D_{0})$') plt.legend(); plt.xlabel(r'$\phi$'); plt.show() phmax = 4*math.pi; dph = phmax/50; ph = np.arange(0, phmax+dph, dph); d = ph.shape[0] w = 1; pw1 = (1+(2*w-1)*np.cos(ph))/2; w = 0.25; pw025 = (1+(2*w-1)*np.cos(ph))/2 w = 0.5; pw05 = (1+(2*w-1)*np.cos(ph))/2; w = 0.75; pw075 = (1+(2*w-1)*np.cos(ph))/2 w = 0; pw0 = (1+(2*w-1)*np.cos(ph))/2 matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(ph, pw1, label = r'$w=1$'); plt.plot(ph, pw075, label = r'$w=0.75$') plt.plot(ph, pw05, label = r'$w=0.5$'); plt.plot(ph, pw025, label = r'$w=0.25$') plt.plot(ph, pw0, label = r'$w=0$') plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left'); plt.xlabel(r'$\phi$'); plt.show() def shannon_num(pv): d = pv.shape[0]; SE = 0.0; j = -1 while (j < d-1): j = j + 1 if pv[j] > 10**-15 and pv[j] < (1.0-10**-15): SE -= pv[j]*math.log(pv[j], 2) return SE import scipy.linalg.lapack as lapak def von_neumann_num(rho): d = rho.shape[0]; b = lapak.zheevd(rho) return shannon_num(b[0]) def V(pd): return (np.max(pd)-np.min(pd))/(np.max(pd)+np.min(pd)) def pd_ph(w): phmax = 4*math.pi; dph = phmax/100; ph = np.arange(0, phmax+dph, dph) return (1+(2*w-1)*np.cos(ph))/2 def rhow(w): return np.array([[w,0],[0,1-w]]) w = np.arange(0, 1.05, 0.05); d = w.shape[0]; Vis = np.zeros(d); Svn = np.zeros(d) for j in range(0, d): pd = pd_ph(w[j]); Vis[j] = V(pd); rho = rhow(w[j]); Svn[j] = von_neumann_num(rho) matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100) plt.plot(w, Vis, label = 'V'); plt.plot(w, Svn, label = r'$S_{vn}$') plt.xlabel(r'$w$'); plt.legend(); plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import random from qiskit.quantum_info import Statevector secret = random.randint(0,7) # the owner is randomly picked secret_string = format(secret, '03b') # format the owner in 3-bit string oracle = Statevector.from_label(secret_string) # let the oracle know the owner from qiskit.algorithms import AmplificationProblem problem = AmplificationProblem(oracle, is_good_state=secret_string) from qiskit.algorithms import Grover grover_circuits = [] for iteration in range(1,3): grover = Grover(iterations=iteration) circuit = grover.construct_circuit(problem) circuit.measure_all() grover_circuits.append(circuit) # Grover's circuit with 1 iteration grover_circuits[0].draw() # Grover's circuit with 2 iterations grover_circuits[1].draw() from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" # use the simulator from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run(circuits=grover_circuits, shots=1000) result = job.result() print(result) from qiskit.tools.visualization import plot_histogram # Extract bit string with highest probability from results as the answer result_dict = result.quasi_dists[1].binary_probabilities() answer = max(result_dict, key=result_dict.get) print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n" "And the results with 2 iterations have higher probability than the results with 1 iteration." ) # Plot the results plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations']) # Print the results and the correct answer. print(f"Quantum answer: {answer}") print(f"Correct answer: {secret_string}") print('Success!' if answer == secret_string else 'Failure!') import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Shashankaubaru/NISQ-TDA
Shashankaubaru
# noqa: E501,E402,E401,E128 # flake8 disable errors # -*- coding: utf-8 -*- # Copyright 2018 IBM. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= # import warnings # warnings.filterwarnings("ignore", category=DeprecationWarning) # For Homology from classical_homology import \ construct_unfilled_triangle, \ construct_unfilled_square, \ complete_unsigned_complex, \ one_skeleton_triangle, \ one_skeleton_square, \ one_skeleton_pyramid, \ one_skeleton_random, \ one_skeleton_fully_connected, \ one_skeleton_tetrahedron, \ one_skeleton_square_with_diagonal, \ one_skeleton_unfilled_cube, \ one_skeleton_n_disconnected_squares from homology_tools import d_dim_simplices_mask, num_underlying_vertices_vector_length, num_underlying_vertices_simplices, print_signs_simplicial_vector_parts, reshape_vector_to_matrix_and_index, simplices_to_count_vector, count_vector_to_simplices from math_fiddling import binarize, print_matrix, format_basic, format_complex, print_matrix_and_info, format_real, countBits, num_bits, integer_to_binary_as_string, pair_index_to_two_power_2s, two_power_2s_to_pair_index, num_qubits_from_num_pairs, is_power_of_2, first_non_zero_bit, bin_string2int #For General Computing import itertools import numpy as np from numpy.linalg import norm as norm import time import secrets #from scipy.spatial.KDTree import query_pairs as find_pairs from scipy.special import rel_entr, entr import json import copy #For Qiskit use from qiskit.quantum_info import Pauli from qiskit.aqua.operators import PrimitiveOp, MatrixOp from qiskit import BasicAer, Aer import qiskit.providers.aer.noise as qnoise from qiskit.providers.aer import AerSimulator from qiskit.test.mock import fake_pulse_backend from qiskit.aqua import QuantumInstance from qiskit.aqua.utils import decimal_to_binary from qiskit.aqua.algorithms import NumPyMinimumEigensolver from qiskit.aqua.algorithms import QPE from qiskit.circuit.library import QFT from qiskit.aqua.components.initial_states import Custom #from qiskit.aqua.operators.legacy import MatrixOperator, WeightedPauliOperator #from qiskit.aqua.operators.legacy import op_converter from qiskit import AncillaRegister, QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.aqua.utils import summarize_circuits from qiskit.circuit.quantumregister import Qubit # from qiskit.aqua.circuits import FourierTransformCircuits as Fourier_circ # from qiskit.circuit.library import QFT # from qiskit.circuit import Parameter # from qiskit.aqua.operators import PauliTrotterEvolution, Suzuki from qiskit.extensions.quantum_initializer.initializer import Initialize from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.aqua import AquaError from qiskit.aqua.utils import CircuitFactory from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit from qiskit.aqua.circuits import PhaseEstimationCircuit from qiskit.aqua.utils.subsystem import get_subsystems_counts from qiskit.circuit.library import TwoLocal from qiskit.compiler import transpile, assemble from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit.providers.jobstatus import JobStatus from qiskit.providers.ibmq.managed import IBMQJobManager from datetime import datetime, timedelta from dateutil import tz # from qiskit_ionq import IonQProvider from qiskit.providers.honeywell import Honeywell # from qiskit.providers.basicaer import BasicAerJob import matplotlib.pyplot as plot from qiskit.visualization import plot_histogram import glob # import pdb # from pdb import set_trace as bp EPS = 1e-16 JOB_RETRIEVE_LIMIT = 300 JOB_PREVIOUS_DAYS = 20 ####################################################################### ############################################ ### HARDWARE HELPER FUNCTIONS ############################################ def get_post_select_counts(complete_system_counts, post_select_indices_set=None, post_select_flags_set=None): if len(post_select_indices_set)!=len(post_select_flags_set): raise ValueError("indices list not same length as flags list.") mixed_measurements = list(complete_system_counts) num_registers = len(mixed_measurements[0].split()) count_dicts = [{} for _ in range(len(post_select_flags_set))] post_selections = [(i,j,k) for i, (j,k) in enumerate(zip(post_select_indices_set, post_select_flags_set))] for mixed_measurement in mixed_measurements: split_measurement = np.array(mixed_measurement.split()[::-1], dtype=str) #-1 reverses so registers are correct, strings themselves remain in qiskit ordering for i, post_select_indices, post_select_flags in post_selections: if np.all(split_measurement[post_select_indices] == post_select_flags): other_indices = list(range(num_registers)) list(map(other_indices.remove, post_select_indices)) if other_indices: count_dicts[i][" ".join(split_measurement[other_indices])] = \ complete_system_counts[mixed_measurement] else: count_dicts[i][mixed_measurement] = complete_system_counts[mixed_measurement] return count_dicts # remember other_indices registers are in qiskit ordering # TODO: make unittests # get_post_select_counts({'0 0': 10, '1 1' : 20}, [[1],[1]], [['0'],['1']]) # get_post_select_counts({'0 0': 10, '1 1' : 20, '1 2': 30}, [[1],[1]], [['0'],['1']]) def get_fraction_count_for_all_k(complete_system_counts, laplacian, sqrt): # 0 simplicies are points, remember, may not be able to count _num_main_qubits in count register, so let's return size num_main_qubits - 1 # Main # main_0_indices = [0] # main_0_flags = ['0'*laplacian._num_main_qubits] # no, rather let vary count_start = 0 # Ancilla: Not measuring for now! TODO implement error mitigation. # count_start = int((laplacian._num_clean_ancillae > 0)) # ancilla_indices = [1]*count_start #count_start is zero or one only # ancilla_flags = ['0'*laplacian._num_clean_ancillae]*count_start ancilla_indices = [] ancilla_flags = [] # Project Complex count_start += 1 count_end = count_start + laplacian._num_complex_projections project_complex_indices = list(range(count_start, count_end)) project_complex_flags = ['0'*laplacian._num_pairs]*laplacian._num_complex_projections # Split count_start = count_end count_end = count_start + laplacian._num_split_projections matching_split_indices_set = [list(range(count_start, count_end))]*\ (laplacian._num_main_qubits-1) matching_split_flags_set = [] for k in range(0, laplacian._num_main_qubits-1): # k is simplex dim # k+1 is num vertices: k_as_bin_str = integer_to_binary_as_string(k+1, width=laplacian._count_bits_per_projection) matching_split_flags_set.append([k_as_bin_str]*laplacian._num_split_projections) projection_indices = ancilla_indices + project_complex_indices projection_flags = ancilla_flags + project_complex_flags projection_indices_set = list(map(lambda matching_split_indices: \ projection_indices + matching_split_indices, matching_split_indices_set)) projection_flags_set = list(map(lambda matching_split_flags: \ projection_flags + matching_split_flags, matching_split_flags_set)) counts_dicts = get_post_select_counts(complete_system_counts, projection_indices_set, projection_flags_set) #prob0 = [dict_k['00']/sum(dict_k.values()) for dict_k in prob0_dicts], no forgot about footnote 12, go back to over everything else! total_counts = sum(complete_system_counts.values()) # old confused way, when restricted counts to k simplices # frac_counts = [] # for k, dict_k in enumerate(counts_dicts): # valid_keys = [select_key for select_key in dict_k.keys() # if sum(map(int, list(select_key))) == k+1] # frac_counts.append(sum([*map(dict_k.get, valid_keys)])/total_counts) if sqrt: frac_counts = [sum(dict_k.values())/total_counts for dict_k in counts_dicts] else: frac_counts = [dict_k['0'*laplacian._num_main_qubits]/total_counts for dict_k in counts_dicts] return frac_counts ############################################ ### BOUNDARY OPERATOR HELPER FUNCTIONS ############################################ def operator_from_pauli_labels(coeff, paulis): pauli_ops = [] for w, p in zip(coeff, paulis): pauli_ops += [PrimitiveOp(Pauli.from_label(p), coeff=np.real(w) + np.imag(w)*1.j)] return sum(pauli_ops) # We go straight to the Pauli representation of b + b* def boundary_operator_plus_conjugate_as_pauli_labels(num_vertices): boundary_map_pauli_coeff = [1 for _ in range(num_vertices)] first_part = "Z"*(num_vertices-1) last_part = "I"*(num_vertices-1) boundary_map_pauli_strings = map(lambda i: first_part[:i] + "X" + last_part[i:], range(num_vertices)) return boundary_map_pauli_coeff, list(boundary_map_pauli_strings) def boundary_operator_hermitian(num_vertices): qubit_op = operator_from_pauli_labels( *boundary_operator_plus_conjugate_as_pauli_labels( num_vertices)) return qubit_op # return (1/np.sqrt(num_vertices))*qubit_op #normalize def Ri_add(to_add_circ, three_qubits, theta): qubit0 = three_qubits[1] qubit1 = three_qubits[0] target_qubit = three_qubits[2] # Yi-1 # D to_add_circ.x(qubit0) to_add_circ.s(qubit0) to_add_circ.h(qubit0) # CNOT to_add_circ.cx(qubit0, target_qubit) # Xi to_add_circ.h(qubit1) to_add_circ.cx(qubit1, target_qubit) to_add_circ.rz(theta, target_qubit) # Xi\dagger to_add_circ.cx(qubit1, target_qubit) to_add_circ.h(qubit1) # Yi-1\dagger to_add_circ.cx(qubit0, target_qubit) # D\dagger to_add_circ.h(qubit0) to_add_circ.sdg(qubit0) to_add_circ.x(qubit0) def boundary_operator_unitary_circuit(main_qreg=None, target_register=None, control_qubit=None): if isinstance(main_qreg, int): main_qreg = QuantumRegister(main_qreg) num_vertices = len(main_qreg) if target_register is None: target_register = QuantumRegister(1) boundary_circ = QuantumCircuit(main_qreg, target_register) R_circ = QuantumCircuit(main_qreg, target_register) #if isinstance(target_qubit, QuantumRegister): target_qubit = target_register[0] for i in range(1, num_vertices): Ri_add(R_circ, [main_qreg[i-1], main_qreg[i], target_qubit], np.arctan2(np.sqrt(i), 1)) # R boundary_circ += R_circ # P_0 if control_qubit is None: boundary_circ.x(main_qreg[-1]) else: boundary_circ.cx(control_qubit, main_qreg[-1]) # R\dagger boundary_circ += R_circ.inverse() return boundary_circ # Just to check, we can define the boundary operator separately: def boundary_operator_as_pauli_labels(num_vertices): boundary_map_pauli_coeff = [[1/2, 1j/2] for _ in range(num_vertices)] first_part = "Z"*(num_vertices-1) last_part = "I"*(num_vertices-1) boundary_map_pauli_strings = map(lambda i: list(map( lambda B01_term: first_part[:i] + B01_term + last_part[i:], ["X", "Y"])), range(num_vertices)) return list(itertools.chain.from_iterable(boundary_map_pauli_coeff)),\ list(itertools.chain.from_iterable(boundary_map_pauli_strings)) def boundary_operator(num_vertices): qubit_op = operator_from_pauli_labels( *boundary_operator_as_pauli_labels(num_vertices)) return qubit_op # def boundary_operator_conjugate_as_pauli_labels(num_vertices): # coeffs, paulis = boundary_operator_as_pauli_labels(num_vertices) # for i in range(num_vertices): # coeffs[2*i+1] = -coeffs[2*i+1] # return coeffs, paulis # # def boundary_operator_hermitian_derived_separately(num_vertices): # qubit_op = operator_from_pauli_labels( # *boundary_operator_conjugate_as_pauli_labels(num_vertices)) \ # + operator_from_pauli_labels( # *boundary_operator_as_pauli_labels(num_vertices)) # return qubit_op # def boundary_operator_squared_normalized(num_vertices): # # this is automatically hermitian # qubit_op = boundary_operator_hermitian(num_vertices) # qubit_op *= (1/num_vertices)*qubit_op # qubit_op.simplify() # return qubit_op # def boundary_reworked_to_kernel(num_vertices): # qubit_op = boundary_operator_squared_normalized(num_vertices) # return WeightedPauliOperator.from_list([Pauli.from_label("I"*(num_vertices+1))]) + (-1)*qubit_op #Careful, here we take the real part only because we expect only real entries! def classical_matrix_from_pauli_operator(qubit_op): return np.real(qubit_op.to_matrix()) def rbs(circ, pair_reg, angle): circ.h(pair_reg) circ.cz(pair_reg[0], pair_reg[1]) circ.ry(-angle, pair_reg[0]) circ.ry(angle, pair_reg[1]) circ.cz(pair_reg[0], pair_reg[1]) circ.h(pair_reg) return circ def parity(circ, reg): num_left = len(reg) qubit_indices = list(range(num_left)) while num_left > 1: new_qubit_indices = [] for start_index in range(0, num_left-1, 2): circ.cx(reg[qubit_indices[start_index+1]], reg[qubit_indices[start_index]]) new_qubit_indices.append(qubit_indices[start_index]) if start_index < num_left - 2: new_qubit_indices.append(qubit_indices[-1]) qubit_indices = new_qubit_indices[:] num_left = len(qubit_indices) return circ def fbs(circ, reg, i, j, theta): if i+2<j: temp_circ = QuantumCircuit(reg) parity(temp_circ, reg[i+1:j]) circ += temp_circ.inverse() if i+1<j: circ.cz(i+1,i) rbs(circ, [reg[i], reg[j]], theta) if i+1<j: circ.cz(i+1,i) if i+2<j: circ += temp_circ return circ def clifford_loader(circ, reg, theta): temp_circ = QuantumCircuit(reg) num_left = len(reg) qubit_indices = list(range(num_left)) while num_left > 1: new_qubit_indices = [] for start_index in range(0, num_left-1, 2): fbs(temp_circ, reg, qubit_indices[start_index], qubit_indices[start_index+1], theta) new_qubit_indices.append(qubit_indices[start_index]) if start_index < num_left - 2: new_qubit_indices.append(qubit_indices[-1]) qubit_indices = new_qubit_indices[:] num_left = len(qubit_indices) circ += temp_circ.inverse() circ.x(reg[0]) circ += temp_circ return circ ####################################################################### ############################################ ### PROJECT ONTO COMPLEX HELPER FUNCTIONS ############################################ ############################################ ### Controlled Permutation (Add 1 And Cycle) ############################################ def permutation_circuit(qr=None, qancilla=None, circ=None): # By permutation we mean "add 1 with wrapping". The key insight was seeing the 4x4 permutation matrix as a swapped flipped CNOT! Then for the 8x8: swap rows 000 and 100 and so on for higher order. #NB: assumes Qiskit ordering if qr is None: raise Exception("Need to operate on a quantum register.") if circ is None: raise Exception("Need to operate on a circuit.") num_qubits = len(qr) if num_qubits==1: circ.x(qr[0]) return circ else: if num_qubits > 3: if qancilla is None: qancilla = QuantumRegister(num_qubits - 2) circ.add_register(qancilla) print("Warning: adding ancilla ", qancilla.name) for i in range(1, num_qubits): if i > 1: circ.x(qr[i-1]) if i == 1: circ.cx(qr[0], qr[i]) else: if i == 2: circ.ccx(qr[0], qr[1], qr[i]) else: circ.mct(qr[0:i], qr[i], qancilla, mode="v-chain") if i == (num_qubits - 1): circ.x(qr[0:i]) return qancilla def diagonal_permutation_circuit(qr=None, angle=None, circ=None): #default angle for permutation dagger (+ angle) if qr is None: raise Exception("Need to operate on a quantum register.") if circ is None: raise Exception("Need to operate on a circuit.") n = len(qr) if angle is None: angle = 2*np.pi/(1<<n) for i in range(0,n): #circ.u1(angle*(1<<i), qr[i]) circ.p(angle*(1<<i), qr[i]) def multiplex_diagonal_permutation_circuit(qcontrol=None, qr=None, angle=None, circ=None): #create control permutation_dagger_permutation circuit. This circuit comes from Shende and Bullock, a multiplexed diagonal is a multiplexed Rz gate. Since we have very special structure to the diagonal elements, the multiplexed recursion is short-circuited! if circ is None: raise Exception("Need to operate on a circuit.") if (qr is None) or (qcontrol is None): raise Exception("Need to operate on a quantum registers") if (type(qcontrol) != Qubit): raise Exception("Need first argument to be the single control qubit.") n = len(qr) + 1 if angle is None: angle = 2*np.pi/(1<<(n-1)) for i in range(0,n-1): circ.cx(qcontrol, qr[i]) #circ.u1(angle*(1<<i), qr[i]) circ.p(angle*(1<<i), qr[i]) circ.cx(qcontrol, qr[i]) #circ.u1(-angle*((1<<(n-1))-1), qcontrol) circ.p(-angle*((1<<(n-1))-1), qcontrol) # technically need to inverse(), since the algorithm takes desired state to zero but can use circ.mirror(). With mirror we do not take the minus sign of the desired angle, but with inverse we would have had to. Finally, we do not even need to call mirror because recursion is short-circuited and this particular circuit is invariant to mirroring because all the subparts commute: the target of CNOTs between subparts are different and U1 on source commutes with CNOT. def control_permutation_circuit(qcontrol=None, count_register=None, angle=None, qancilla=None, circ=None, leave_out_W=False, leave_out_V=False): if circ is None: raise Exception("Need to operate on a circuit.") if (count_register is None) or (qcontrol is None): raise Exception("Need to operate on a quantum registers") if (type(qcontrol) != Qubit): raise Exception("Need first argument to be the single control qubit.") num_count_qubits = len(count_register) if angle is None: angle = 2*np.pi/(1 << (num_count_qubits + 1)) ########## AAAAAAAAAAAAAA DOCUMENT!!! This is taking the square root! D^2 is the diagonal of the permutation matrix, D is the square root of D^2 count_register_flipped = count_register[::-1] # iqft_inst = QFT(num_count_qubits, inverse=True, # do_swaps=False).to_instruction() iqft_inst = QFT(num_count_qubits, do_swaps=False).inverse().to_instruction() qft_inst = QFT(num_count_qubits, inverse=False, do_swaps=False).to_instruction() # iqft_inst = QFT(num_count_qubits, do_swaps=False).inverse().to_instruction() # qft_inst = QFT(num_count_qubits, inverse=False, # do_swaps=True).to_instruction() # W in paper if not leave_out_W: qancilla = permutation_circuit(count_register, qancilla, circ=circ) # Fourier_circ.construct_circuit(circ, count_register, # inverse=True, do_swaps=False) circ.append(iqft_inst, count_register_flipped)#count_register) #In the forward Fourier circuit, the swaps come at the beginning, for the inverse, the swaps come at the end. Switching off the swaps implies that after this inverse circuit, the ordering significance is now swapped and subsequent placement of gates must be flipped. # diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ) diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ) #gates are flipped because one swap is missing (the significance is swapped) # (D D^) in paper #multiplex_diagonal_permutation_circuit(qcontrol, count_register_flipped, angle=angle, circ=circ) multiplex_diagonal_permutation_circuit(qcontrol, count_register_flipped, angle=angle, circ=circ) #gates still flipped because one swap is missing # V in paper # Fourier_circ.construct_circuit(circ, count_register, inverse=False, do_swaps=False) if not leave_out_V: circ.append(qft_inst, count_register_flipped) # count_register) #with swaps off at the beginning, the flipped significance is already in the flipped order required for the subsequent placement of gates, thereafter everything is back to normal return qancilla ################################################## # def rccx(circ, qubit0, qubit1, target_qubit): # circ.ry(np.pi/4, target_qubit) # circ.cx(qubit1, target_qubit) # circ.ry(np.pi/4, target_qubit) # circ.cx(qubit0, target_qubit) # circ.ry(-np.pi/4, target_qubit) # circ.cx(qubit1, target_qubit) # circ.ry(-np.pi/4, target_qubit) def num_complex_projections(powers=[1], sqrt=False): sum_projections = 0 coeff = 1 if sqrt else 2 for p in powers: sum_projections += coeff*p + 1 return sum_projections # flag register: n/2 qubits # Code up n-1 rounds of n/2 CCNOTS. Placing the gate only if the pair under consideration is not (is) present in edges_in. # mid-circuit measurement on the flag register # Bail out if flag register is not all ones (zeros) def project_onto_complex(circ, edges_in, simplex_qreg, simplex_in, measure_reg=None, num_resets=1, do_rccx=True): #simplex_in flag register of size n/2 #measure_reg size n C 2 #edges_in are pairs of points. points are identified by their point index (starting at 0) #edges_in must be list of list num_main_qubits = len(simplex_qreg) num_pairs = num_main_qubits*(num_main_qubits - 1)//2 half_num_main_qubits = num_main_qubits//2 if measure_reg is not None: if (half_num_main_qubits != len(simplex_in)): raise ValueError("Size of simplex_in register, " "does not equal n/2.") else: if (num_pairs != len(simplex_in)): raise ValueError("Size of simplex_in register, " "does not equal num_pairs.") if not isinstance(edges_in, list): raise ValueError("edges_in not a list of a list of two ints.") for pair in edges_in: if not isinstance(pair, list) or len(pair) != 2: raise ValueError("edges_in does not contain lists of two ints.") if not isinstance(pair[0], int) or not isinstance(pair[1], int): raise ValueError("edges_in inner lists do not contain ints.") top_qubits = np.arange(num_main_qubits) bottom_qubits = np.arange(num_main_qubits) bottom_qubits = np.roll(bottom_qubits,-1) # gates = [] for count_round in range(1, half_num_main_qubits+1): # R from spreadsheet count_round_from_zero = count_round - 1 pair_qubits = np.array([*zip(top_qubits, bottom_qubits)]) take = 1 << (first_non_zero_bit(count_round)) #the last round only has one inner_round if count_round < half_num_main_qubits: rounds = [0, 1] else: rounds = [0] for inner_round in rounds: take_in_a_row = np.array(range(take)) take_indices = np.zeros((half_num_main_qubits), dtype=int) for i in range((half_num_main_qubits)//take): take_indices[i*take:(i+1)*take] = \ (take_in_a_row + i*(2*take) + inner_round*take) % num_main_qubits for pairs_index, pair in enumerate(pair_qubits[take_indices].tolist()): if pair not in edges_in: # consider using bisect search of sorted list pair.reverse() if pair not in edges_in: if measure_reg is not None: qubits = (pair[0], pair[1], simplex_in[pairs_index]) else: qubits = (pair[0], pair[1], simplex_in[ count_round_from_zero*num_main_qubits + inner_round*half_num_main_qubits + pairs_index]) if do_rccx: circ.rccx(*qubits) # rccx(circ, *qubits) else: circ.ccx(*qubits) if measure_reg is not None: # could use: circ._mid_circuit, but prefer not to delve into internals circ.measure(simplex_in, measure_reg[ count_round_from_zero*num_main_qubits + inner_round*half_num_main_qubits: count_round_from_zero*num_main_qubits + (inner_round+1)*half_num_main_qubits]) for _ in range(num_resets): circ.reset(simplex_in) bottom_qubits = np.roll(bottom_qubits, -1) return circ ####################################################################### ### SPLIT BY SIMPLEX DEGREE K (entangle with counter reg, then PROJECT) ####################################################################### def split_k(circ, from_qreg, counter_qreg, qancilla=None): # , reshuffle=False): # PROJECTION ONTO K-SIMPLICES #warning, code similar to within control_permutation_circuit count_register_flipped = counter_qreg[::-1] num_count_qubits = len(counter_qreg) angle = -2*np.pi/(1 << (num_count_qubits + 1)) # separate by k for k-simplices for i in range(len(from_qreg)): leave_out_W = True if i > 0 else False leave_out_V = True if i < len(from_qreg)-1 else False qancilla = control_permutation_circuit(from_qreg[i], counter_qreg, qancilla=qancilla, circ=circ, leave_out_V=leave_out_V, leave_out_W=leave_out_W) if leave_out_V: diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ) return qancilla # #make 1 and 2, 1x neighbours, if we measure counter_qreg[1], it collapses the entangled simplices # if reshuffle: # circ.cx(counter_qreg[0], counter_qreg[1]) #interfere neighbours -> not necessary (maybe it could help later?) #circ.h(counter_qreg[0]) def split_k_inverse(circ, from_qreg, counter_qreg): # TODO: decide what to do about qancilla tempCirc = QuantumCircuit(from_qreg, counter_qreg) split_k(tempCirc, from_qreg, counter_qreg) circ.data += tempCirc.inverse().data def num_split_projections(powers=[1], sqrt=False): sum_projections = 0 add_proj = 0 if sqrt else 1 intdiv = 2 if sqrt else 1 for p in powers: sum_projections += p//intdiv + 1 return sum_projections ####################################################################### ############################################ ### OTHER HELPER FUNCTIONS ############################################ def initialize_register(qcirc, complex_vector, qreg, inverse=False): circ_complex = QuantumCircuit(qreg) myinit = Initialize(complex_vector) circ_complex.append( myinit.gates_to_uncompute().to_instruction(), qreg) if inverse: qcirc += circ_complex else: qcirc += circ_complex.inverse() def unroll_projections(list_projs): unrolled_proj = [] for projs in list_projs: unrolled_proj.extend(projs) return unrolled_proj def advanced_index_selecting_diagonal_of_split_k(laplacian): # Old: # select_dim = [0, 0] # select_dim.extend(list(np.ones( # laplacian._num_complex_projections, dtype=int) # * ((1 << num_pairs) - 1))) # select_dim.extend([np.array(range(1, num_main_qubits + 1), dtype=int) # for _ in # range( # laplacian._num_split_projections)]) num_main_qubits = laplacian._num_main_qubits advanced_index_array_base = np.arange(1, num_main_qubits, dtype=int) # This is counting vertices, 1, num_main_qubits+1 is from 1 to num_main_qubits, inclusive. Careful if complex is fully connected, introduce check or wrap % num_main_qubits - 1, or leave out num_main_qubits, yes do this advanced_index_array = np.zeros(num_main_qubits - 1, dtype=int) for i in range(laplacian._num_split_projections): advanced_index_array += \ advanced_index_array_base*(1 << (i*laplacian._count_bits_per_projection)) return advanced_index_array def reshape_into_tensor_of_dim_main_ancilla_proj_split(circ_output, laplacian): # Old: # reshape_dim = np.zeros(2 + laplacian._num_complex_projections + # laplacian._num_split_projections, dtype=int) # reshape_dim[0] = 1 << num_main_qubits # reshape_dim[1] = 1 << laplacian._num_clean_ancillae # reshape_dim[2:2+laplacian._num_complex_projections] = \ # np.ones(laplacian._num_complex_projections) *\ # (1 << num_pairs) # reshape_dim[2+laplacian._num_complex_projections:] = \ # np.ones(laplacian._num_split_projections) *\ # (1 << laplacian._count_bits_per_projection) # output_tensor = circ_output.reshape(tuple(reshape_dim), # order='F') output_tensor = circ_output.reshape( 1 << laplacian._num_main_qubits, 1 << laplacian._num_clean_ancillae, 1 << laplacian._num_complex_projections*laplacian._num_pairs, 1 << laplacian._num_split_projections* \ laplacian._count_bits_per_projection, order='F') return output_tensor ####################################################################### ####################################################################### ############################################################ ### MAIN CLASSES TO CREATE CIRCUITS FOR MOMENTS OF LAPLACIAN ############################################################ class Projected_Laplacian(QuantumCircuit): # Since Laplacian is implemented using Taylor expansion # a lot of post-processing is required # leave out first projection because assuming only one simplex already in # the complex (Ken) -> yes option open again? -> no, because using # Rademacher vectors """ Direct Unitary Method: boundary_operator_unitary_circuit(num_vertices) """ def __init__(self, *, num_vertices=None, edges_in=None, power=1, num_ancillae_eigenvalue_resolution=0, sqrt=False, mid_circuit=False, num_resets=None, do_rccx=True): # Registers: _main_qreg, _clean_ancilla, _reusable_qreg OR (_complex_qregs AND _split_qregs) # Size: _num_main_qubits, _num_clean_ancillae, ._num_projection_qubits (= _half_num_main_qubits* OR # (_num_complex_projections*_num_pairs + # _num_split_projections*_count_bits_per_projection)) #################################################### # Consume num_vertices, edges_in #################################################### if num_vertices is None: raise(ValueError("num_vertices not specified from which to build up complex.")) if edges_in is None: raise(ValueError("edges_in not specified from which to build up complex.")) # TODO: worry about user inputing the wrong size edges_in self._edges_in = edges_in # self._num_pairs = len(edges_in) # self._num_qubits = num_qubits_from_num_pairs(self._num_pairs) if not is_power_of_2(num_vertices): raise ValueError("For now, num_vertices must be a power of two.") self._num_main_qubits = num_vertices # consider getting from largest vertex in edges_in, nah, see remap self._half_num_main_qubits = num_vertices // 2 self._num_pairs = num_vertices*(num_vertices-1)//2 self._main_qreg = QuantumRegister(self._num_main_qubits, "mainqreg") super().__init__(self._main_qreg) self._count_bits_per_projection = num_bits(self._num_main_qubits) # Should be number + 1, to store the all-vertex simplex. Decided to save that bit (we're in the case of power of 2). We could introduce check for the fully connected one-skeleton and return something meaningful, but rather just say we're not interested in simplices of order num_vertices, which is the case. self._num_permutation_ancillae = max(0, self._count_bits_per_projection - 2) if not mid_circuit: # and self._num_permutation_ancillae > 0: self._num_clean_ancillae = max(self._num_permutation_ancillae, 1) # max(# self._num_pairs, # n^2 vs logn, don't need. The 1 is for boundary. # in NISQ it may be better to have separate registers to limit # noise? or use mid-circuit reset!! self._clean_ancilla = AncillaRegister(self._num_clean_ancillae, # could multiply by numsplit and measure all at the end as a noise detection scheme name="clean_ancillae") self.add_register(self._clean_ancilla) else: # for the case mid_circuit=True, we still don't need extra quantum ancillae, even though we could get classical ancillae answers out. TODO: do just that for error mitigation. self._num_clean_ancillae = 0 self._clean_ancilla = None #################################################### # Consume power, num_ancillae_eigenvalue_resolution #################################################### self.base_power = power self._num_ancillae_eigenvalue_resolution = \ int(num_ancillae_eigenvalue_resolution) if self._num_ancillae_eigenvalue_resolution > 0: self.powers = [int(self.base_power*(2**i)) for i in range( self._num_ancillae_eigenvalue_resolution)] self._control_reg_consolidate = QuantumRegister(1) self.add_register(self._control_reg_consolidate) if self._num_ancillae_eigenvalue_resolution == 1: self._control_reg = None else: self._control_reg = QuantumRegister(self._num_ancillae_eigenvalue_resolution) self.add_register(self._control_reg) else: self.powers = [int(self.base_power)] self._control_reg_consolidate = None #################################################### # Consume sqrt, mid_circuit #################################################### self._sqrt = sqrt self._mid_circuit = mid_circuit self._num_complex_projections = num_complex_projections(self.powers, self._sqrt) self._num_split_projections = num_split_projections(self.powers, self._sqrt) if mid_circuit: self._reusable_qreg = AncillaRegister( max(self._half_num_main_qubits, self._count_bits_per_projection + self._num_permutation_ancillae, 1), name="reusableprojqreg") # Complex projection (always the max), Order projection (count + mct), boundary circ exponentiate Z on target self._num_projection_qubits = len(self._reusable_qreg) self.add_register(self._reusable_qreg) self._boundary_sum_unitary_circuit = \ boundary_operator_unitary_circuit(self._main_qreg, self._reusable_qreg, # don't worry whole reg not used self._control_reg_consolidate) # consider reset -> yes see power else: self._boundary_sum_unitary_circuit = \ boundary_operator_unitary_circuit(self._main_qreg, self._clean_ancilla, self._control_reg_consolidate) self._complex_qregs = [] self._split_qregs = [] for power in self.powers: projections_for_power = [] power_num_complex_projections = num_complex_projections([power], self._sqrt) for projection in range(power_num_complex_projections): projections_for_power.append( AncillaRegister(self._num_pairs, name="power" + str(power) + "complexqproj" + str(projection))) self._complex_qregs.append(projections_for_power) projections_for_power = [] power_num_split_projections = num_split_projections([power], self._sqrt) for projection in range(power_num_split_projections): projections_for_power.append( AncillaRegister(self._count_bits_per_projection, name="power" + str(power) + "splitqproj" + str(projection))) self._split_qregs.append(projections_for_power) self.add_register(*unroll_projections(self._complex_qregs), *unroll_projections(self._split_qregs)) self._num_projection_qubits = self._num_complex_projections*self._num_pairs + \ self._num_split_projections*self._count_bits_per_projection #technically don't need _main_creg at all, if backend is statevector_simulator, but can't check here, because don't know what backend is, no need to pass because no harm if created. if self._sqrt: self._main_creg = ClassicalRegister(self._num_main_qubits) self.add_register(self._main_creg) else: self._main_creg = ClassicalRegister(1) self.add_register(self._main_creg) self._complex_cregs = [] self._split_cregs = [] for power in self.powers: projections_for_power = [] for projection in range(num_complex_projections([power], self._sqrt)): projections_for_power.append( ClassicalRegister(self._num_pairs, name="power" + str(power) + "complexcproj" + str(projection))) self._complex_cregs.append(projections_for_power) projections_for_power = [] for projection in range(num_split_projections([power], self._sqrt)): projections_for_power.append( ClassicalRegister(self._count_bits_per_projection, name="power" + str(power) + "splitcproj" + str(projection))) self._split_cregs.append(projections_for_power) self.add_register(*unroll_projections(self._complex_cregs), *unroll_projections(self._split_cregs)) self._num_total_qubits = self._num_main_qubits + self._num_clean_ancillae + \ self._num_projection_qubits # Uncomment to use as a form of error detection # # put at end (first in count list) to allow for easier removal # if (not mid_circuit) and self._num_permutation_ancillae > 0: # self._clean_ancilla_creg = ClassicalRegister( # self._num_permutation_ancillae) # self.add_register(self._clean_ancilla_creg) # else: # self._clean_ancilla_creg = None # # should actually peal away case of mid-circuit and possibly measure # # for split_projection as a noise detection mechanism! also reset reusable quantum register # Both mid_circuit=True and False need classical registers #################################################### # Consume num_resets and do_rccx #################################################### if num_resets is None: self._num_resets = int(mid_circuit) else: self._num_resets = num_resets if mid_circuit: if num_resets == 0: print("Warning: mid_circuit==True and num_resets==0.") elif num_resets > 0: print("Warning: mid_circuit==False but num_resets>0.") self._do_rccx = do_rccx def measure_all_qregs(self): """Only to be called for "count" backends (sim or hardware), not to be called for statevector backends. Place measurements on projection registers if mid_circuit is false. Always place measurements on main register (sqrt uses all counts on main reg, not sqrt uses 0 of main reg)! Technically don't need to place measurements on ancillae, but could be used to check for errors?""" if self._sqrt: self.measure(self._main_qreg, self._main_creg) else: self.measure(self._main_qreg[0], self._main_creg[0]) if not self._mid_circuit: for qreg_for_power, creg_for_power in zip(unroll_projections(self._complex_qregs), unroll_projections(self._complex_cregs)): self.measure(qreg_for_power, creg_for_power) for qreg_for_power, creg_for_power in zip(unroll_projections(self._split_qregs), unroll_projections(self._split_cregs)): self.measure(qreg_for_power, creg_for_power) # uncomment to use as a form of error detection also introduce such measurements for # mid_circuit=True in the loop # if self._num_clean_ancillae > 0: # self.measure(self._clean_ancilla, self._clean_ancilla_creg) def split_ancillae(self): if self._num_permutation_ancillae > 0: return self._clean_ancilla[:self._num_permutation_ancillae] else: return None def power(self, power, matrix_power=False): # Warning returns first entry only, but should only have one and only one # Note not storing power, so .power(2).control() won't control the square, rather: .control(power=2) -> reconsider this now that control automatically handled? if matrix_power: raise Exception("Matrix Power not supported") power_index = self.powers.index(power) count_complex_projection = 0 count_split_projection = 0 def place_complex_projection(): nonlocal count_complex_projection if self._mid_circuit: complex_qreg = self._reusable_qreg[:self._half_num_main_qubits] # self._num_pairs] complex_creg = self._complex_cregs[power_index][count_complex_projection] else: complex_qreg = self._complex_qregs[power_index][count_complex_projection] complex_creg = None project_onto_complex(self, self._edges_in, self._main_qreg, complex_qreg, complex_creg, self._num_resets, do_rccx=self._do_rccx) count_complex_projection += 1 def place_split_projection(): nonlocal count_split_projection if self._mid_circuit: split_qreg = self._reusable_qreg[:self._count_bits_per_projection] ancilla_qreg = self._reusable_qreg[self._count_bits_per_projection:] else: split_qreg = self._split_qregs[power_index][count_split_projection] ancilla_qreg = self.split_ancillae() split_k(self, self._main_qreg, split_qreg, qancilla=ancilla_qreg) # self.split_ancillae()) if self._mid_circuit: self.measure(split_qreg, self._split_cregs[power_index][count_split_projection]) for _ in range(self._num_resets): self.reset(split_qreg) count_split_projection += 1 place_complex_projection() place_split_projection() if self._sqrt: number_of_PB_pairs = power else: number_of_PB_pairs = 2*power for i in range(number_of_PB_pairs): self += self._boundary_sum_unitary_circuit # automatically caters for control if self._mid_circuit: for _ in range(self._num_resets): self.reset(self._reusable_qreg[0]) # boundary circuit uses the first qubit of the reusable register as the ancilla place_complex_projection() if (i % 2): place_split_projection() def control(self, num_ctrl_qubits=None, label=None, ctrl_state=None, power=1, use_basis_gates=True): # TODO: write unit tests and use in QPE # overloading, not controlling projection since shouldn't change anything? # consider doing the 'wrong' black-box control! if num_ctrl_qubits is None: num_ctrl_qubits = self._num_ancillae_eigenvalue_resolution if label is None: label='c_{}'.format(self.name) if ctrl_state is not None: raise Exception("Not handling ctrl_state=True at the moment.") if self._control_reg is not None: self.mct(self._control_reg, self._control_reg_consolidate) self.power(power) class Project_and_Split(Projected_Laplacian): # TODO: still to write unit_tests def __init__(self, edges_in=None, num_vertices=None, mid_circuit=False): super().__init__(edges_in=edges_in, num_vertices=num_vertices, power=0, mid_circuit=mid_circuit) # self.power(0) class Projected_Boundary(Projected_Laplacian): def __init__(self, edges_in=None, num_vertices=None, power=1, num_ancillae_eigenvalue_resolution=0, mid_circuit=False): super().__init__(edges_in=edges_in, num_vertices=num_vertices, power=power, num_ancillae_eigenvalue_resolution=num_ancillae_eigenvalue_resolution, sqrt=True, mid_circuit=mid_circuit) ####################################################################### ####################################################################### # FUNCTIONS TO RUN CIRCUITS and POST-PROCESS ####################################################################### def print_unitary_and_trace(circ, trace=True): usim = BasicAer.get_backend('unitary_simulator') # usim = Aer.get_backend('aer_simulator') # laplacian.save_unitary() temp_circuit = transpile(circ, backend=usim, optimization_level=0) qobj = assemble(temp_circuit) unitary = usim.run(qobj).result().get_unitary() print_matrix(unitary, vecfunc=format_real) if trace: import pdb pdb.set_trace() def expectation_of_laplacian(*, num_vertices, edges_in, vec_in=None, vec_in_circ=None, power=1, mid_circuit=False, sqrt=True, num_resets=None, job_name=None, backend_name="aer_simulator_statevector", rename_job_after_done=False, do_rccx=True, noise=None, shots=None): def rename_job(job): nonlocal job_name nonlocal backend_local_sim nonlocal rename_job_after_done job_name = job_name + "_" + secrets.token_urlsafe(8) if not backend_local_sim and rename_job_after_done: # not isinstance(job, BasicAerJob) print("Renaming ibmq job to: ", job_name) job.update_name(job_name) if vec_in is not None and vec_in_circ is not None: raise ValueError("Error: vec_in and vec_in_circ specified. Specify one or neither.") # TODO: rather check type of single argument else: qreg_temp = QuantumRegister(num_vertices) vec_circ = QuantumCircuit(qreg_temp) if vec_in is not None: initialize_register(vec_circ, vec_in, qreg_temp) elif vec_in_circ is not None: vec_circ = vec_in_circ else: vec_circ.h(qreg_temp) vec_circ_inst = vec_circ.to_instruction() vec_circ_inverse_inst = vec_circ.copy().inverse().to_instruction() result = None if backend_name is None: backend_any_asked = True else: backend_any_asked = False backend_local_sim = (backend_name == 'qasm_simulator' or # old python simulator backend_name == 'statevector_simulator' or # old python backend_name == 'aer_simulator_statevector' or # new C++ backend_name == 'aer_simulator_statevector_gpu' or # new GPU backend_name == 'aer_simulator_density_matrix' or # new C++ backend_name == 'aer_simulator_density_matrix_gpu') # new GPU gpu = (backend_name == 'aer_simulator_statevector_gpu' or backend_name == 'aer_simulator_density_matrix_gpu') if backend_local_sim: if mid_circuit or noise is not None: if backend_name == 'statevector_simulator': raise ValueError('mid_circuit/noise not compatible with old statevector ' 'simulator') backend = Aer.get_backend(backend_name) if gpu: backend.device="GPU" # should not be needed backend.set_options(batched_shots_gpu=True) backend.set_options(batched_shots_gpu_max_qubits=32) if shots is None: shots = 50000 if noise is not None: # Error probabilities prob_1 = noise[0] # 1-qubit gate prob_2 = noise[1] # 2-qubit gate prob_mat = [[1-prob_2,prob_2],[prob_2,1-prob_2]] # Depolarizing quantum errors error_1 = qnoise.depolarizing_error(prob_1, 1) error_2 = qnoise.depolarizing_error(prob_2, 2) read_err = qnoise.ReadoutError(prob_mat) # Add errors to noise model noise_model = qnoise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) noise_model.add_all_qubit_readout_error(read_err) # Get basis gates from noise model basis_gates = noise_model.basis_gates backend.set_options(noise_model=noise_model, basis_gates=basis_gates) else: noise_model = None # mybackend_shots = 80000 # backend._configuration.n_qubits = 24 # if backend_name == 'qasm_simulator': # backend._configuration.max_shots = 2*10**3#10**6 #1000 # 10**7 else: backend = None if backend_name == "ionq_qpu": provider = IonQProvider("YKI565sxYHK1Pe3w4mRRHOQ6EvhbGXeF") # print(provider.backends()) backend = provider.get_backend("ionq_qpu") if shots is None: shots = 100 # backend._configuration.max_shots elif backend_name == "HQS-LT-S1-SIM" or backend_name == "HQS-LT-S2-SIM" \ or backend_name == "HQS-LT-S1" or backend_name == "HQS-LT-S2": Honeywell.load_account() backend = Honeywell.get_backend(backend_name) if shots is None: shots = 2000 else: if IBMQ.active_account() is None: IBMQ.enable_account(\ 'ec1952054b99bc0febe3c3d296521da193190fb4f9c3925d7' 'b7a015c443240f07263c4f9b6bdbf1a0c99f6fe7451af029b' '2c52d06f222e94bc467f14b8e2adf6') provider = IBMQ.get_provider(hub='ibm-q-internal') # ('ibm-q-internal') if backend_name is not None: backend = provider.get_backend(backend_name) if job_name is not None: past_days = datetime.now() - timedelta(days=JOB_PREVIOUS_DAYS) # Add local tz in order to compare to `creation_date` which is tz aware. # past_days_tz_aware = past_days.replace(tzinfo=tz.tzlocal()) if backend is None: myjobs = provider.backends.jobs(limit=JOB_RETRIEVE_LIMIT, start_datetime=past_days) else: myjobs = backend.jobs(limit=JOB_RETRIEVE_LIMIT, start_datetime=past_days) myjob_dict = {myjob.name():myjob for myjob in myjobs} if job_name in list(myjob_dict): myjob_status = myjob_dict[job_name].status() if backend is None: backend = myjob_dict[job_name].backend() backend_name = backend.name() if myjob_status is not JobStatus.DONE: print("Found job: ", job_name, ", Status is: ", myjob_status, ". Rerun later.") return (backend_name, job_name) else: result = myjob_dict[job_name].result() print("Found job: ", job_name, ", Status is: ", myjob_status, ".") rename_job(myjob_dict[job_name]) # Need the laplacian object to choose hardware backend, run and/or to analyse results laplacian = Projected_Laplacian(num_vertices=num_vertices, edges_in=edges_in, power=power, mid_circuit=mid_circuit, sqrt=sqrt, num_resets=num_resets, do_rccx=do_rccx) q_main_reg = laplacian._main_qreg num_main_qubits = laplacian._num_main_qubits num_pairs = laplacian._num_pairs num_total_qubits = laplacian._num_total_qubits if result is None: if backend is None: # when sim is False and no job found available_devices = provider.backends( filters=lambda x: (x.configuration().n_qubits >= num_total_qubits) and (not x.configuration().simulator)) # and x.status().operational==True) if not available_devices: raise AssertionError("No available devices with at least " + str(num_total_qubits) + " qubits.") backend = least_busy(available_devices) backend_name = backend.configuration().backend_name backend_any_asked = True print("Least Busy Backend:", backend_name) if shots is None: shots = backend._configuration.max_shots # CIRCUIT CONSTRUCTION laplacian.append(vec_circ_inst, qargs=q_main_reg) laplacian.power(power) # already taking into account sqrt (during _init_) if not sqrt: # here and below could use laplacian._sqrt to emphasise laplacian, chose not to since did assign local variables to other laplcian variables laplacian.append(vec_circ_inverse_inst, qargs=q_main_reg) # print_unitary_and_trace(laplacian) if backend_name != 'statevector_simulator': # may need to check for ibmq statevector_simulator laplacian.measure_all_qregs() if backend.configuration().n_qubits == 27: if num_main_qubits == 2: if mid_circuit: rqreg = laplacian._reusable_qreg initial_layout = {q_main_reg[0]: 11, q_main_reg[1]: 16, rqreg[0]: 14} else: cqreg = laplacian._complex_qregs[0] sqreg = laplacian._split_qregs[0] aqreg = laplacian._clean_ancilla initial_layout = {q_main_reg[0]: 11, q_main_reg[1]: 16, aqreg[0]: 14, sqreg[0][0]: 13, cqreg[0][0]: 8, cqreg[1][0]: 19} elif num_main_qubits >= 4: if mid_circuit: rqreg = laplacian._reusable_qreg initial_layout = {q_main_reg[0]: 11, q_main_reg[1]: 16, q_main_reg[2]: 15, q_main_reg[3]: 10, rqreg[0]: 14, rqreg[1]: 12} #rqreg[2]: 13} else: cqreg = laplacian._complex_qregs[0] sqreg = laplacian._split_qregs[0] aqreg = laplacian._clean_ancilla initial_layout = {q_main_reg[0]: 11, q_main_reg[1]: 16, q_main_reg[2]: 15, q_main_reg[3]: 10, aqreg[0]: 13, sqreg[0][0]: 14, sqreg[0][1]: 12, cqreg[0][0]: 8, cqreg[0][1]: 19, cqreg[0][2]: 18, cqreg[0][3]: 7, cqreg[0][4]: 5, cqreg[0][5]: 22, cqreg[1][0]: 9, cqreg[1][1]: 20, cqreg[1][2]: 17, cqreg[1][3]: 6, cqreg[1][4]: 21, cqreg[1][5]: 4} else: initial_layout = None else: initial_layout = None # RUN CIRCUIT unrolled_laplacian = transpile(laplacian, backend=backend, seed_transpiler=11, optimization_level=0) optimized_laplacian = transpile(laplacian, backend=backend, seed_transpiler=11, optimization_level=3, initial_layout=initial_layout) print("width: ", optimized_laplacian.width(), "depth: ", optimized_laplacian.depth()) if backend_name == "ionq_qpu": job = backend.run(optimized_laplacian, shots=shots) import time while job.status() is not JobStatus.DONE: print("Job status is", job.status()) time.sleep(60) result = job # sic, weird IonQ convention if rename_job_after_done: print("Warning: Ignoring rename job on IonQ server, no functionality.") rename_job_after_done = False rename_job(job) elif backend_name == "HQS-LT-S1-SIM" or backend_name == "HQS-LT-S2-SIM" \ or backend_name == "HQS-LT-S1" or backend_name == "HQS-LT-S2": job_honey = execute(optimized_laplacian, backend, shots=shots) job_honey_id = job_honey.job_ids()[0] print("Honeywell Job id: ", job_honey_id) return (backend_name, job_honey_id) else: if job_name is None: job_name = str(num_vertices) + "_" \ + ("True" if mid_circuit else "False") + "_" \ + ("True" if sqrt else "False") job = execute(optimized_laplacian, backend, job_name=job_name, shots=shots) # time.sleep(5) if job.status() is JobStatus.DONE or backend_local_sim: result = job.result() rename_job(job) else: print("Job submitted, please rerun to collect results.") return (backend_name, job_name) else: print("Laplacian Original:") print("width: ", laplacian.width()) # print("depth: ", laplacian.depth()) -> zero if reached if backend_name == 'statevector_simulator': circ_output = result.get_statevector(optimized_laplacian) output_tensor = reshape_into_tensor_of_dim_main_ancilla_proj_split(circ_output, laplacian) main_qreg_select = slice(0, None) if sqrt else 0 advanced_index_array = advanced_index_selecting_diagonal_of_split_k(laplacian) expectation_laplacian = output_tensor[ main_qreg_select, 0, 0, advanced_index_array] if sqrt: expectation_laplacian = np.linalg.norm(expectation_laplacian, axis=0)**2 else: # 'qasm_simulator' or hardware counts = result.get_counts() counts_file = open("../output/" + (backend_name + "_" if backend_any_asked else "") + job_name + ".json", "w") json.dump(counts, counts_file) counts_file.close() frac_counts = np.array(get_fraction_count_for_all_k(counts, laplacian, sqrt)) expectation_laplacian = frac_counts if sqrt else np.sqrt(frac_counts) # num_Bs = power*(1 if sqrt else 2) not actual B's, but analytical number # num_Bs = power*2 #expectation_laplacian *= np.sqrt(num_vertices)**(num_Bs) # final correction since B = sqrt(n)RXR # expectation_laplacian *= num_vertices**power times (num_vertices^power) to correct for B, divide by to make largest eigenvalue 1 # expectation_laplacian[0] -= 1/(num_vertices**power) # correction for augmented Laplacian, see Goldeberg Page 42 v^T(P_kP_GBP_GBP_GP_k)v, since v^TUv = 0 for Hadamard vectors, we ignore this term return expectation_laplacian # if power > 0: # # expectation_projections = fraction_in_complex_of_all_orders(num_vertices=num_vertices, # # edges_in=edges_in, # # vec_in_circ=vec_circ) # # # Boundary squared = identity * num_main_qubits # # expectation_boundary_squared = expectation_projections*num_main_qubits # # expectation_laplacian = ((-1)**sqrt)*((expectation_projections - # # expectation_taylor)/(laplacian._time_evolution**2) - # # expectation_boundary_squared*power) # return expectation_laplacian # else: # return expectation_taylor def fraction_in_complex_of_all_orders(*, num_vertices, edges_in, vec_in=None, vec_in_circ=None, mid_circuit=False, sqrt=True, job_name=None, backend_name="statevector_simulator"): return expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in, vec_in=vec_in, vec_in_circ=vec_in_circ, power=0, mid_circuit=mid_circuit, sqrt=sqrt, job_name=job_name, backend_name=backend_name) # def average_expectation_over_random_two_local_vec_circs(num_vertices, edges_in, power=1, num_samples=1): # expectation_val = 0 # for i in range(num_samples): # random_circ = TwoLocal(num_vertices, 'ry', 'cx', 'linear', # parameter_prefix='theta', reps=1) # param_dict = {} # for param in random_circ.ordered_parameters: # param_dict[param] = np.random.rand()*2*np.pi # random_circ = random_circ.bind_parameters(param_dict) # expectation_run = expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in, # vec_in_circ=random_circ, # power=power, backend_name="statevector_simulator") # expectation_val += expectation_run # expectation_val = expectation_val/num_samples # return expectation_val def expectation_over_random_hadamard_vecs(num_vertices, edges_in, powers=[1], num_samples=10, noise = [0.001,0.1], expt_name= None, gpu = True): # expectation_val = 0 expectation_matrix = np.zeros((num_samples, int(len(powers)), num_vertices-1)) for sample in range(num_samples): random_circ = QuantumCircuit(num_vertices) count_h = 0 for i in range(num_vertices): if (np.random.rand() < 0.5): count_h+=1 random_circ.x(i) if count_h == 0: random_circ.x(np.random.randint(0,num_vertices)) for i in range(num_vertices): random_circ.h(i) for power_index, power in enumerate(powers): if expt_name is not None: job_name = expt_name+"degree"+str(power_index)+"sample"+str(sample) if gpu: b_name = "qasm_simulator" else: b_name = "ibmq_qasm_simulator" temp = expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in, vec_in_circ=random_circ, power=power, mid_circuit=True, backend_name=b_name, noise = noise, job_name = job_name, gpu = gpu) if isinstance(temp[0], str): continue else: expectation_matrix[sample, power_index, :] = temp else: expectation_matrix[sample, power_index, :] = \ expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in, vec_in_circ=random_circ, power=power, mid_circuit=True, backend_name="qasm_simulator", noise = noise) return expectation_matrix def help_setting_laplacian_arguments(num_vertices=4, mid_circuit=True, do_rccx=True, sqrt=True, num_resets=None, backend_name=None, make_edges_in=10, make_vec_in_circ=5, noise_lvl=None, shots=1000): if make_edges_in == 0: edges_in, min_num_vert, edges_in_type = [], 2, "noedge" elif make_edges_in == 1: edges_in, min_num_vert, edges_in_type = [[0,1]], 2, "edge" elif make_edges_in == 2: edges_in, min_num_vert = one_skeleton_triangle() edges_in_type = "triangle" elif make_edges_in == 3: edges_in, min_num_vert = one_skeleton_square() edges_in_type = "square" elif make_edges_in == 4: edges_in, min_num_vert = one_skeleton_tetrahedron() edges_in_type = "tetrahedron" elif make_edges_in == 5: edges_in, min_num_vert = one_skeleton_square_with_diagonal() edges_in_type = "square_diag" elif make_edges_in == 6: edges_in, min_num_vert = one_skeleton_pyramid() edges_in_type = "pyramid" elif make_edges_in == 7: edges_in, min_num_vert = one_skeleton_unfilled_cube() edges_in_type = "cube" elif make_edges_in == 8: edges_in, min_num_vert = one_skeleton_n_disconnected_squares(num_vertices) edges_in_type = "disconnected_squares" elif make_edges_in == 9: one_skel, _ = one_skeleton_fully_connected(num_vertices) edges_in = one_skel[:len(one_skel)//2] min_num_vert = num_vertices edges_in_type = "half_all_edges" elif make_edges_in == 10: one_skel, _ = one_skeleton_fully_connected(num_vertices//2) edges_in = one_skel + (np.array(one_skel) + [[num_vertices//2, num_vertices//2]]).tolist() min_num_vert = num_vertices edges_in_type = "two_fully_connected_clusters" else: raise ValueError("Unknown option for 'make_edges_in': ", make_edges_in) if min_num_vert > num_vertices: raise ValueError("Need more vertices than requested: " + str(min_num_vert) + " > " + str(num_vertices)) if make_vec_in_circ == 1: vec_in_circ = QuantumCircuit(num_vertices) for i in range(num_vertices): if (np.random.rand() < 0.5): vec_in_circ.x(i) for i in range(num_vertices): vec_in_circ.h(i) print(vec_in_circ._data) vec_in_circ_type = "random_vec" elif make_vec_in_circ == 2: vec_in_circ = QuantumCircuit(num_vertices) vec_in_circ.x(0) vec_in_circ.x(1) vec_in_circ_type = "edge_only_vec" elif make_vec_in_circ == 3: vec_in_circ = None vec_in_circ_type = "uniform_vec" elif make_vec_in_circ == 4: vec_in_circ = QuantumCircuit(num_vertices) vec_in_circ.x(0) vec_in_circ.h(1) vec_in_circ.cx(1, 0) vec_in_circ_type = "two_vertices_vec" elif make_vec_in_circ == 5: vec_in_circ = QuantumCircuit(num_vertices) vec_in_circ.x(0) for i in range(num_vertices): vec_in_circ.h(i) vec_in_circ_type = "fixed_rademacher" else: raise ValueError("Unknown option for 'make_vec_in_circ': ", make_vec_in_circ) if noise_lvl == 0: noise = None elif noise_lvl == 1: noise = [0.0001, 0.001] elif noise_lvl == 2: noise = [0.001, 0.01] elif noise_lvl == 3: noise = [0.01, 0.1] elif noise_lvl == 4: noise = [10**(-5), 10**(-4)] elif noise_lvl == 5: noise = [10**(-4), 0.001] elif noise_lvl == 6: noise = [0.0002, 0.002] elif noise_lvl == 7: noise = [0.0005, 0.005] elif noise_lvl == 8: noise = [0.001, 0.01] else: raise ValueError("Unknown option for 'noise_lvl': ", noise_lvl) job_name = ((backend_name + "_" if backend_name is not None else "") + edges_in_type + "_" + "vert_" + str(num_vertices) + "_" + "mid_circ_" + str(mid_circuit) + "_" + "sqrt_" + str(sqrt) + "_" + (("r_" + str(num_resets) + "_") if mid_circuit and num_resets is not None else "") + vec_in_circ_type + "_" + ("rccx_" if do_rccx else "ccx_") + (str(noise[0])+"_"+str(noise[1]) + "_" if noise is not None else "no_noise_") + "shots_" + ("*" if shots is None else str(shots))) return edges_in, min_num_vert, edges_in_type, vec_in_circ, vec_in_circ_type, noise, job_name ########################################################################## def compare_counts_hellinger(counts1, counts2): if isinstance(counts1, str): counts1 = json.load(open(counts1, "r")) elif not isinstance(counts1, dict): raise ValueError("Argument must be filename string or counts dictionary.") if isinstance(counts2, str): counts2 = json.load(open(counts2, "r")) elif not isinstance(counts2, dict): raise ValueError("Argument must be filename string or counts dictionary.") total1 = sum(counts1.values()) total2 = sum(counts2.values()) all_keys = set(list(counts1.keys()) + list(counts2.keys())) hellinger = 0 for key in all_keys: hellinger += (np.sqrt(counts1.get(key, 0)/total1) - np.sqrt(counts2.get(key, 0)/total2))**2 hellinger /= 2 return hellinger def compare_counts(counts1, counts2, interpret_counts_as_integers=False, wrap_at=0, kl_frac=True): if isinstance(counts1, str): counts1 = json.load(open(counts1, "r")) elif not isinstance(counts1, dict): raise ValueError("Argument must be filename string or counts dictionary.") if isinstance(counts2, str): counts2 = json.load(open(counts2, "r")) elif not isinstance(counts2, dict): raise ValueError("Argument must be filename string or counts dictionary.") total1 = sum(counts1.values()) total2 = sum(counts2.values()) matching_counts = [] if interpret_counts_as_integers: counts1_list_of_reg_strings = list(map(lambda count: count.split(), counts1.keys())) counts1keys = list(map(bin_string2int, counts1_list_of_reg_strings)) counts1values = list(counts1.values()) counts2_list_of_reg_strings = list(map(lambda count: count.split(), counts2.keys())) counts2keys = np.array(list(map(bin_string2int, counts2_list_of_reg_strings))) # if bug_fix_ancilla: # counts2keys = np.delete(counts2keys, -2, axis=1) # # uneccessarily long for noise, but saves me from calc lookup num_vertices_2 = len(counts2_list_of_reg_strings[0][-1]) counts2values = list(counts2.values()) for place_in_counts1, integer_list_key_in_counts1 in enumerate(counts1keys): if wrap_at: source_keys_count_reg = (integer_list_key_in_counts1[0] + np.arange(0, num_vertices_2, wrap_at)).reshape(-1,1) num_source = source_keys_count_reg.shape[0] remaining_regs = integer_list_key_in_counts1[1:] num_remaining = len(remaining_regs) group_keys = np.concatenate((source_keys_count_reg, np.broadcast_to(remaining_regs, (num_source, num_remaining))), axis=1).tolist() else: group_keys = [integer_list_key_in_counts1] accumulate_counts = 0 for integer_list_key_in_group in group_keys: look_for_key = np.all(counts2keys == integer_list_key_in_group, axis=1) place_in_counts2 = np.where(look_for_key)[0] if place_in_counts2.size > 0: accumulate_counts += counts2values[place_in_counts2[0]] if accumulate_counts == 0: print("KL: to infinity and beyond!") return np.inf matching_counts.append((counts1values[place_in_counts1], accumulate_counts)) else: for i in counts1.keys(): count2 = counts2.get(i) if count2 is None: print("KL: to infinity and beyond!") return np.inf matching_counts.append((counts1[i], count2)) matching_counts = np.array(matching_counts) kl_div = sum(rel_entr(matching_counts[:, 0]/total1, matching_counts[:, 1]/total2)) if kl_frac: num_qubits = sum(map(len, next(iter(counts2)).split())) entropy_counts1 = sum(entr(matching_counts[:, 0]/total1)) kl_div = kl_div/(num_qubits*np.log(2)-entropy_counts1) print("KL Fraction: ", kl_div) return kl_div else: print("KL: ", kl_div) return kl_div def merge_counts(dict_or_filenames_list, clip_val=None, keep_keys=None, template=None, salt_rest=False): merged_dict = {} if len(dict_or_filenames_list) == 0: ValueError("Argument must be filename string or counts dictionary list.") for counts_dict in dict_or_filenames_list: if isinstance(counts_dict, str): counts_dict = json.load(open(counts_dict, "r")) elif not isinstance(counts_dict, dict): raise ValueError("Argument must be filename string or counts dictionary list.") if template is not None: template = template[::-1] fixed_counts_dict = {} num_registers = len(template) expected_key_len = sum(template) for key in counts_dict: # if key =='1': # pdb.set_trace() actual_key_len = len(key) padded_key = '0'*(expected_key_len - actual_key_len) + key start_index = 0 end_index = template[0] # Reverse # start_index = -template[0] # end_index = expected_key_len new_key = '' for i in range(num_registers): new_key = padded_key[start_index:end_index] + new_key if i < num_registers-1: new_key = ' ' + new_key start_index = end_index end_index = end_index + template[i+1] # Reverse # end_index = start_index # start_index = start_index - template[i+1] fixed_counts_dict[new_key] = counts_dict[key] counts_dict = fixed_counts_dict for key in counts_dict: # actually don't need to run if only one dict old_val = merged_dict.get(key, 0) merged_dict[key] = old_val + counts_dict[key] normalize_count = sum(list(merged_dict.values())) if keep_keys is not None: new_dict = {} for key in keep_keys: old_val = merged_dict.get(key, 0) if old_val > 0: new_dict[key] = old_val else: new_dict = merged_dict if clip_val is not None: new_dict_2 = {} # normalize_count = 0 for key in new_dict: old_val = new_dict.get(key) # normalize_count += old_val if old_val > clip_val: new_dict_2[key] = old_val # del merged_dict[key] -> problem in for loop new_dict = new_dict_2 if (keep_keys or clip_val): new_dict['rest' + (secrets.token_urlsafe(8) if salt_rest else "")] = normalize_count-sum(new_dict.values()) # new_dict[key] = int((new_dict.get(key)/normalize_count)*10**6) # new_dict['rest'] = int(10**6-sum(new_dict.values())) return new_dict def load_merge_compare(list1, list2, interpret_counts_as_integers=True, wrap_at=0, kl_frac=True): list1_counts = merge_counts(list1) list1_counts_num_shots = sum(list1_counts.values()) list2_counts = merge_counts(list2) list2_counts_num_shots = sum(list2_counts.values()) print("List 1 counts:", list1_counts_num_shots) print("List 2 counts:", list2_counts_num_shots) kl = compare_counts(list1_counts, list2_counts, interpret_counts_as_integers=interpret_counts_as_integers, wrap_at=wrap_at, kl_frac=kl_frac) return kl def expectation_of_laplacian_json(filename, num_vertices, power=1, mid_circuit=True, sqrt=True, num_resets=None, do_rccx=True ): laplacian = Projected_Laplacian(num_vertices=num_vertices, edges_in=[], power=power, mid_circuit=mid_circuit, sqrt=sqrt, num_resets=num_resets, do_rccx=do_rccx) template = [laplacian._count_bits_per_projection]*laplacian._num_split_projections + [laplacian._num_pairs]*laplacian._num_complex_projections + [num_vertices] counts = merge_counts([filename], clip_val=None, keep_keys=None, template=template) frac_counts = np.array(get_fraction_count_for_all_k(counts, laplacian, sqrt)) expectation_laplacian = frac_counts if sqrt else np.sqrt(frac_counts) return expectation_laplacian def calc_circuit_depths(*, log_num_vertices_start=1, log_num_vertices_end=6, power=1, mid_circuit=False, sqrt=True, do_rccx=True, num_resets=None, backend_name_or_Fake="statevector_simulator"): # ibmq_qasm_simulator ibmq_armonk ibmq_montreal ibmq_toronto ibmq_santiago ibmq_bogota ibmq_manhattan ibmq_casablanca ibmq_sydney ibmq_mumbai ibmq_lima ibmq_belem ibmq_quito ibmq_guadalupe ibmq_brooklyn ibmq_jakarta ibmq_manila ibm_hanoi ibm_lagos ibm_cairo # https://github.com/Qiskit/qiskit-terra/tree/795e845bd83deda54c527bb3d750df00d9d03431/qiskit/test/mock/backends # properties = backend.properties() # coupling_map = backend.configuration().coupling_map # simulator = Aer.get_backend('qasm_simulator') depths = [] backend = None honeywell=False if backend_name_or_Fake == "ionq_simulator": from qiskit_ionq import IonQProvider provider = IonQProvider() # backend = provider.get_backend("ionq_simulator") # provider = IonQProvider("YKI565sxYHK1Pe3w4mRRHOQ6EvhbGXeF") # print(provider.backends()) # backend = provider.get_backend("ionq_qpu") elif backend_name_or_Fake in ['HQS-LT-S2-APIVAL', 'HQS-LT-S2-SIM', 'HQS-LT-S1-SIM', 'HQS-LT-S1-APIVAL', 'H1-2E', 'H1-1E']: Honeywell.load_account() # backends = Honeywell.backends() backend = Honeywell.get_backend(backend_name_or_Fake) honeywell=True elif backend_name_or_Fake == "statevector_simulator" or \ backend_name_or_Fake == "qasm_simulator": backend = BasicAer.get_backend(backend_name_or_Fake) elif backend_name_or_Fake.__class__.__bases__[0] is fake_pulse_backend.FakePulseBackend: backend = backend_name_or_Fake else: raise(ValueError("Error: backend_name_or_Fake not sim string or FakeBackend.")) # exec("from qiskit.test.mock import " + backend_name) # # Security risk! # exec("backend = " + backend_name + "()") # pass # Wow, weird error if leave out for log_num in range(log_num_vertices_start, log_num_vertices_end): num_vertices = 1 << log_num vec_circ = QuantumCircuit(num_vertices) for i in range(num_vertices//2): vec_circ.x(i) for i in range(num_vertices): vec_circ.h(i) vec_circ_inst = vec_circ.to_instruction() vec_circ_inverse_inst = \ vec_circ.copy().inverse().to_instruction() one_skel, _ = one_skeleton_fully_connected(num_vertices) half_one_skel = one_skel[:len(one_skel)//2] laplacian = Projected_Laplacian(num_vertices=num_vertices, edges_in=half_one_skel, power=power, mid_circuit=mid_circuit, sqrt=sqrt, num_resets=num_resets, do_rccx=do_rccx) q_main_reg = laplacian._main_qreg num_main_qubits = laplacian._num_main_qubits num_pairs = laplacian._num_pairs num_total_qubits = laplacian._num_total_qubits # CIRCUIT CONSTRUCTION laplacian.append(vec_circ_inst, qargs=q_main_reg) laplacian.power(power) # already taking into account sqrt (during _init_) if not sqrt: # here and below could use laplacian._sqrt to emphasise laplacian, chose not to since did assign local variables to other laplcian variables laplacian.append(vec_circ_inverse_inst, qargs=q_main_reg) # print_unitary_and_trace(laplacian) if backend_name_or_Fake != 'statevector_simulator': #may need to check for ibmq statevector_simulator laplacian.measure_all_qregs() unrolled_laplacian = transpile(laplacian, backend=backend, seed_transpiler=11, optimization_level=0) print(unrolled_laplacian.count_ops()) unrolled_depth = unrolled_laplacian.depth() print("width: ", unrolled_laplacian.width(), "depth: ", unrolled_depth) print("Laplacian Optimized:") optimized_laplacian = transpile(laplacian, backend=backend, seed_transpiler=11, optimization_level=3) print(optimized_laplacian.count_ops()) optimized_depth = optimized_laplacian.depth() print("width: ", optimized_laplacian.width(), "depth: ", optimized_depth) # if honeywell: # job = execute(unrolled_laplacian, backend) # print("HQC: ", job.__dict__)#job._experiment_results)#[0]['cost']) depths.append((num_vertices, unrolled_depth, optimized_depth)) return depths def produce_depths_plot(do_rccx=True): import matplotlib.pyplot as plot # depths_False_True = np.array(calc_circuit_depths(mid_circuit=False, # sqrt=True, do_rccx=do_rccx)) depths_True_True = np.array(calc_circuit_depths(log_num_vertices_end=8, mid_circuit=True, sqrt=True, do_rccx=do_rccx, power=3, backend_name_or_Fake="qasm_simulator")) # depths_True_True_Honeywell2 = np.array(calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True, # sqrt=True, do_rccx=do_rccx, # backend_name_or_Fake='H1-2E')) depths_True_True_Honeywell1 = np.array(calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True, sqrt=True, do_rccx=do_rccx, power=3, backend_name_or_Fake='H1-1E')) # backend_name_or_Fake="HQS-LT-S1-APIVAL")) # from qiskit.test.mock import FakeManhattan # fake_backend = FakeManhattan() # depths_True_True_fake = \ # np.array(calc_circuit_depths(mid_circuit=True, # sqrt=True, do_rccx=do_rccx, # backend_name_or_Fake=fake_backend)) # depths_True_True_IonQ = np.array(calc_circuit_depths(mid_circuit=True, # sqrt=True, do_rccx=do_rccx, # backend_name_or_Fake="ionq_simulator")) # mycolors = ('green', 'blue', 'orange', 'red') # mycirc_names = ('Statevector Simulation', 'Mid-circuit QASM all-to-all connectivity', 'Mid-circuit IonQ all-to-all connectivity', 'Mid-circuit IBM hardware connectivity') # circuits = [depths_False_True, depths_True_True, depths_True_True_IonQ, # depths_True_True_fake] # mycolors = ('blue', 'magenta') mycolors = ("#0c276c", "#7b1547") mydarkcolors = ("#648fff", "#dc006c") mycirc_names = ('QASM all-to-all connectivity', 'Ion-trap') circuits = [depths_True_True, depths_True_True_Honeywell1] fig, ax = plot.subplots() ax.set_title("Depth vs Num Vertices") ax.set_xlabel("Number of Vertices") ax.set_ylabel("Depth") for i, depths in enumerate(circuits): print("Depths: ", depths) ax.plot(depths[:, 0], depths[:, 1], label="Non-optimized " + mycirc_names[i], color=mycolors[i]) ax.plot(depths[:, 0], depths[:, 2], label="Optimized " + mycirc_names[i], color=mydarkcolors[i])#'dark'+mycolors[i]) ax.legend() plot.show() # plot.savefig("../output/circuit_depth_vs_vertices_with_honeywell" + ("rccx" if do_rccx else "ccx") + ".png") def honeywell_save_account_and_info(): Honeywell.save_account('lhoresh@us.ibm.com') Honeywell.load_account() # backend = Honeywell.get_backend('HQS-LT-S1-APIVAL') # backend = Honeywell.get_backend('HQS-LT-S2-APIVAL') backends = Honeywell.backends() print("Backends: ", backends) # for backend in honey_backends: # # backend = Honeywell.get_backend(backend_name) # print(backend._configuration.n_qubits) # raise(ValueError("Stop, but keep interpreter.")) # backend = Honeywell.get_backend('HQS-LT-S1-APIVAL') # backend = Honeywell.get_backend('HQS-LT-S2-APIVAL') def honeywell_retrieve_counts(backend_name, job_honey_id): Honeywell.load_account() backend = Honeywell.get_backend(backend_name) job = backend.retrieve_job(job_honey_id) result = job.result() counts = result.get_counts() print(counts) json.dump(counts, open('../output/' + job_honey_id + '.json', 'w')) edge_2_qasm = \ "../output/qasm_simulator_edge_2_True_True_r_None_uniform_vec_rccx_*.json" # wQwZaMMxCsc.json" square_4_qasm = \ "../output/qasm_simulator_square_4_True_True_r_None_uniform_vec_rccx_*.json" # Oo7V2RA5lHI.json" cube_8_qasm = \ "../output/qasm_simulator_cube_8_True_True_r_None_uniform_vec_rccx_2Wh8W7eFp9k.json" #_*.json" #DB7w1fJK6e4.json" edge_2_honeywell = \ "../output/32f5839d79674998aa80c261dfe8a1bb.json" square_4_honeywell = \ "../output/c90c48da23c448dc97f6054bd9d45cee.json" cube_8_honeywell = \ "../output/5b5a56527ed24073aab10011699e493d.json" if __name__ == '__main__': # depths = calc_circuit_depths(log_num_vertices_start=3, log_num_vertices_end=3, power=1, mid_circuit=True, backend_name_or_Fake='qasm_simulator') # print("Depths: ", depths) # raise(ValueError("Stop, but keep interpreter.")) # depths = calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True, backend_name_or_Fake='HQS-LT-S1-APIVAL') # print("Depths: ", depths) # raise(ValueError("Stop, but keep interpreter.")) ##################################### # Depth plots ##################################### honeywell_save_account_and_info() produce_depths_plot(do_rccx=True) # raise ValueError("Exiting, but keeping interpreter.") ##################################### # Unit test all ##################################### # import unittest # unittest.main(module='test.test_quantum_homology_advanced') ##################################### # Unit test specific ##################################### # import test.test_quantum_homology_advanced # mylaplace = test.test_quantum_homology_advanced.Expectation_of_Laplacian_TestCase() # mylaplace.setUp() # mylaplace.test_expectation_01() # (backend="ionq_qpu") # mylaplace.test_expectation_02() # (backend="ionq_qpu") # mylaplace.test_expectation_03() # (backend="ionq_qpu") # mylaplace.test_expectation_04() # (backend="ionq_qpu") # mylaplace.test_expectation_05() # (backend="ionq_qpu") # # mylaplace.test_expectation_05() # mylaplace.test_run_random() # raise(ValueError("Stop, but keep interpreter.")) # honeywell_save_account_and_info() # honeywell_retrieve_counts('HQS-LT-S2', 'c90c48da23c448dc97f6054bd9d45cee') # honeywell_retrieve_counts('HQS-LT-S2', '5b5a56527ed24073aab10011699e493d') pass # job.result() # Result(backend_name='ionq_qpu', backend_version='0.0.1', qobj_id='None', job_id='5286dc3f-fdbd-4a6b-8231-af79375e143d', success=True, results=[ExperimentResult(shots=100, success=True, meas_level=2, data=ExperimentResultData(counts={'0x1': 1, '0x2': 4, '0x4': 2, '0x5': 44, '0x6': 38, '0x7': 1, '0xd': 4, '0xe': 1, '0xf': 2, '0x14': 1, '0x16': 2}, probabilities={'0x1': 0.01, '0x2': 0.04, '0x4': 0.02, '0x5': 0.44, '0x6': 0.38, '0x7': 0.01, '0xd': 0.04, '0xe': 0.01, '0xf': 0.02, '0x14': 0.01, '0x16': 0.02}), header=QobjExperimentHeader(memory_slots=5, global_phase=2.356194490192344, n_qubits=6, name='circuit-16', creg_sizes=[['c0', 2], ['power1complexcproj0', 1], ['power1complexcproj1', 1], ['power1splitcproj0', 1]], clbit_labels=[['c0', 0], ['c0', 1], ['power1complexcproj0', 0], ['power1complexcproj1', 0], ['power1splitcproj0', 0]], qreg_sizes=[['mainqreg', 2], ['clean_ancillae', 1], ['power1complexqproj0', 1], ['power1complexqproj1', 1], ['power1splitqproj0', 1]], qubit_labels=[['mainqreg', 0], ['mainqreg', 1], ['clean_ancillae', 0], ['power1complexqproj0', 0], ['power1complexqproj1', 0], ['power1splitqproj0', 0]]))], time_taken=2.579)
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. # pylint: disable=invalid-name """Tests for Choi 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 Choi from .channel_test_case import ChannelTestCase class TestChoi(ChannelTestCase): """Tests for Choi channel representation.""" def test_init(self): """Test initialization""" mat4 = np.eye(4) / 2.0 chan = Choi(mat4) assert_allclose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) self.assertEqual(chan.num_qubits, 1) mat8 = np.eye(8) / 2.0 chan = Choi(mat8, input_dims=4) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (4, 2)) self.assertIsNone(chan.num_qubits) chan = Choi(mat8, input_dims=2) assert_allclose(chan.data, mat8) self.assertEqual(chan.dim, (2, 4)) self.assertIsNone(chan.num_qubits) mat16 = np.eye(16) / 4 chan = Choi(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, Choi, mat8, input_dims=[4], output_dims=[4]) def test_circuit_init(self): """Test initialization from a circuit.""" circuit, target = self.simple_circuit_no_measure() op = Choi(circuit) target = Choi(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, Choi, circuit) def test_equal(self): """Test __eq__ method""" mat = self.rand_matrix(4, 4) self.assertEqual(Choi(mat), Choi(mat)) def test_copy(self): """Test copy method""" mat = np.eye(2) with self.subTest("Deep copy"): orig = Choi(mat) cpy = orig.copy() cpy._data[0, 0] = 0.0 self.assertFalse(cpy == orig) with self.subTest("Shallow copy"): orig = Choi(mat) clone = copy.copy(orig) clone._data[0, 0] = 0.0 self.assertTrue(clone == orig) def test_clone(self): """Test clone method""" mat = np.eye(4) orig = Choi(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(Choi(self.depol_choi(0.25)).is_cptp()) # Non-CPTP should return false self.assertFalse(Choi(1.25 * self.choiI - 0.25 * self.depol_choi(1)).is_cptp()) def test_conjugate(self): """Test conjugate method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Conjugate channel swaps Y-basis states targ = Choi(np.kron(Zp, Ym) + np.kron(Zm, Yp)) chan_conj = chan.conjugate() self.assertEqual(chan_conj, targ) def test_transpose(self): """Test transpose method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Transpose channel swaps basis targ = Choi(np.kron(Yp, Zp) + np.kron(Ym, Zm)) chan_t = chan.transpose() self.assertEqual(chan_t, targ) def test_adjoint(self): """Test adjoint method.""" # Test channel measures in Z basis and prepares in Y basis # Zp -> Yp, Zm -> Ym Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Yp, Ym = np.array([[1, -1j], [1j, 1]]) / 2, np.array([[1, 1j], [-1j, 1]]) / 2 chan = Choi(np.kron(Zp, Yp) + np.kron(Zm, Ym)) # Ajoint channel swaps Y-basis elements and Z<->Y bases targ = Choi(np.kron(Ym, Zp) + np.kron(Yp, Zm)) chan_adj = chan.adjoint() self.assertEqual(chan_adj, targ) def test_compose_except(self): """Test compose different dimension exception""" self.assertRaises(QiskitError, Choi(np.eye(4)).compose, Choi(np.eye(8))) self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2) def test_compose(self): """Test compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan1.compose(chan2), targ) self.assertEqual(chan1 & chan2, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan2.compose(chan1), targ) self.assertEqual(chan2 & chan1, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2) self.assertEqual(chan.dim, (2, 2)) chan = chan2.compose(chan1) self.assertEqual(chan.dim, (4, 4)) def test_dot(self): """Test dot method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) targ = Choi(self.choiZ) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan1.dot(chan1), targ) self.assertEqual(chan1 @ chan1, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan2.dot(chan1), targ) self.assertEqual(chan2 @ chan1, targ) # X-gate first swaps Z states targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan1.dot(chan2), targ) self.assertEqual(chan1 @ chan2, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.dot(chan2) self.assertEqual(chan.dim, (4, 4)) chan = chan1 @ chan2 self.assertEqual(chan.dim, (4, 4)) chan = chan2.dot(chan1) self.assertEqual(chan.dim, (2, 2)) chan = chan2 @ chan1 self.assertEqual(chan.dim, (2, 2)) def test_compose_front(self): """Test front compose method.""" # UnitaryChannel evolution chan1 = Choi(self.choiX) chan2 = Choi(self.choiY) chan = chan1.compose(chan2, front=True) targ = Choi(self.choiZ) self.assertEqual(chan, targ) # 50% depolarizing channel chan1 = Choi(self.depol_choi(0.5)) chan = chan1.compose(chan1, front=True) targ = Choi(self.depol_choi(0.75)) self.assertEqual(chan, targ) # Measure and rotation Zp, Zm = np.diag([1, 0]), np.diag([0, 1]) Xp, Xm = np.array([[1, 1], [1, 1]]) / 2, np.array([[1, -1], [-1, 1]]) / 2 chan1 = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) chan2 = Choi(self.choiX) # X-gate second does nothing chan = chan2.compose(chan1, front=True) targ = Choi(np.kron(Zp, Xp) + np.kron(Zm, Xm)) self.assertEqual(chan, targ) # X-gate first swaps Z states chan = chan1.compose(chan2, front=True) targ = Choi(np.kron(Zm, Xp) + np.kron(Zp, Xm)) self.assertEqual(chan, targ) # Compose different dimensions chan1 = Choi(np.eye(8) / 4, input_dims=2, output_dims=4) chan2 = Choi(np.eye(8) / 2, input_dims=4, output_dims=2) chan = chan1.compose(chan2, front=True) self.assertEqual(chan.dim, (4, 4)) chan = chan2.compose(chan1, front=True) self.assertEqual(chan.dim, (2, 2)) def test_expand(self): """Test expand method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I chan = chan1.expand(chan2) rho_targ = DensityMatrix(np.kron(rho1, rho0)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X chan = chan2.expand(chan1) rho_targ = DensityMatrix(np.kron(rho0, rho1)) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.expand(chan_dep) rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_tensor(self): """Test tensor method.""" rho0, rho1 = np.diag([1, 0]), np.diag([0, 1]) rho_init = DensityMatrix(np.kron(rho0, rho0)) chan1 = Choi(self.choiI) chan2 = Choi(self.choiX) # X \otimes I rho_targ = DensityMatrix(np.kron(rho1, rho0)) chan = chan2.tensor(chan1) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan2 ^ chan1 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # I \otimes X rho_targ = DensityMatrix(np.kron(rho0, rho1)) chan = chan1.tensor(chan2) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan1 ^ chan2 self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) # Completely depolarizing rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4) chan_dep = Choi(self.depol_choi(1)) chan = chan_dep.tensor(chan_dep) self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) chan = chan_dep ^ chan_dep self.assertEqual(chan.dim, (4, 4)) self.assertEqual(rho_init.evolve(chan), rho_targ) def test_power(self): """Test power method.""" # 10% depolarizing channel p_id = 0.9 depol = Choi(self.depol_choi(1 - p_id)) # Compose 3 times p_id3 = p_id**3 chan3 = depol.power(3) targ3 = Choi(self.depol_choi(1 - p_id3)) self.assertEqual(chan3, targ3) def test_add(self): """Test add method.""" mat1 = 0.5 * self.choiI mat2 = 0.5 * self.depol_choi(1) chan1 = Choi(mat1) chan2 = Choi(mat2) targ = Choi(mat1 + mat2) self.assertEqual(chan1._add(chan2), targ) self.assertEqual(chan1 + chan2, targ) targ = Choi(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 = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) 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 = Choi(mat) op0 = Choi(mat0) op1 = Choi(mat1) op01 = op1.tensor(op0) eye = Choi(self.choiI) 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 = Choi(self.choiI) chan2 = Choi(np.eye(8)) self.assertRaises(QiskitError, chan1._add, chan2) self.assertRaises(QiskitError, chan1._add, 5) def test_multiply(self): """Test multiply method.""" chan = Choi(self.choiI) val = 0.5 targ = Choi(val * self.choiI) self.assertEqual(chan._multiply(val), targ) self.assertEqual(val * chan, targ) targ = Choi(self.choiI * val) self.assertEqual(chan * val, targ) def test_multiply_except(self): """Test multiply method raises exceptions.""" chan = Choi(self.choiI) 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 = Choi(self.choiI) targ = Choi(-1 * self.choiI) self.assertEqual(-chan, targ) if __name__ == "__main__": unittest.main()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
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 the Sabre Swap pass""" import unittest import itertools import ddt import numpy.random from qiskit.circuit import Clbit, ControlFlowOp, Qubit from qiskit.circuit.library import CCXGate, HGate, Measure, SwapGate from qiskit.circuit.classical import expr from qiskit.circuit.random import random_circuit from qiskit.compiler.transpiler import transpile from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2 from qiskit.transpiler.passes import SabreSwap, TrivialLayout, CheckMap from qiskit.transpiler import CouplingMap, Layout, PassManager, Target, TranspilerError from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.test._canonical import canonicalize_control_flow from qiskit.utils import optionals def looping_circuit(uphill_swaps=1, additional_local_minimum_gates=0): """A circuit that causes SabreSwap to loop infinitely. This looks like (using cz gates to show the symmetry, though we actually output cx for testing purposes): .. parsed-literal:: q_0: ─■──────────────── │ q_1: ─┼──■───────────── │ │ q_2: ─┼──┼──■────────── │ │ │ q_3: ─┼──┼──┼──■─────── │ │ │ │ q_4: ─┼──┼──┼──┼─────■─ │ │ │ │ │ q_5: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_6: ─┼──┼──┼──┼──┼──── │ │ │ │ │ q_7: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_8: ─┼──┼──┼──┼─────■─ │ │ │ │ q_9: ─┼──┼──┼──■─────── │ │ │ q_10: ─┼──┼──■────────── │ │ q_11: ─┼──■───────────── │ q_12: ─■──────────────── where `uphill_swaps` is the number of qubits separating the inner-most gate (representing how many swaps need to be made that all increase the heuristics), and `additional_local_minimum_gates` is how many extra gates to add on the outside (these increase the size of the region of stability). """ outers = 4 + additional_local_minimum_gates n_qubits = 2 * outers + 4 + uphill_swaps # This is (most of) the front layer, which is a bunch of outer qubits in the # coupling map. outer_pairs = [(i, n_qubits - i - 1) for i in range(outers)] inner_heuristic_peak = [ # This gate is completely "inside" all the others in the front layer in # terms of the coupling map, so it's the only one that we can in theory # make progress towards without making the others worse. (outers + 1, outers + 2 + uphill_swaps), # These are the only two gates in the extended set, and they both get # further apart if you make a swap to bring the above gate closer # together, which is the trick that creates the "heuristic hill". (outers, outers + 1), (outers + 2 + uphill_swaps, outers + 3 + uphill_swaps), ] qc = QuantumCircuit(n_qubits) for pair in outer_pairs + inner_heuristic_peak: qc.cx(*pair) return qc @ddt.ddt class TestSabreSwap(QiskitTestCase): """Tests the SabreSwap pass.""" def test_trivial_case(self): """Test that an already mapped circuit is unchanged. ┌───┐┌───┐ q_0: ──■──┤ H ├┤ X ├──■── ┌─┴─┐└───┘└─┬─┘ │ q_1: ┤ X ├──■────■────┼── └───┘┌─┴─┐ │ q_2: ──■──┤ X ├───────┼── ┌─┴─┐├───┤ │ q_3: ┤ X ├┤ X ├───────┼── └───┘└─┬─┘ ┌─┴─┐ q_4: ───────■───────┤ X ├ └───┘ """ coupling = CouplingMap.from_ring(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(coupling, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_trivial_with_target(self): """Test that an already mapped circuit is unchanged with target.""" coupling = CouplingMap.from_ring(5) target = Target(num_qubits=5) target.add_instruction(SwapGate(), {edge: None for edge in coupling.get_edges()}) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(target, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_lookahead_mode(self): """Test lookahead mode's lookahead finds single SWAP gate. ┌───┐ q_0: ──■──┤ H ├─────────────── ┌─┴─┐└───┘ q_1: ┤ X ├──■────■─────────■── └───┘┌─┴─┐ │ │ q_2: ──■──┤ X ├──┼────■────┼── ┌─┴─┐└───┘┌─┴─┐┌─┴─┐┌─┴─┐ q_3: ┤ X ├─────┤ X ├┤ X ├┤ X ├ └───┘ └───┘└───┘└───┘ q_4: ───────────────────────── """ coupling = CouplingMap.from_line(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # free qc.cx(1, 3) # F qc.cx(2, 3) # E qc.cx(1, 3) # E pm = PassManager(SabreSwap(coupling, "lookahead")) new_qc = pm.run(qc) self.assertEqual(new_qc.num_nonlocal_gates(), 7) def test_do_not_change_cm(self): """Coupling map should not change. See https://github.com/Qiskit/qiskit-terra/issues/5675""" cm_edges = [(1, 0), (2, 0), (2, 1), (3, 2), (3, 4), (4, 2)] coupling = CouplingMap(cm_edges) passmanager = PassManager(SabreSwap(coupling)) _ = passmanager.run(QuantumCircuit(coupling.size())) self.assertEqual(set(cm_edges), set(coupling.get_edges())) def test_do_not_reorder_measurements(self): """Test that SabreSwap doesn't reorder measurements to the same classical bit. With the particular coupling map used in this test and the 3q ccx gate, the routing would invariably the measurements if the classical successors are not accurately tracked. Regression test of gh-7950.""" coupling = CouplingMap([(0, 2), (2, 0), (1, 2), (2, 1)]) qc = QuantumCircuit(3, 1) qc.compose(CCXGate().definition, [0, 1, 2], []) # Unroll CCX to 2q operations. qc.h(0) qc.barrier() qc.measure(0, 0) # This measure is 50/50 between the Z states. qc.measure(1, 0) # This measure always overwrites with 0. passmanager = PassManager(SabreSwap(coupling)) transpiled = passmanager.run(qc) last_h = transpiled.data[-4] self.assertIsInstance(last_h.operation, HGate) first_measure = transpiled.data[-2] second_measure = transpiled.data[-1] self.assertIsInstance(first_measure.operation, Measure) self.assertIsInstance(second_measure.operation, Measure) # Assert that the first measure is on the same qubit that the HGate was applied to, and the # second measurement is on a different qubit (though we don't care which exactly - that # depends a little on the randomisation of the pass). self.assertEqual(last_h.qubits, first_measure.qubits) self.assertNotEqual(last_h.qubits, second_measure.qubits) # The 'basic' method can't get stuck in the same way. @ddt.data("lookahead", "decay") def test_no_infinite_loop(self, method): """Test that the 'release value' mechanisms allow SabreSwap to make progress even on circuits that get stuck in a stable local minimum of the lookahead parameters.""" qc = looping_circuit(3, 1) qc.measure_all() coupling_map = CouplingMap.from_line(qc.num_qubits) routing_pass = PassManager(SabreSwap(coupling_map, method)) n_swap_gates = 0 def leak_number_of_swaps(cls, *args, **kwargs): nonlocal n_swap_gates n_swap_gates += 1 if n_swap_gates > 1_000: raise Exception("SabreSwap seems to be stuck in a loop") # pylint: disable=bad-super-call return super(SwapGate, cls).__new__(cls, *args, **kwargs) with unittest.mock.patch.object(SwapGate, "__new__", leak_number_of_swaps): routed = routing_pass.run(qc) routed_ops = routed.count_ops() del routed_ops["swap"] self.assertEqual(routed_ops, qc.count_ops()) couplings = { tuple(routed.find_bit(bit).index for bit in instruction.qubits) for instruction in routed.data if len(instruction.qubits) == 2 } # Asserting equality to the empty set gives better errors on failure than asserting that # `couplings <= coupling_map`. self.assertEqual(couplings - set(coupling_map.get_edges()), set()) # Assert that the same keys are produced by a simulation - this is a test that the inserted # swaps route the qubits correctly. if not optionals.HAS_AER: return from qiskit import Aer sim = Aer.get_backend("aer_simulator") in_results = sim.run(qc, shots=4096).result().get_counts() out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): """Test that :class:`.SabreSwap` correctly accounts for classical conditions in its reckoning on whether a node is resolved or not. If it is not handled correctly, the second gate might not appear in the output. Regression test of gh-8040.""" with self.subTest("1 bit in register"): qc = QuantumCircuit(2, 1) qc.z(0) qc.z(0).c_if(qc.cregs[0], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) with self.subTest("multiple registers"): cregs = [ClassicalRegister(3), ClassicalRegister(4)] qc = QuantumCircuit(QuantumRegister(2, name="q"), *cregs) qc.z(0) qc.z(0).c_if(cregs[0], 0) qc.z(0).c_if(cregs[1], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) def test_classical_condition_cargs(self): """Test that classical conditions are preserved even if missing from cargs DAGNode field. Created from reproduction in https://github.com/Qiskit/qiskit-terra/issues/8675 """ with self.subTest("missing measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 2).c_if(0, 0) qc.measure(1, 0) qc.h(2).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(2, 0) expected.h(1).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) with self.subTest("reordered measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 1).c_if(0, 0) qc.measure(1, 0) qc.h(0).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0) expected.h(0).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) def test_conditional_measurement(self): """Test that instructions with cargs and conditions are handled correctly.""" qc = QuantumCircuit(3, 2) qc.cx(0, 2).c_if(0, 0) qc.measure(2, 0).c_if(1, 0) qc.h(2).c_if(0, 0) qc.measure(1, 1) expected = QuantumCircuit(3, 2) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0).c_if(1, 0) expected.h(1).c_if(0, 0) expected.measure(2, 1) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) @ddt.data("basic", "lookahead", "decay") def test_deterministic(self, heuristic): """Test that the output of the SabreSwap pass is deterministic for a given random seed.""" width = 40 # The actual circuit is unimportant, we just need one with lots of scoring degeneracy. qc = QuantumCircuit(width) for i in range(width // 2): qc.cx(i, i + (width // 2)) for i in range(0, width, 2): qc.cx(i, i + 1) dag = circuit_to_dag(qc) coupling = CouplingMap.from_line(width) pass_0 = SabreSwap(coupling, heuristic, seed=0, trials=1) pass_1 = SabreSwap(coupling, heuristic, seed=1, trials=1) dag_0 = pass_0.run(dag) dag_1 = pass_1.run(dag) # This deliberately avoids using a topological order, because that introduces an opportunity # for the re-ordering to sort the swaps back into a canonical order. def normalize_nodes(dag): return [(node.op.name, node.qargs, node.cargs) for node in dag.op_nodes()] # A sanity check for the test - if unequal seeds don't produce different outputs for this # degenerate circuit, then the test probably needs fixing (or Sabre is ignoring the seed). self.assertNotEqual(normalize_nodes(dag_0), normalize_nodes(dag_1)) # Check that a re-run with the same seed produces the same circuit in the exact same order. self.assertEqual(normalize_nodes(dag_0), normalize_nodes(pass_0.run(dag))) def test_rejects_too_many_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(5, "q")) with self.assertRaisesRegex(TranspilerError, "More qubits in the circuit"): pass_(qc) def test_rejects_too_few_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(3, "q")) with self.assertRaisesRegex(TranspilerError, "Fewer qubits in the circuit"): pass_(qc) @ddt.ddt class TestSabreSwapControlFlow(QiskitTestCase): """Tests for control flow in sabre swap.""" def test_shared_block(self): """Test multiple control flow ops sharing the same block instance.""" inner = QuantumCircuit(2) inner.cx(0, 1) qreg = QuantumRegister(4, "q") outer = QuantumCircuit(qreg, ClassicalRegister(1)) for pair in itertools.permutations(range(outer.num_qubits), 2): outer.if_test((outer.cregs[0], 1), inner, pair, []) coupling = CouplingMap.from_line(4) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(outer)) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_blocks_use_registers(self): """Test that control flow ops using registers still use registers after routing.""" num_qubits = 2 qreg = QuantumRegister(num_qubits, "q") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qc = QuantumCircuit(qreg, cr1, cr2) with qc.if_test((cr1, False)): qc.cx(0, 1) qc.measure(0, cr2[0]) with qc.if_test((cr2, 0)): qc.cx(0, 1) coupling = CouplingMap.from_line(num_qubits) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(qc)) outer_if_op = cdag.op_nodes(ControlFlowOp)[0].op self.assertEqual(outer_if_op.condition[0], cr1) inner_if_op = circuit_to_dag(outer_if_op.blocks[0]).op_nodes(ControlFlowOp)[0].op self.assertEqual(inner_if_op.condition[0], cr2) def test_pre_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[2]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[2]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) efalse_body.x(1) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else_route_post_x(self): """test swap with if else controlflow construct; pre-cx and post x""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]]) qc.x(1) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) new_order = [0, 2, 1, 3, 4] etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.x(2) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_post_if_else_route(self): """test swap with if else controlflow construct; post cx""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.barrier(qreg) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.cx(0, 2) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.barrier(qreg) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.barrier(qreg) expected.swap(1, 2) expected.cx(0, 1) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else2(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) false_body = QuantumCircuit(qreg, creg[[0]]) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[0]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[0]], creg[[0]]) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_intra_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_if_else(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) etrue_body = QuantumCircuit(qreg, creg[[0]]) efalse_body = QuantumCircuit(qreg, creg[[0]]) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body.cx(0, 1) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_post_if_else(self): """test swap with if else controlflow construct; cx before, in, and after if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.h(3) qc.cx(3, 0) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]]) expected.h(3) expected.swap(1, 2) expected.cx(3, 2) expected.barrier() expected.measure(qreg, creg[[1, 2, 0, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_if_expr(self): """Test simple if conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_if_else_expr(self): """Test simple if/else conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) true = QuantumCircuit(4) true.cx(0, 1) true.cx(0, 2) true.cx(0, 3) false = QuantumCircuit(4) false.cx(3, 0) false.cx(3, 1) false.cx(3, 2) qc = QuantumCircuit(4, 2) qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_no_layout_change(self): """test controlflow with no layout change needed""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) @ddt.data(1, 2, 3) def test_for_loop(self, nloops): """test stochastic swap with for_loop""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) for_body = QuantumCircuit(qreg) for_body.cx(0, 2) loop_parameter = None qc.for_loop(range(nloops), loop_parameter, for_body, qreg, []) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) efor_body = QuantumCircuit(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) loop_parameter = None expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, []) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop(self): """test while loop""" num_qubits = 4 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(len(qreg)) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) while_body = QuantumCircuit(qreg, creg) while_body.reset(qreg[2:]) while_body.h(qreg[2:]) while_body.cx(0, 3) while_body.measure(qreg[3], creg[3]) qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) ewhile_body = QuantumCircuit(qreg, creg) ewhile_body.reset(qreg[2:]) ewhile_body.h(qreg[2:]) ewhile_body.swap(0, 1) ewhile_body.swap(2, 3) ewhile_body.cx(1, 2) ewhile_body.measure(qreg[2], creg[3]) ewhile_body.swap(1, 0) ewhile_body.swap(3, 2) expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits) expected.barrier() expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop_expr(self): """Test simple while loop with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_switch_implicit_carg_use(self): """Test that a switch statement that uses cargs only implicitly via its ``target`` attribute and not explicitly in bodies of the cases is routed correctly, with the dependencies fulfilled correctly.""" coupling = CouplingMap.from_line(4) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) body = QuantumCircuit([Qubit()]) body.x(0) # If the classical wire condition isn't respected, then the switch would appear in the front # layer and be immediately eligible for routing, which would produce invalid output. qc = QuantumCircuit(4, 1) qc.cx(0, 1) qc.cx(1, 2) qc.cx(0, 2) qc.measure(2, 0) qc.switch(expr.lift(qc.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], []) expected = QuantumCircuit(4, 1) expected.cx(0, 1) expected.cx(1, 2) expected.swap(2, 1) expected.cx(0, 1) expected.measure(1, 0) expected.switch( expr.lift(expected.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], [] ) self.assertEqual(pass_(qc), expected) def test_switch_single_case(self): """Test routing of 'switch' with just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive(self): """Test routing of 'switch' with several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_single_case(self): """Test routing of 'switch' with an `Expr` target and just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_nonexhaustive(self): """Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_nested_inner_cnot(self): """test swap in nested if else controlflow construct; swap in inner""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(0, 2) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_nested_outer_cnot(self): """test swap with nested if else controlflow construct; swap in outer""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(1, 3) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.cx(2, 3) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], []) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 1, 2, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_disjoint_looping(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) loop_body = QuantumCircuit(2) loop_body.cx(0, 1) qc.for_loop((0,), None, loop_body, [0, 2], []) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr) efor_body = QuantumCircuit(qr[[0, 1, 2]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) expected.for_loop((0,), None, efor_body, [0, 1, 2], []) self.assertEqual(cqc, expected) def test_disjoint_multiblock(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr[0:3] + cr[:]) true_body.cx(0, 1) false_body = QuantumCircuit(qr[0:3] + cr[:]) false_body.cx(0, 2) qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0]) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr, cr) etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) efalse_body.swap(1, 2) efalse_body.cx(0, 1) efalse_body.swap(1, 2) expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]]) self.assertEqual(cqc, expected) def test_multiple_ops_per_layer(self): """Test circuits with multiple operations per layer""" num_qubits = 6 coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) # This cx and the for_loop are in the same layer. qc.cx(0, 2) with qc.for_loop((0,)): qc.cx(3, 5) cqc = SabreSwap(coupling, "lookahead", seed=82, trials=1)(qc) check_map_pass(cqc) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qr) expected.swap(1, 2) expected.cx(0, 1) efor_body = QuantumCircuit(qr[[3, 4, 5]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(2, 1) expected.for_loop((0,), None, efor_body, [3, 4, 5], []) self.assertEqual(cqc, expected) def test_if_no_else_restores_layout(self): """Test that an if block with no else branch restores the initial layout.""" qc = QuantumCircuit(8, 1) with qc.if_test((qc.clbits[0], False)): # Just some arbitrary gates with no perfect layout. qc.cx(3, 5) qc.cx(4, 6) qc.cx(1, 4) qc.cx(7, 4) qc.cx(0, 5) qc.cx(7, 3) qc.cx(1, 3) qc.cx(5, 2) qc.cx(6, 7) qc.cx(3, 2) qc.cx(6, 2) qc.cx(2, 0) qc.cx(7, 6) coupling = CouplingMap.from_line(8) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) transpiled = pass_(qc) # Check the pass claims to have done things right. initial_layout = Layout.generate_trivial_layout(*qc.qubits) self.assertEqual(initial_layout, pass_.property_set["final_layout"]) # Check that pass really did do it right. inner_block = transpiled.data[0].operation.blocks[0] running_layout = initial_layout.copy() for instruction in inner_block: if instruction.operation.name == "swap": running_layout.swap(*instruction.qubits) self.assertEqual(initial_layout, running_layout) @ddt.ddt class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase): """Assert the output of a transpilation with stochastic swap is a physical circuit.""" @classmethod def setUpClass(cls): super().setUpClass() cls.backend = FakeMumbai() cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} cls.basis_gates = set(cls.backend.configuration().basis_gates) cls.basis_gates.update(["for_loop", "while_loop", "if_else"]) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNotNone(getattr(transpiled, "_layout", None)) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name in {"barrier", "measure"}: continue self.assertIn(instruction.operation.name, self.basis_gates) qargs = tuple(qubit_mapping[x] for x in instruction.qubits) if not isinstance(instruction.operation, ControlFlowOp): if len(qargs) > 2 or len(qargs) < 0: raise Exception("Invalid number of qargs for instruction") if len(qargs) == 2: self.assertIn(qargs, self.coupling_edge_set) else: self.assertLessEqual(qargs[0], 26) else: for block in instruction.operation.blocks: self.assertEqual(block.num_qubits, len(instruction.qubits)) self.assertEqual(block.num_clbits, len(instruction.clbits)) new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, self.backend, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow_target(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, target=FakeMumbaiV2().target, ) self.assert_valid_circuit(tqc) @ddt.data(*range(4, 27)) def test_random_circuit_for_loop(self, size): """Test that transpiled random circuits with nested for loops are physical circuits.""" circuit = random_circuit(size, 3, measure=False, seed=12342) for_block = random_circuit(3, 2, measure=False, seed=12342) inner_for_block = random_circuit(2, 1, measure=False, seed=12342) with circuit.for_loop((1,)): with circuit.for_loop((1,)): circuit.append(inner_for_block, [0, 3]) circuit.append(for_block, [1, 0, 2]) circuit.measure_all() tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(6, 27)) def test_random_circuit_if_else(self, size): """Test that transpiled random circuits with if else blocks are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) if_block = random_circuit(3, 2, measure=True, seed=12342) else_block = random_circuit(2, 1, measure=True, seed=12342) rng = numpy.random.default_rng(seed=12342) inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits)) if inner_clbit_count > circuit.num_clbits: circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)]) clbit_indices = list(range(circuit.num_clbits)) rng.shuffle(clbit_indices) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits]) with else_: circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits]) tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit top = QuantumCircuit(1) top.x(0); bottom = QuantumCircuit(2) bottom.cry(0.2, 0, 1); tensored = bottom.tensor(top) tensored.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Test qclib.gate.qdmcu.QDMCU """ from unittest import TestCase import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from scipy.stats import unitary_group from qclib.gates.qdmcu import Qdmcu from qclib.util import get_cnot_count class TestQDMCU(TestCase): def _generate_u2(self): return unitary_group.rvs(2) def _build_qiskit_qdmcu(self, u2, num_controls, ctrl_state: str = None): u2_gate = QuantumCircuit(1) u2_gate.unitary(u2, 0) controls_list = list(range(num_controls)) target = num_controls qiskit_circ = QuantumCircuit(target + 1) qiskit_circ.append(u2_gate.control(num_controls, ctrl_state=ctrl_state), [*controls_list, target]) return qiskit_circ def test_gate_trivial_ctrl_state(self): """Compares QDMCU result gate against qiskit's with a trivial state""" u2 = self._generate_u2() for n_ctrl in range(1, 8): qiskit_circ = self._build_qiskit_qdmcu(u2, n_ctrl) qdmcu_circ = Qdmcu(u2, n_ctrl).definition qiskit_op = Operator(qiskit_circ).data qdmcu_op = Operator(qdmcu_circ).data self.assertTrue(np.allclose(qiskit_op, qdmcu_op)) def test_gate_random_ctrl_state(self): """Compares QDMCU result gate against qiskit's with a trivial state""" u2 = self._generate_u2() for n_ctrl in range(1, 8): ctrl_state = f'{np.random.randint(1, 2**n_ctrl):0{n_ctrl}b}' qiskit_circ = self._build_qiskit_qdmcu(u2, n_ctrl, ctrl_state=ctrl_state) qdmcu_circ = Qdmcu(u2, n_ctrl, ctrl_state=ctrl_state).definition qiskit_op = Operator(qiskit_circ).data qdmcu_op = Operator(qdmcu_circ).data self.assertTrue(np.allclose(qiskit_op, qdmcu_op)) def test_cnot_count(self): """Compares QDMCU cnot count against qiskit's cnot count""" u2 = self._generate_u2() for n_ctrl in range(1, 8): ctrl_state = f'{np.random.randint(1, 2**n_ctrl):0{n_ctrl}b}' qiskit_circ = self._build_qiskit_qdmcu(u2, n_ctrl, ctrl_state=ctrl_state) qdmcu_circ = Qdmcu(u2, n_ctrl, ctrl_state=ctrl_state).definition qiskit_cnots = get_cnot_count(qiskit_circ) qdmcu_cnots = get_cnot_count(qdmcu_circ) self.assertLessEqual(qdmcu_cnots, qiskit_cnots)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.problems import QuadraticProgram # define a problem qp = QuadraticProgram() qp.binary_var("x") qp.integer_var(name="y", lowerbound=-1, upperbound=4) qp.maximize(quadratic={("x", "y"): 1}) qp.linear_constraint({"x": 1, "y": -1}, "<=", 0) print(qp.prettyprint()) from qiskit_optimization.algorithms import CplexOptimizer, GurobiOptimizer cplex_result = CplexOptimizer().solve(qp) gurobi_result = GurobiOptimizer().solve(qp) print("cplex") print(cplex_result.prettyprint()) print() print("gurobi") print(gurobi_result.prettyprint()) result = CplexOptimizer(disp=True, cplex_parameters={"threads": 1, "timelimit": 0.1}).solve(qp) print(result.prettyprint()) from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit_aer import Aer from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler meo = MinimumEigenOptimizer(QAOA(sampler=Sampler(), optimizer=COBYLA(maxiter=100))) result = meo.solve(qp) print(result.prettyprint()) print("\ndisplay the best 5 solution samples") for sample in result.samples[:5]: print(sample) # docplex model from docplex.mp.model import Model docplex_model = Model("docplex") x = docplex_model.binary_var("x") y = docplex_model.integer_var(-1, 4, "y") docplex_model.maximize(x * y) docplex_model.add_constraint(x <= y) docplex_model.prettyprint() # gurobi model import gurobipy as gp gurobipy_model = gp.Model("gurobi") x = gurobipy_model.addVar(vtype=gp.GRB.BINARY, name="x") y = gurobipy_model.addVar(vtype=gp.GRB.INTEGER, lb=-1, ub=4, name="y") gurobipy_model.setObjective(x * y, gp.GRB.MAXIMIZE) gurobipy_model.addConstr(x - y <= 0) gurobipy_model.update() gurobipy_model.display() from qiskit_optimization.translators import from_docplex_mp, from_gurobipy qp = from_docplex_mp(docplex_model) print("QuadraticProgram obtained from docpblex") print(qp.prettyprint()) print("-------------") print("QuadraticProgram obtained from gurobipy") qp2 = from_gurobipy(gurobipy_model) print(qp2.prettyprint()) from qiskit_optimization.translators import to_gurobipy, to_docplex_mp gmod = to_gurobipy(from_docplex_mp(docplex_model)) print("convert docplex to gurobipy via QuadraticProgram") gmod.display() dmod = to_docplex_mp(from_gurobipy(gurobipy_model)) print("\nconvert gurobipy to docplex via QuadraticProgram") print(dmod.export_as_lp_string()) ind_mod = Model("docplex") x = ind_mod.binary_var("x") y = ind_mod.integer_var(-1, 2, "y") z = ind_mod.integer_var(-1, 2, "z") ind_mod.maximize(3 * x + y - z) ind_mod.add_indicator(x, y >= z, 1) print(ind_mod.export_as_lp_string()) qp = from_docplex_mp(ind_mod) result = meo.solve(qp) # apply QAOA to QuadraticProgram print("QAOA") print(result.prettyprint()) print("-----\nCPLEX") print(ind_mod.solve()) # apply CPLEX directly to the Docplex model import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/qonwaygameoflife/qonwaygameoflife
qonwaygameoflife
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import Aer, execute from qiskit.tools.qi.qi import partial_trace def liveliness(nhood): v=nhood a = v[0][0][0]+v[0][1][0]+v[0][2][0]+v[1][0][0]+v[1][2][0]+v[2][0][0]+v[2][1][0]+v[2][2][0] return a def SQGOL(nhood): a = liveliness(nhood) value = nhood[1][1] alive = np.array([1.0,0.0]) dead = np.array([0.0,1.0]) B = np.array([[0,0],[1,1]]) D = np.array([[1,1],[0,0]]) S = np.array([[1,0],[0,1]]) if a <= 1: value = dead elif (a > 1 and a <= 2): value = ((np.sqrt(2)+1)*2-(np.sqrt(2)+1)*a)*dead+(a-1)*value#(((np.sqrt(2)+1)*(2-a))**2+(a-1)**2) elif (a > 2 and a <= 3): value = (((np.sqrt(2)+1)*3)-(np.sqrt(2)+1)*a)*value+(a-2)*alive#(((np.sqrt(2)+1)*(3-a))**2+(a-2)**2) elif (a > 3 and a < 4): value = ((np.sqrt(2)+1)*4-(np.sqrt(2)+1)*a)*alive+(a-3)*dead#(((np.sqrt(2)+1)*(4-a))**2+(a-3)**2) elif a >= 4: value = dead value = value/np.linalg.norm(value) return value def init_quantum(nhood): v=nhood a = (v[0][0]+v[0][1]+v[0][2]+v[1][0]+v[1][2]+v[2][0]+v[2][1]+v[2][2])/8 a = a/np.linalg.norm(a) qr = QuantumRegister(3,'qr') qc = QuantumCircuit(qr,name='conway') counter = 0 initial_state = (1/np.sqrt(6))*np.array([2,1,0,1]) qc.initialize(initial_state,[qr[1],qr[2]]) qc.initialize(a,[qr[0]]) qc.cx(qr[0],qr[1]) qc.initialize(a,[qr[0]]) qc.cx(qr[0],qr[1]) qc.cx(qr[0],qr[2]) qc.cx(qr[1],qr[0]) qc.cx(qr[2],qr[0]) job = execute(qc,Aer.get_backend('statevector_simulator')) results = job.result().get_statevector() del qr del qc del job value = partial_trace(results,[1,2])[0] value = np.real(value) return value def DSQGOL(nhood): a = liveliness(nhood) value = nhood[1][1][0] value = nhood[1][1] alive = [1,0] dead = [0,1] if value[0] > 0.98: if (a <= 1.5 ): value = dead elif (a > 1.5 and a <= 2.5): value = init_quantum(nhood) # qci, qri = init_quantum(nhood) # for i in range(9): # if i !=5: # qci.cx(qri[5],qri[i]) # job = execute(qci,Aer.get_backend('statevector_simulator')) # results = job.result().get_statevector() # value = partial_trace(results,[0,1,2,3,4,6,7,8]) elif (a > 2.5 and a <= 3.5): value = alive elif (a > 3.5): value = dead elif a < 0.02: if (a < 1 ): value = dead elif (a > 1 and a <= 1.5): value = dead elif (a > 1.5 and a <= 2.5): value = init_quantum(nhood) # qc, qr = init_quantum(nhood) # for i in range(9): # if i !=5: # qci.cx(qri[5],qri[i]) # job = execute(qc,Aer.get_backend('statevector_simulator')) # results = job.result().get_statevector() # value = partial_trace(results,[0,1,2,3,4,6,7,8]) elif (a > 2.5 and a <= 3.5): value = alive elif (a > 3.5): value = dead else: if (a < 1 ): value = dead elif (a > 1 and a <= 1.5): value = dead elif (a > 1.5 and a <= 2.5): value = init_quantum(nhood) # qci, qri = init_quantum(nhood) # for i in range(9): # if i !=5: # qci.cx(qri[5],qri[i]) # job = execute(qc,Aer.get_backend('statevector_simulator')) # results = job.result().get_statevector() # value = partial_trace(results,[0,1,2,3,4,6,7,8]) elif (a > 2.5 and a <= 3.5): value = init_quantum(nhood) # qri = QuantumRegister(1,'qr') # qci = QuantumCircuit(qc,name='conway') # qci.initialize(value,qri[i]) # qci.measure(qr(5)) # job = execute(qci,Aer.get_backend('statevector_simulator')) # value = job.result().get_statevector() elif (a > 3.5): value=dead return value
https://github.com/QuSTaR/kaleidoscope
QuSTaR
# -*- coding: utf-8 -*- # This code is part of Kaleidoscope. # # (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. """Interactive Bloch discs""" import math import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import matplotlib.pyplot as plt import matplotlib.colors from kaleidoscope.utils import pi_check from kaleidoscope.interactive.plotly_wrapper import PlotlyFigure, PlotlyWidget from kaleidoscope.interactive.bloch.utils import bloch_components from kaleidoscope.colors.utils import hex_to_rgb from kaleidoscope.colors import BJY from kaleidoscope.colors.cmap import cmap_to_plotly NORM = plt.Normalize(-1, 1) def bloch_sunburst(vec, colormap): """Create a Bloch disc using a Plotly sunburst. Parameters: vec (ndarray): A vector of Bloch components. colormap (Colormap): A matplotlib colormap. Returns: go.Figure: A Plotly figure instance, Raises: ValueError: Input vector is not normalized. """ eps = 1e-6 vec = np.asarray(vec) vec_norm = np.linalg.norm(vec) if vec_norm > 1.0 + eps: raise ValueError('Input vector has length {} greater than 1.0'.format(vec_norm)) for idx, val in enumerate(vec): if abs(val) < 1e-15: vec[idx] = 0 th = math.atan2(vec[1], vec[0]) if th < 0: th = 2*np.pi+th z_hex = matplotlib.colors.rgb2hex(colormap(NORM(vec[2]))) z_color = "rgba({},{},{},{})".format(*hex_to_rgb(z_hex), 0.95*vec_norm+0.05) ring_color = "rgba({},{},{},{})".format(*hex_to_rgb('#000000'), 0.95*vec_norm+0.05) wedge_str = "\u2329X\u232A= {x}<br>" wedge_str += "\u2329Y\u232A= {y}<br>" wedge_str += "\u2329Z\u232A= {z}<br>" wedge_str += " \u03B8 = {th}<br>" wedge_str += "|\u03C8| = {pur}" th_str = pi_check(th, ndigits=3) th_str = th_str.replace('pi', '\u03C0') hover_text = [wedge_str.format(x=round(vec[0], 3), y=round(vec[1], 3), z=round(vec[2], 3), th=th_str, pur=np.round(vec_norm, 3))] + [None] bloch = go.Sunburst(labels=[" ", " "], parents=["", " "], values=[2*np.pi-th, th], hoverinfo="text", hovertext=hover_text, marker=dict(colors=[z_color, ring_color])) return bloch def bloch_disc(rho, figsize=None, title=None, colormap=None, as_widget=False): """Plot a Bloch disc for a single qubit. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix, or Bloch components. figsize (tuple): Figure size in pixels, default=(200,275). title (str): Plot title. colormap (Colormap): A matplotlib colormap. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_disc qc = QuantumCircuit(1) qc.ry(np.pi*np.random.random(), 0) qc.rz(np.pi*np.random.random(), 0) state = Statevector.from_instruction(qc) bloch_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data if len(rho) != 3: rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) else: comp = [rho] if title: title = [title] + ["\u2329Z\u232A"] else: title = [""] + ["\u2329Z\u232A"] if colormap is None: colormap = BJY if figsize is None: figsize = (200, 275) fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}]+[{'type': 'xy'}]], subplot_titles=title, column_widths=[0.93]+[0.07]) fig.add_trace(bloch_sunburst(comp[0], colormap), row=1, col=1) zval = comp[0][2] zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] idx = (np.abs(np.linspace(-1, 1, 100) - zval)).argmin() tickvals = np.array([0, 49, 99, idx]) idx_sort = np.argsort(tickvals) tickvals = tickvals[idx_sort] ticktext = [-1, 0, 1, "\u25C0"+str(np.round(zval, 3))] if zval <= -0.95: ticktext[0] = '' elif abs(zval) <= 0.05: ticktext[1] = '' elif zval >= 0.95: ticktext[2] = '' ticktext = [ticktext[kk] for kk in idx_sort] PLOTLY_CMAP = cmap_to_plotly(colormap) fig.append_trace(go.Heatmap(z=zrange, colorscale=PLOTLY_CMAP, showscale=False, hoverinfo='none', ), row=1, col=2 ) fig.update_yaxes(row=1, col=2, tickvals=tickvals, ticktext=ticktext) fig.update_yaxes(row=1, col=2, side="right") fig.update_xaxes(row=1, col=2, visible=False) fig.update_layout(margin=dict(t=30, l=10, r=0, b=0), height=figsize[0], width=figsize[1], hoverlabel=dict(font_size=16, font_family="courier,monospace", align='left' ) ) for ann in fig['layout']['annotations']: ann['font'] = dict(size=14) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig) def bloch_multi_disc(rho, figsize=None, titles=True, colormap=None, as_widget=False): """Plot Bloch discs for a multi-qubit state. Parameters: rho (list or ndarray or Statevector or DensityMatrix): Input statevector, density matrix. figsize (tuple): Figure size in pixels, default=(125*num_qubits, 150). titles (bool): Display titles. colormap (Colormap): A matplotlib colormap. as_widget (bool): Return plot as a widget. Returns: PlotlyFigure: A Plotly figure instance PlotlyWidget : A Plotly widget if `as_widget=True`. Example: .. jupyter-execute:: import numpy as np from qiskit import * from qiskit.quantum_info import Statevector from kaleidoscope.interactive import bloch_multi_disc N = 4 qc = QuantumCircuit(N) qc.h(range(N)) for kk in range(N): qc.ry(2*np.pi*np.random.random(), kk) for kk in range(N-1): qc.cx(kk,kk+1) for kk in range(N): qc.rz(2*np.pi*np.random.random(), kk) state = Statevector.from_instruction(qc) bloch_multi_disc(state) """ # A hack so I do not have to import the actual instances from Qiskit. if rho.__class__.__name__ in ['Statevector', 'DensityMatrix'] \ and 'qiskit' in rho.__class__.__module__: rho = rho.data rho = np.asarray(rho, dtype=complex) comp = bloch_components(rho) num = int(np.log2(rho.shape[0])) nrows = 1 ncols = num if figsize is None: figsize = (ncols*125, 150) if titles: titles = ["Qubit {}".format(k) for k in range(num)] + ["\u2329Z\u232A"] else: titles = ["" for k in range(num)] + ["\u2329Z\u232A"] if colormap is None: colormap = BJY fig = make_subplots(rows=nrows, cols=ncols+1, specs=[[{'type': 'domain'}]*ncols+[{'type': 'xy'}]], subplot_titles=titles, column_widths=[0.95/num]*num+[0.05]) for jj in range(num): fig.add_trace(bloch_sunburst(comp[jj], colormap), row=1, col=jj+1) zrange = [k*np.ones(1) for k in np.linspace(-1, 1, 100)] PLOTLY_CMAP = cmap_to_plotly(colormap) fig.append_trace(go.Heatmap(z=zrange, colorscale=PLOTLY_CMAP, showscale=False, hoverinfo='none', ), row=1, col=num+1) fig.update_yaxes(row=1, col=num+1, tickvals=[0, 49, 99], ticktext=[-1, 0, 1]) fig.update_yaxes(row=1, col=num+1, side="right") fig.update_xaxes(row=1, col=num+1, visible=False) fig.update_layout(margin=dict(t=50, l=0, r=15, b=30), width=figsize[0], height=figsize[1], hoverlabel=dict(font_size=14, font_family="monospace", align='left' ) ) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=16) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt #Import Qiskit classes classes import qiskit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error #Import the qv function. import qiskit.ignis.verification.quantum_volume as qv # qubit_lists: list of list of qubit subsets to generate QV circuits qubit_lists = [[0,1,3],[0,1,3,5],[0,1,3,5,7],[0,1,3,5,7,10]] # ntrials: Number of random circuits to create for each subset ntrials = 50 qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, ntrials) #pass the first trial of the nomeas through the transpiler to illustrate the circuit qv_circs_nomeas[0] = qiskit.compiler.transpile(qv_circs_nomeas[0], basis_gates=['u1','u2','u3','cx']) print(qv_circs_nomeas[0][0]) #The Unitary is an identity (with a global phase) backend = qiskit.Aer.get_backend('statevector_simulator') ideal_results = [] for trial in range(ntrials): print('Simulating trial %d'%trial) ideal_results.append(qiskit.execute(qv_circs_nomeas[trial], backend=backend).result()) qv_fitter = qv.QVFitter(qubit_lists=qubit_lists) qv_fitter.add_statevectors(ideal_results) for qubit_list in qubit_lists: l = len(qubit_list) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_outputs['qv_depth_'+str(l)+'_trial_0']) for qubit_list in qubit_lists: l = len(qubit_list) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_output_prob_ideal['qv_depth_'+str(l)+'_trial_0']) noise_model = NoiseModel() p1Q = 0.002 p2Q = 0.02 noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2') noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3') noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx') #noise_model = None backend = qiskit.Aer.get_backend('qasm_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now shots = 1024 exp_results = [] for trial in range(ntrials): print('Running trial %d'%trial) exp_results.append(qiskit.execute(qv_circs[trial], basis_gates=basis_gates, backend=backend, noise_model=noise_model, backend_options={'max_parallel_experiments': 0}).result()) qv_fitter.add_data(exp_results) for qubit_list in qubit_lists: l = len(qubit_list) #print (qv_fitter._heavy_output_counts) print ('qv_depth_'+str(l)+'_trial_0:', qv_fitter._heavy_output_counts['qv_depth_'+str(l)+'_trial_0']) plt.figure(figsize=(10, 6)) ax = plt.gca() # Plot the essence by calling plot_rb_data qv_fitter.plot_qv_data(ax=ax, show_plt=False) # Add title and label ax.set_title('Quantum Volume for up to %d Qubits \n and %d Trials'%(len(qubit_lists[-1]), ntrials), fontsize=18) plt.show() qv_success_list = qv_fitter.qv_success() qv_list = qv_fitter.ydata QV = 1 for qidx, qubit_list in enumerate(qubit_lists): if qv_list[0][qidx]>2/3: if qv_success_list[qidx][0]: print("Width/depth %d greater than 2/3 (%f) with confidence %f (successful). Quantum volume %d"% (len(qubit_list),qv_list[0][qidx],qv_success_list[qidx][1],qv_fitter.quantum_volume()[qidx])) QV = qv_fitter.quantum_volume()[qidx] else: print("Width/depth %d greater than 2/3 (%f) with confidence %f (unsuccessful)."% (len(qubit_list),qv_list[0][qidx],qv_success_list[qidx][1])) else: print("Width/depth %d less than 2/3 (unsuccessful)."%len(qubit_list)) print ("The Quantum Volume is:", QV)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() import qiskit as q import math # for Pi and other math functions from qiskit.visualization import plot_histogram, plot_bloch_multivector qasm_sim= q.Aer.get_backend("qasm_simulator") #Choose to run the code on a simulator or a real quantum computer statevec_sim = q.Aer.get_backend("statevector_simulator") print("done setup") # This circuit to practice Qiskit (gives hints to HW5) c = q.QuantumCircuit(4,3) # create a circuit with 4 qubits and 3 cbits. The cbits are needed to store the measerued qubits values. c.rx(math.pi/2, 0) # Rotate qbit-0 90 degrees on X c.ry(math.pi/4, 1) # Rorate qbit-1 45 degrees on Y c.h(2) # apply H gate on qbit-2 c.cnot(0,3) # apply CNot gate on qubits (0 and 1) c.cnot(1,3) # apply CNot gate on qubits (1 and 3) c.cnot(2,3) # apply CNot gate on qubits (2 and 3) c.rz(math.pi/4, 2) # Rotate qbit-2 45 degrees on Z c.h(2) # Apply H gate again on qbit-2 c.measure([0,1,2], [0,1,2]) # measure qubits [0,1,2] and store the results in cbit [0,1,2] psi0 = q.execute(c,backend=statevec_sim).result().get_statevector() print("Done.. Draw circuit:") c.draw() plot_bloch_multivector(psi0) count1 = q.execute(c,backend=qasm_sim, shots=1024).result().get_counts() plot_histogram([count1], legend=['counts'] )
https://github.com/0xCAB0/shor_algorithm
0xCAB0
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(12) for idx in range(5): qc.h(idx) qc.cx(idx, idx+5) qc.cx(1, 7) qc.x(8) qc.cx(1, 9) qc.x(7) qc.cx(1, 11) qc.swap(6, 11) qc.swap(6, 9) qc.swap(6, 10) qc.x(6) qc.draw('mpl')
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import sys sys.path.insert(0, "D:/myProjects/AfekaCodeProjects/codeProjects/FinalProject_qiskit/qiskit_algorithm/qft_results.ipynb") from shor_algorithm.shor_algo_adder_method import qft_dagger, qft, set_start_state import numpy as np import matplotlib.pyplot as plt from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, Aer, transpile from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector import pandas as pd from qiskit.transpiler.passes import RemoveBarriers from qiskit.providers.fake_provider import FakeAuckland n = 4 number = 5 qc = QuantumCircuit(n, n) set_start_state(qc, number, 0) qc = qc.compose(qft(n, True), range(n)) qc = qc.compose(qft_dagger(n, True), range(n)) qc.measure(range(n), range(n)) qc.draw('mpl') sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) aer_sim = Aer.get_backend('aer_simulator') qc_tran_aer = transpile(qc, aer_sim, optimization_level=0) counts_aer = aer_sim.run(qc_tran_aer).result().get_counts() plot_histogram(counts_aer) fake_backend = FakeAuckland() circ_no_bar = RemoveBarriers()(qc) tran0 = transpile(circ_no_bar, backend=fake_backend, optimization_level=0) # tran3 = transpile(circ_no_bar, backend=fake_backend, optimization_level=3) counts_aer = fake_backend.run(qc_tran_aer).result().get_counts() plot_histogram(counts_aer) depth_basic = circ_no_bar.depth() depth0 = tran0.depth() depth3 = qc_tran_aer.depth() plot_histogram({"basic":depth_basic, "level=0":depth0, "aer":depth3})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse with pulse.build(name='my_example') as my_program: # Add instructions here pass my_program from qiskit.pulse import DriveChannel channel = DriveChannel(0) from qiskit.providers.fake_provider import FakeValencia backend = FakeValencia() with pulse.build(backend=backend, name='backend_aware') as backend_aware_program: channel = pulse.drive_channel(0) print(pulse.num_qubits()) # Raises an error as backend only has 5 qubits #pulse.drive_channel(100) with pulse.build(backend) as delay_5dt: pulse.delay(5, channel) from qiskit.pulse import library amp = 1 sigma = 10 num_samples = 128 gaus = pulse.library.Gaussian(num_samples, amp, sigma, name="Parametric Gaus") gaus.draw() import numpy as np times = np.arange(num_samples) gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2)) gaus = library.Waveform(gaussian_samples, name="WF Gaus") gaus.draw() gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus") gaus.draw() with pulse.build() as schedule: pulse.play(gaus, channel) schedule.draw() with pulse.build() as schedule: pulse.play([0.001*i for i in range(160)], channel) schedule.draw() with pulse.build(backend) as schedule: pulse.set_frequency(4.5e9, channel) with pulse.build(backend) as schedule: pulse.shift_phase(np.pi, channel) from qiskit.pulse import Acquire, AcquireChannel, MemorySlot with pulse.build(backend) as schedule: pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0)) with pulse.build(backend, name='Left align example') as program: with pulse.align_left(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='Right align example') as program: with pulse.align_right(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='example') as program: gaussian_pulse = library.gaussian(100, 0.5, 20) with pulse.align_equispaced(2*gaussian_pulse.duration): pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='example') as program: with pulse.align_sequential(): gaussian_pulse = library.gaussian(100, 0.5, 20) pulse.play(gaussian_pulse, pulse.drive_channel(0)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) pulse.play(gaussian_pulse, pulse.drive_channel(1)) program.draw() with pulse.build(backend, name='Offset example') as program: with pulse.phase_offset(3.14, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) with pulse.frequency_offset(10e6, pulse.drive_channel(0)): pulse.play(gaussian_pulse, pulse.drive_channel(0)) program.draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/codigoscupom/QuantumAlgs
codigoscupom
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import logging import math import numpy as np from sklearn.utils import shuffle from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class, AquaError from qiskit.aqua.components.feature_maps import FeatureMap from qiskit.aqua.utils import get_feature_dimension from qiskit.aqua.utils import map_label_to_class_name from qiskit.aqua.utils import split_dataset_to_data_and_labels from qiskit.aqua.utils import find_regs_by_name from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm logger = logging.getLogger(__name__) def assign_label(measured_key, num_classes): """ Classes = 2: - If odd number of qubits we use majority vote - If even number of qubits we use parity Classes = 3 - We use part-parity {ex. for 2 qubits: [00], [01,10], [11] would be the three labels} Args: measured_key (str): measured key num_classes (int): number of classes """ measured_key = np.asarray([int(k) for k in list(measured_key)]) num_qubits = len(measured_key) if num_classes == 2: if num_qubits % 2 != 0: total = np.sum(measured_key) return 1 if total > num_qubits / 2 else 0 else: hamming_weight = np.sum(measured_key) is_odd_parity = hamming_weight % 2 return is_odd_parity elif num_classes == 3: first_half = int(np.floor(num_qubits / 2)) modulo = num_qubits % 2 # First half of key hamming_weight_1 = np.sum(measured_key[0:first_half + modulo]) # Second half of key hamming_weight_2 = np.sum(measured_key[first_half + modulo:]) is_odd_parity_1 = hamming_weight_1 % 2 is_odd_parity_2 = hamming_weight_2 % 2 return is_odd_parity_1 + is_odd_parity_2 else: total_size = 2**num_qubits class_step = np.floor(total_size / num_classes) decimal_value = measured_key.dot(1 << np.arange(measured_key.shape[-1] - 1, -1, -1)) key_order = int(decimal_value / class_step) return key_order if key_order < num_classes else num_classes - 1 def cost_estimate(probs, gt_labels, shots=None): """Calculate cross entropy # shots is kept since it may be needed in future. Args: shots (int): the number of shots used in quantum computing probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class gt_labels (numpy.ndarray): Nx1 array Returns: float: cross entropy loss between estimated probs and gt_labels """ mylabels = np.zeros(probs.shape) for i in range(gt_labels.shape[0]): whichindex = gt_labels[i] mylabels[i][whichindex] = 1 def cross_entropy(predictions, targets, epsilon=1e-12): predictions = np.clip(predictions, epsilon, 1. - epsilon) N = predictions.shape[0] tmp = np.sum(targets*np.log(predictions), axis=1) ce = -np.sum(tmp)/N return ce x = cross_entropy(probs, mylabels) return x def cost_estimate_sigmoid(shots, probs, gt_labels): """Calculate sigmoid cross entropy Args: shots (int): the number of shots used in quantum computing probs (numpy.ndarray): NxK array, N is the number of data and K is the number of class gt_labels (numpy.ndarray): Nx1 array Returns: float: sigmoid cross entropy loss between estimated probs and gt_labels """ #Error in the order of parameters corrected below - 19 Dec 2018 #x = cost_estimate(shots, probs, gt_labels) x = cost_estimate(probs, gt_labels, shots) loss = (1.) / (1. + np.exp(-x)) return loss def return_probabilities(counts, num_classes): """Return the probabilities of given measured counts Args: counts ([dict]): N data and each with a dict recording the counts num_classes (int): number of classes Returns: numpy.ndarray: NxK array """ probs = np.zeros(((len(counts), num_classes))) for idx in range(len(counts)): count = counts[idx] shots = sum(count.values()) for k, v in count.items(): label = assign_label(k, num_classes) probs[idx][label] += v / shots return probs class VQC(VQAlgorithm): CONFIGURATION = { 'name': 'VQC', 'description': 'Variational Quantum Classifier', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqc_schema', 'type': 'object', 'properties': { 'override_SPSA_params': { 'type': 'boolean', 'default': True }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 }, 'minibatch_size': { 'type': 'integer', 'default': -1 } }, 'additionalProperties': False }, 'problems': ['classification'], 'depends': [ { 'pluggable_type': 'optimizer', 'default': { 'name': 'SPSA' }, }, { 'pluggable_type': 'feature_map', 'default': { 'name': 'SecondOrderExpansion', 'depth': 2 }, }, { 'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ', 'depth': 3 }, }, ], } def __init__( self, optimizer=None, feature_map=None, var_form=None, training_dataset=None, test_dataset=None, datapoints=None, max_evals_grouped=1, minibatch_size=-1, callback=None ): """Initialize the object Args: optimizer (Optimizer): The classical optimizer to use. feature_map (FeatureMap): The FeatureMap instance to use. var_form (VariationalForm): The variational form instance. training_dataset (dict): The training dataset, in the format: {'A': np.ndarray, 'B': np.ndarray, ...}. test_dataset (dict): The test dataset, in same format as `training_dataset`. datapoints (np.ndarray): NxD array, N is the number of data and D is data dimension. max_evals_grouped (int): The maximum number of evaluations to perform simultaneously. minibatch_size (int): The size of a mini-batch. callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of data batch, the index of evaluation, parameters of variational form, evaluated value. Notes: We use `label` to denotes numeric results and `class` the class names (str). """ self.validate(locals()) super().__init__( var_form=var_form, optimizer=optimizer, cost_fn=self._cost_function_wrapper ) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if feature_map is None: raise AquaError('Missing feature map.') if training_dataset is None: raise AquaError('Missing training dataset.') self._training_dataset, self._class_to_label = split_dataset_to_data_and_labels( training_dataset) self._label_to_class = {label: class_name for class_name, label in self._class_to_label.items()} self._num_classes = len(list(self._class_to_label.keys())) if test_dataset is not None: self._test_dataset = split_dataset_to_data_and_labels(test_dataset, self._class_to_label) else: self._test_dataset = test_dataset if datapoints is not None and not isinstance(datapoints, np.ndarray): datapoints = np.asarray(datapoints) self._datapoints = datapoints self._minibatch_size = minibatch_size self._eval_count = 0 self._ret = {} self._feature_map = feature_map self._num_qubits = feature_map.num_qubits @classmethod def init_params(cls, params, algo_input): algo_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) override_spsa_params = algo_params.get('override_SPSA_params') max_evals_grouped = algo_params.get('max_evals_grouped') minibatch_size = algo_params.get('minibatch_size') # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) # If SPSA then override SPSA params as reqd to our predetermined values if opt_params['name'] == 'SPSA' and override_spsa_params: opt_params['c0'] = 4.0 opt_params['c1'] = 0.1 opt_params['c2'] = 0.602 opt_params['c3'] = 0.101 opt_params['c4'] = 0.0 opt_params['skip_calibration'] = True optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) # Set up feature map fea_map_params = params.get(Pluggable.SECTION_KEY_FEATURE_MAP) feature_dimension = get_feature_dimension(algo_input.training_dataset) fea_map_params['feature_dimension'] = feature_dimension feature_map = get_pluggable_class(PluggableType.FEATURE_MAP, fea_map_params['name']).init_params(params) # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = feature_map.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) return cls(optimizer, feature_map, var_form, algo_input.training_dataset, algo_input.test_dataset, algo_input.datapoints, max_evals_grouped, minibatch_size) def construct_circuit(self, x, theta, measurement=False): """ Construct circuit based on data and parameters in variational form. Args: x (numpy.ndarray): 1-D array with D dimension theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form measurement (bool): flag to add measurement Returns: QuantumCircuit: the circuit """ qr = QuantumRegister(self._num_qubits, name='q') cr = ClassicalRegister(self._num_qubits, name='c') qc = QuantumCircuit(qr, cr) qc += self._feature_map.construct_circuit(x, qr) qc += self._var_form.construct_circuit(theta, qr) if measurement: qc.barrier(qr) qc.measure(qr, cr) return qc def _get_prediction(self, data, theta): """ Make prediction on data based on each theta. Args: data (numpy.ndarray): 2-D array, NxD, N data points, each with D dimension theta ([numpy.ndarray]): list of 1-D array, parameters sets for variational form Returns: numpy.ndarray or [numpy.ndarray]: list of NxK array numpy.ndarray or [numpy.ndarray]: list of Nx1 array """ # if self._quantum_instance.is_statevector: # raise ValueError('Selected backend "{}" is not supported.'.format( # self._quantum_instance.backend_name)) circuits = {} circuit_id = 0 num_theta_sets = len(theta) // self._var_form.num_parameters theta_sets = np.split(theta, num_theta_sets) for theta in theta_sets: for datum in data: if self._quantum_instance.is_statevector: circuit = self.construct_circuit(datum, theta, measurement=False) else: circuit = self.construct_circuit(datum, theta, measurement=True) circuits[circuit_id] = circuit circuit_id += 1 results = self._quantum_instance.execute(list(circuits.values())) circuit_id = 0 predicted_probs = [] predicted_labels = [] for _ in theta_sets: counts = [] for _ in data: if self._quantum_instance.is_statevector: temp = results.get_statevector(circuits[circuit_id]) outcome_vector = (temp * temp.conj()).real # convert outcome_vector to outcome_dict, where key is a basis state and value is the count. # Note: the count can be scaled linearly, i.e., it does not have to be an integer. outcome_dict = {} bitstr_size = int(math.log2(len(outcome_vector))) for i in range(len(outcome_vector)): bitstr_i = format(i, '0' + str(bitstr_size) + 'b') outcome_dict[bitstr_i] = outcome_vector[i] else: outcome_dict = results.get_counts(circuits[circuit_id]) counts.append(outcome_dict) circuit_id += 1 probs = return_probabilities(counts, self._num_classes) predicted_probs.append(probs) predicted_labels.append(np.argmax(probs, axis=1)) if len(predicted_probs) == 1: predicted_probs = predicted_probs[0] if len(predicted_labels) == 1: predicted_labels = predicted_labels[0] return predicted_probs, predicted_labels # Breaks data into minibatches. Labels are optional, but will be broken into batches if included. def batch_data(self, data, labels=None, minibatch_size=-1): label_batches = None if 0 < minibatch_size < len(data): batch_size = min(minibatch_size, len(data)) if labels is not None: shuffled_samples, shuffled_labels = shuffle(data, labels, random_state=self.random) label_batches = np.array_split(shuffled_labels, batch_size) else: shuffled_samples = shuffle(data, random_state=self.random) batches = np.array_split(shuffled_samples, batch_size) else: batches = np.asarray([data]) label_batches = np.asarray([labels]) return batches, label_batches def is_gradient_really_supported(self): return self.optimizer.is_gradient_supported and not self.optimizer.is_gradient_ignored def train(self, data, labels, quantum_instance=None, minibatch_size=-1): """Train the models, and save results. Args: data (numpy.ndarray): NxD array, N is number of data and D is dimension labels (numpy.ndarray): Nx1 array, N is number of data quantum_instance (QuantumInstance): quantum backend with all setting minibatch_size (int): the size of each minibatched accuracy evalutation """ self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size self._batches, self._label_batches = self.batch_data(data, labels, minibatch_size) self._batch_index = 0 if self.initial_point is None: self.initial_point = self.random.randn(self._var_form.num_parameters) self._eval_count = 0 grad_fn = None if minibatch_size > 0 and self.is_gradient_really_supported(): # we need some wrapper grad_fn = self._gradient_function_wrapper self._ret = self.find_minimum( initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._cost_function_wrapper, optimizer=self.optimizer, gradient_fn = grad_fn # func for computing gradient ) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count del self._batches del self._label_batches del self._batch_index self._ret['training_loss'] = self._ret['min_val'] # temporary fix: this code should be unified with the gradient api in optimizer.py def _gradient_function_wrapper(self, theta): """Compute and return the gradient at the point theta. Args: theta (numpy.ndarray): 1-d array Returns: numpy.ndarray: 1-d array with the same shape as theta. The gradient computed """ epsilon = 1e-8 f_orig = self._cost_function_wrapper(theta) grad = np.zeros((len(theta),), float) for k in range(len(theta)): theta[k] += epsilon f_new = self._cost_function_wrapper(theta) grad[k] = (f_new - f_orig) / epsilon theta[k] -= epsilon # recover to the center state if self.is_gradient_really_supported(): self._batch_index += 1 # increment the batch after gradient callback return grad def _cost_function_wrapper(self, theta): batch_index = self._batch_index % len(self._batches) predicted_probs, predicted_labels = self._get_prediction(self._batches[batch_index], theta) total_cost = [] if not isinstance(predicted_probs, list): predicted_probs = [predicted_probs] for i in range(len(predicted_probs)): curr_cost = cost_estimate(predicted_probs[i], self._label_batches[batch_index]) total_cost.append(curr_cost) if self._callback is not None: self._callback( self._eval_count, theta[i * self._var_form.num_parameters:(i + 1) * self._var_form.num_parameters], curr_cost, self._batch_index ) self._eval_count += 1 if not self.is_gradient_really_supported(): self._batch_index += 1 # increment the batch after eval callback logger.debug('Intermediate batch cost: {}'.format(sum(total_cost))) return total_cost if len(total_cost) > 1 else total_cost[0] def test(self, data, labels, quantum_instance=None, minibatch_size=-1, params=None): """Predict the labels for the data, and test against with ground truth labels. Args: data (numpy.ndarray): NxD array, N is number of data and D is data dimension labels (numpy.ndarray): Nx1 array, N is number of data quantum_instance (QuantumInstance): quantum backend with all setting minibatch_size (int): the size of each minibatched accuracy evalutation params (list): list of parameters to populate in the variational form Returns: float: classification accuracy """ # minibatch size defaults to setting in instance variable if not set minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size batches, label_batches = self.batch_data(data, labels, minibatch_size) self.batch_num = 0 if params is None: params = self.optimal_params total_cost = 0 total_correct = 0 total_samples = 0 self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance for batch, label_batch in zip(batches, label_batches): predicted_probs, predicted_labels = self._get_prediction(batch, params) total_cost += cost_estimate(predicted_probs, label_batch) total_correct += np.sum((np.argmax(predicted_probs, axis=1) == label_batch)) total_samples += label_batch.shape[0] int_accuracy = np.sum((np.argmax(predicted_probs, axis=1) == label_batch)) / label_batch.shape[0] logger.debug('Intermediate batch accuracy: {:.2f}%'.format(int_accuracy * 100.0)) total_accuracy = total_correct / total_samples logger.info('Accuracy is {:.2f}%'.format(total_accuracy * 100.0)) self._ret['testing_accuracy'] = total_accuracy self._ret['test_success_ratio'] = total_accuracy self._ret['testing_loss'] = total_cost / len(batches) return total_accuracy def predict(self, data, quantum_instance=None, minibatch_size=-1, params=None): """Predict the labels for the data. Args: data (numpy.ndarray): NxD array, N is number of data, D is data dimension quantum_instance (QuantumInstance): quantum backend with all setting minibatch_size (int): the size of each minibatched accuracy evalutation params (list): list of parameters to populate in the variational form Returns: list: for each data point, generates the predicted probability for each class list: for each data point, generates the predicted label (that with the highest prob) """ # minibatch size defaults to setting in instance variable if not set minibatch_size = minibatch_size if minibatch_size > 0 else self._minibatch_size batches, _ = self.batch_data(data, None, minibatch_size) if params is None: params = self.optimal_params predicted_probs = None predicted_labels = None self._quantum_instance = self._quantum_instance if quantum_instance is None else quantum_instance for i, batch in enumerate(batches): if len(batches) > 0: logger.debug('Predicting batch {}'.format(i)) batch_probs, batch_labels = self._get_prediction(batch, params) if not predicted_probs and not predicted_labels: predicted_probs = batch_probs predicted_labels = batch_labels else: np.concatenate((predicted_probs, batch_probs)) np.concatenate((predicted_labels, batch_labels)) self._ret['predicted_probs'] = predicted_probs self._ret['predicted_labels'] = predicted_labels return predicted_probs, predicted_labels def _run(self): self.train(self._training_dataset[0], self._training_dataset[1]) if self._test_dataset is not None: self.test(self._test_dataset[0], self._test_dataset[1]) if self._datapoints is not None: predicted_probs, predicted_labels = self.predict(self._datapoints) self._ret['predicted_classes'] = map_label_to_class_name(predicted_labels, self._label_to_class) return self._ret def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params'] @property def ret(self): return self._ret @ret.setter def ret(self, new_value): self._ret = new_value @property def label_to_class(self): return self._label_to_class @property def class_to_label(self): return self._class_to_label def load_model(self, file_path): model_npz = np.load(file_path) self._ret['opt_params'] = model_npz['opt_params'] def save_model(self, file_path): model = {'opt_params': self._ret['opt_params']} np.savez(file_path, **model) @property def test_dataset(self): return self._test_dataset @property def training_dataset(self): return self._training_dataset @property def datapoints(self): return self._datapoints
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Tests for uniformly controlled single-qubit unitaries. """ import unittest from ddt import ddt from test import combine # pylint: disable=wrong-import-order import numpy as np from scipy.linalg import block_diag from qiskit.extensions.quantum_initializer.uc import UCGate from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute from qiskit.test import QiskitTestCase from qiskit.quantum_info.random import random_unitary from qiskit.compiler import transpile from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info import Operator _id = np.eye(2, 2) _not = np.matrix([[0, 1], [1, 0]]) @ddt class TestUCGate(QiskitTestCase): """Qiskit UCGate tests.""" @combine( squs=[ [_not], [_id], [_id, _id], [_id, 1j * _id], [_id, _not, _id, _not], [random_unitary(2, seed=541234).data for _ in range(2**2)], [random_unitary(2, seed=975163).data for _ in range(2**3)], [random_unitary(2, seed=629462).data for _ in range(2**4)], ], up_to_diagonal=[True, False], ) def test_ucg(self, squs, up_to_diagonal): """Test uniformly controlled gates.""" num_con = int(np.log2(len(squs))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(squs, q[1:], q[0], up_to_diagonal=up_to_diagonal) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) if up_to_diagonal: ucg = UCGate(squs, up_to_diagonal=up_to_diagonal) unitary = np.dot(np.diagflat(ucg._get_diagonal()), unitary) unitary_desired = _get_ucg_matrix(squs) self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) def test_global_phase_ucg(self): """Test global phase of uniformly controlled gates""" gates = [random_unitary(2).data for _ in range(2**2)] num_con = int(np.log2(len(gates))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(gates, q[1:], q[0], up_to_diagonal=False) simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_ucg_matrix(gates) self.assertTrue(np.allclose(unitary_desired, unitary)) def test_inverse_ucg(self): """Test inverse function of uniformly controlled gates""" gates = [random_unitary(2, seed=42 + s).data for s in range(2**2)] num_con = int(np.log2(len(gates))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(gates, q[1:], q[0], up_to_diagonal=False) qc.append(qc.inverse(), qc.qubits) unitary = Operator(qc).data unitary_desired = np.identity(2**qc.num_qubits) self.assertTrue(np.allclose(unitary_desired, unitary)) def _get_ucg_matrix(squs): return block_diag(*squs) if __name__ == "__main__": unittest.main()
https://github.com/jacobfeder/quantum_cadets
jacobfeder
import numpy as np import matplotlib.pyplot as plt from scipy import signal from qiskit import * from qiskit.circuit import ControlledGate, Gate, Instruction, Qubit, QuantumRegister, QuantumCircuit from qiskit.visualization import plot_histogram from qiskit.circuit.library.standard_gates import C4XGate, TGate, XGate, RZGate, RXGate from qiskit.ignis.characterization.characterization_utils import pad_id_gates from qiskit.circuit.library.generalized_gates import MCMT from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import phase_damping_error from typing import Union, Callable, List, Tuple def encode_X(num, qubits, register_size): non_register = qubits - register_size Xs = np.array([int(ch) for ch in np.binary_repr(num, width=register_size)], dtype=bool) registers = np.arange(register_size) return registers[Xs] + non_register, registers[np.invert(Xs)] +non_register def build_encode_circuit(num, qubits, register_size): """ Create the registery conversion circuit. Assume the last qubits are the register. qubits [int]: Total number of qubits in the global circuit register_size [int]: Total number of qubits allocated for the register. num [int]: target encoding """ # generate the X-gate configuration CGates, XGates = encode_X(num, qubits, register_size) # create a quantum circuit acting on the registers conv_register = MCMT(XGate(), len(CGates), len(XGates)) XRange = [*CGates, *XGates] return conv_register, XRange def quantum_cadets(n_qubits, noise_circuit, damping_error=0.02): """ n_qubits [int]: total number of qubits - 2^(n_qubits-1) is the number of qft points, plus one sensing qubit noise_circuit [function]: function that takes one input (a time index between 0-1) and returns a quantum circuit with 1 qubit damping_error [float]: T2 damping error """ register_size = n_qubits - 1 # Create a Quantum Circuit acting on the q register qr = QuantumRegister(n_qubits, 'q') cr = ClassicalRegister(register_size) qc = QuantumCircuit(qr, cr) # Add a H gate on qubit 1,2,3...N-1 for i in range(register_size): qc.h(i+1) # multi-qubit controlled-not (mcmt) gate mcmt_gate = MCMT(XGate(), register_size, 1) qr_range=[*range(1, n_qubits), 0] for bit in range(2**register_size): qc.append(mcmt_gate, [qr[i] for i in qr_range]) # external noise gates qc.append(noise_circuit(bit / 2**register_size), [qr[0]]) qc.append(mcmt_gate, [qr[i] for i in qr_range]) if bit == 0: for i in range(register_size): qc.x(i + (n_qubits - register_size)) elif bit == 2**register_size - 1: pass else: conv_register, XRange = build_encode_circuit(bit, n_qubits, register_size) qc.append(conv_register, qr[XRange]) # run the QFT qft = circuit.library.QFT(register_size) qc.append(qft, qr[1:n_qubits]) # map the quantum measurement to classical bits qc.measure(range(1, n_qubits), range(0, register_size)) # display the quantum circuit in text form print(qc.draw('text')) #qc.draw('mpl') plt.show() # noise model t2_noise_model = NoiseModel() t2_noise_model.add_quantum_error(phase_damping_error(damping_error), 'id', [0]) # run the quantum circuit on the statevector simulator backend #backend = Aer.get_backend('statevector_simulator') # run the quantum circuit on the qasm simulator backend backend = Aer.get_backend('qasm_simulator') # number of histogram samples shots = 10000 # execute the quantum program job = execute(qc, backend, noise_model=t2_noise_model, shots=shots) # outputstate = result.get_statevector(qc, decimals=3) # visualization.plot_state_city(outputstate) result = job.result() # collect the state histogram counts counts = result.get_counts(qc) #plot_histogram(counts) qft_result = np.zeros(2**register_size) for f in range(len(qft_result)): # invert qubit order and convert to string f_bin_str = ('{0:0' + str(register_size) + 'b}').format(f)[::-1] if f_bin_str in counts: if f: # flip frequency axis and assign histogram counts qft_result[2**register_size - f] = counts[f_bin_str] / shots else: # assign histogram counts, no flipping because of qft representation (due to nyquist sampling?) qft_result[0] = counts[f_bin_str] / shots freq = np.arange(2**register_size) plt.plot(freq, qft_result, label='QFT') plt.xlabel('Frequency (Hz)') # print the final measurement results print('QFT spectrum:') print(qft_result) # show the plots plt.show() if __name__ == "__main__": def narrowband_noise(time): """ Apply a single-frequency noise source """ f = 13.1 qr = QuantumRegister(1) qc = QuantumCircuit(qr, name='narrowband_noise') qc.append(RZGate(2 * np.pi * f * time), [qr[0]]) return qc def internal_t2_noise(time): """ Apply a large number of identity gates, which will accumulate errors due to the inherent T2 noise """ n_ids = int(80*time) + 1 qr = QuantumRegister(1) qc = QuantumCircuit(qr, name='t2_noise') qc.h(qr[0]) qc = pad_id_gates(qc, qr, 0, n_ids) return qc # arg 1: number of qubits (QFT size + 1) # arg 2: noise function quantum_cadets(7, internal_t2_noise, damping_error=0.02)
https://github.com/mlvqc/Byskit
mlvqc
from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() #provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj') from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer from qiskit import execute # Create one 4 qubit QuantumRegister to hold the Bayesian network and an ancilla qubit, # and a 3 bit ClassicalRegister to hold the sampled values net = QuantumRegister(4, 'qreg') cl = ClassicalRegister(3, 'creg') circ = QuantumCircuit(net, cl, name='circ') from numpy import arcsin, sqrt, pi def probToAngle(prob): """ Converts a given P(1) value into an equivalent theta value. """ return 2*arcsin(sqrt(prob)) # Setting up a qubit to represent the variable P circ.u3(probToAngle(0.35), 0, 0, net[0]) # Since we have P = 1, we use the second row of the probability table for the variable E circ.u3(probToAngle(0.76), 0, 0, net[1]) # Setting up the qubit representing H assuming that E = 0 circ.u3(probToAngle(0.39), 0, 0, net[2]) def oracle(circ): """ Implements an oracle that flips the sign of states that contain P = 1. """ circ.cu3(pi, pi, 0, net[0], net[1]) circ.cu3(pi, pi, 0, net[0], net[1]) return circ def u_gate(circ): """ Implements the U gate that flips states about the average amplitude. """ # Implements the quantum circuit that converts ψ -> |000...0> circ.u3(-1*probToAngle(0.35), 0, 0, net[0]) circ.u3(-1*probToAngle(0.76), 0, 0, net[1]) circ.u3(-1*probToAngle(0.39), 0, 0, net[2]) # Flipping the |000...0> state using a triple controlled Z gate condtioned on P, E and H, # and applied to the ancilla circ.x(net) circ.cu1(pi/4, net[0], net[3]) circ.cx(net[0], net[1]) circ.cu1(-pi/4, net[1], net[3]) circ.cx(net[0], net[1]) circ.cu1(pi/4, net[1], net[3]) circ.cx(net[1], net[2]) circ.cu1(-pi/4, net[2], net[3]) circ.cx(net[0], net[2]) circ.cu1(pi/4, net[2], net[3]) circ.cx(net[1], net[2]) circ.cu1(-pi/4, net[2], net[3]) circ.cx(net[0], net[2]) circ.cu1(pi/4, net[2], net[3]) circ.x(net) # Implements the quantum circuit that converts |000...0> -> ψ circ.u3(probToAngle(0.35), 0, 0, net[0]) circ.u3(probToAngle(0.76), 0, 0, net[1]) circ.u3(probToAngle(0.39), 0, 0, net[2]) return circ # Apply oracle and U gate twice circ = oracle(circ) circ = u_gate(circ) circ = oracle(circ) circ = u_gate(circ) circ.x(net[0]) # Measure E, and rotate H to the P(1) value in the second row of the P(H|E) table condtioned on E circ.measure(net[1], cl[1]) circ.u3(probToAngle(0.82) - probToAngle(0.39), 0, 0, net[2]) # Sample by measuring the rest of the qubits circ.measure(net[0], cl[0]) circ.measure(net[2], cl[2]) # Get backend from Aer provider backend = Aer.get_backend('qasm_simulator') # Run job many times to get multiple samples samples_list = [] n_samples = 1000 for i in range(n_samples): job = execute(circ, backend=backend, shots=1) result = list(job.result().get_counts(circ).keys())[0] if result[2] == '1': samples_list.append(result) # Printing the number of useful samples and percentage of samples rejected print() print(n_samples, 'samples drawn:', len(samples_list), 'samples accepted,', n_samples-len(samples_list), 'samples rejected.' ) print('Percentage of samples rejected: ', 100*(1 - (len(samples_list)/n_samples)), '%') # Computing P(H = 0| P = 1) p_H = 0 for i in samples_list: if i[0] == '0': p_H += 1 p_H /= len(samples_list) print('P(H = 0| P = 1) =', p_H) print()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) print(f"Number of qubits: {H2_op.num_qubits}") from qiskit.algorithms import NumPyMinimumEigensolver from qiskit.opflow import PauliSumOp numpy_solver = NumPyMinimumEigensolver() result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op)) ref_value = result.eigenvalue.real print(f"Reference value: {ref_value:.5f}") # define ansatz and optimizer from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SPSA iterations = 125 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") spsa = SPSA(maxiter=iterations) # define callback # note: Re-run this cell to restart lists before training counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) # define Aer Estimator for noiseless statevector simulation from qiskit.utils import algorithm_globals from qiskit_aer.primitives import Estimator as AerEstimator seed = 170 algorithm_globals.random_seed = seed noiseless_estimator = AerEstimator( run_options={"seed": seed, "shots": 1024}, transpile_options={"seed_transpiler": seed}, ) # instantiate and run VQE from qiskit.algorithms.minimum_eigensolvers import VQE vqe = VQE( noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}") print( f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}" ) import pylab pylab.rcParams["figure.figsize"] = (12, 4) pylab.plot(counts, values) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Convergence with no noise") from qiskit_aer.noise import NoiseModel from qiskit.providers.fake_provider import FakeVigo # fake providers contain data from real IBM Quantum devices stored in Qiskit Terra, # and are useful for extracting realistic noise models. device = FakeVigo() coupling_map = device.configuration().coupling_map noise_model = NoiseModel.from_backend(device) print(noise_model) noisy_estimator = AerEstimator( backend_options={ "method": "density_matrix", "coupling_map": coupling_map, "noise_model": noise_model, }, run_options={"seed": seed, "shots": 1024}, transpile_options={"seed_transpiler": seed}, ) # re-start callback variables counts = [] values = [] vqe.estimator = noisy_estimator result1 = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}") print( f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}" ) if counts or values: pylab.rcParams["figure.figsize"] = (12, 4) pylab.plot(counts, values) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Convergence with noise") print(f"Reference value: {ref_value:.5f}") print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}") print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/victor-onofre/Quantum_Algorithms
victor-onofre
import numpy as np import networkx as nx import matplotlib.pyplot as plt from scipy.optimize import minimize from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer style = {'backgroundcolor': 'lightyellow'} # Style of the drawing of the quantum circuit Graph_Example_1 = nx.Graph() Graph_Example_1.add_edges_from([[1,2],[2,3],[1,3]]) nx.draw(Graph_Example_1,with_labels=True,font_weight='bold') nx.draw(Graph_Example_1,node_color = ['b','b','r']) Graph_Example_2 = nx.Graph() Graph_Example_2.add_edges_from([[1,2],[1,3],[4,2],[4,3]]) nx.draw(Graph_Example_2,with_labels=True,font_weight='bold') nx.draw(Graph_Example_2,node_color = ['r','b','b','r']) Graph_Example_3 = nx.Graph() Graph_Example_3.add_edges_from([[1,4],[1,2],[2,5],[4,5],[5,3],[2,3]]) nx.draw(Graph_Example_3,with_labels=True,font_weight='bold') nx.draw(Graph_Example_3,node_color = ['r','b','b','r','b']) Graph = nx.Graph() Graph.add_edges_from([[0,1],[0,3],[3,4],[1,4],[1,2],[4,2]]) nx.draw(Graph,with_labels=True) Graph.edges() N = Graph.number_of_nodes() # The number of nodes in the graph qc = QuantumCircuit(N,N) # Quantum circuit with N qubits and N classical register gamma = np.pi/8 # parameter gamma for the cost function (maxcut hamiltonian) #Apply the operator to each edge for i, j in Graph.edges(): qc.cx(i,j) qc.rz(2*gamma, j) qc.cx(i,j) qc.barrier() qc.draw(output='mpl', style=style) # Draw the quantum circuit beta = np.pi/8 # parameter for the mixer hamiltonian for n in Graph.nodes(): qc.rx(2*beta, n) # measure the result qc.barrier(range(N)) qc.measure(range(N), range(N)) qc.draw(output='mpl', style=style,fold= 35) def qaoa_circuit(G, theta,p): r""" ############################################ # Compute the QAOA circuit for the graph G # # |psi(theta) > = |psi(beta,gamma) > = e^{-i*beta_p*B} e^{-i*gamma_p*C}... e^{-i*beta_1*B} e^{-i*gamma_1*C} H^{otimes n}|0> # # where C is the Maxcut hamiltonian, B is the mixer hamiltonian. # # G: graph # theta: parameters,first half is betas, second half is gammas # p: number of QAOA steps # return: The QAOA circuit ########################################### """ beta = theta[:p] #Parameters beta for the mixer hamiltonian gamma = theta[p:]#Parameters gamma for the maxcut hamiltonian N = G.number_of_nodes()#Number of nodes of the graph G qc = QuantumCircuit(N,N)# Quantum circuit wiht N qubits and N classical register qc.h(range(N))# Apply the Hadamard gate to all the qubits # Apply p operators for k in range(p): for i, j in G.edges(): #Representation of the maxcut hamiltonian qc.cx(i,j) qc.rz(2*gamma[k], j) qc.cx(i,j) qc.barrier() for n in G.nodes(): # Representation of the mixer hamiltonian qc.rx(2*beta[k], n) # Measurement in all the qubits qc.barrier(range(N)) qc.measure(range(N), range(N)) return qc #Returns the quantum circuit # p is the number of QAOA alternating operators p = 1 theta = np.array([np.pi/8,np.pi/8]) circuit = qaoa_circuit(Graph, theta,p) circuit.draw(output='mpl', style=style,fold= 35) # Draw the quantum circuit #Qiskit uses the least significant bit in the bistring, we need to invert this string def invert_counts(counts): r""" ############################################ # Inverted the binary string # # counts: The result of running the quantum circuit # return: The results with binary string inverted ########################################### """ inv_counts = {} for k, v in counts.items(): inv_counts[k[::-1]] = v return inv_counts def maxcut_objective_function(x,G): r""" ############################################ # Compute the maxcut objective function for the binary string x and graph G # # G: graph # x: binary string # return: The cost of the binary string x ########################################### """ cut = 0 for i, j in G.edges(): if x[i] != x[j]: cut -= 1# the edge is cut return cut # Sum of all the edges that are cut def function_to_minimize(G,p): r""" ############################################ # Define the function to minimize given the graph G and the number of parameters # # G: graph # p: number of parameters # return: The function to minimize ########################################### """ backend = Aer.get_backend('qasm_simulator') def f(theta): r""" ############################################ # Function that gives the energy for parameters theta # # theta: parameters # return: Energy ########################################### """ qc = qaoa_circuit(G,theta,p) # Gives the circuit of QAOA fot a graph G, parameters theta and p operators counts = execute(qc, backend, seed_simulator=10).result().get_counts()# Run the circuit and get the results using the backedn "qasm_simulator" E = 0 # Initial energy total_counts = 0 # Initial counts #Qiskit uses the least significant bit in the bistring, we need to invert this string InvertedCounts = invert_counts(counts) #Inverted the binary string # meas is the binary string measure # meas_count is the number of times that the binary string has been measure for meas, meas_count in InvertedCounts.items(): objective_function = maxcut_objective_function(meas, G)#Compute the maxcut objetive function fot the binary string meas E += objective_function*meas_count # Define the energy as the value of the objective functions times the counts of that measure total_counts += meas_count # The total number of measures in the system return E/total_counts # Returns the energy given the parameters theta return f p = 5 # p is the number of QAOA alternating operators objective_function = function_to_minimize(Graph, p) x0=np.random.randn(10)#Initial parameters minim_solution = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy minim_solution optimal_theta = minim_solution['x'] # The optimal parameters to use optimal_theta backend = Aer.get_backend('qasm_simulator') qc = qaoa_circuit(Graph, optimal_theta,p) # Define the quantum circuit with the optimal parameters counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results #energies = {bs: maxcut_objective_function(bs, Graph) for bs, _ in counts.items()} #energies_sorted = {bs: en for bs, en in sorted(energies.items(), key=lambda item: item[1])} #print(energies_sorted) #print({bs: counts[bs] for bs, energy in energies_sorted.items()}) # Compute the maxcut objective function for the optimal parameters results = [] for x in counts.keys(): results.append([maxcut_objective_function(x,Graph),x]) # Get the best solution given the results of the maxcut objective function best_cut, best_solution = min(results) print(f"Best string: {best_solution} with cut: {-best_cut}") # Define the colors of the nodes for the best solution colors = ['r' if best_solution[node] == '0' else 'b' for node in Graph] nx.draw(Graph,node_color = colors) def solution_max_cut(G): r""" ############################################ # Compute the solution for the maxcut problem given a graph G # # G: graph # return:The draw of the best solution with two colors. Print the solution in the binary string form and the number of cuts ############### """ p = 5 # p is the number of QAOA alternating operators objective_function = function_to_minimize(G, p) x0=np.random.randn(10)#Initial parameters new_parameters = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy optimal_theta = new_parameters['x']# The optimal parameters to use qc = qaoa_circuit(G, optimal_theta,p) # Define the quantum circuit with the optimal parameters counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results # Compute the maxcut objective function for the optimal parameters results = [] for x in counts.keys(): results.append([maxcut_objective_function(x,G),x]) best_cut, best_solution = min(results) # Get the best solution given the results of the maxcut objective function colors = ['r' if best_solution[node] == '0' else 'b' for node in G] # Define the colors of the nodes for the best solution return nx.draw(G,node_color = colors),print(f"Best string: {best_solution} with cut: {-best_cut}") Graph1 = nx.Graph() Graph1.add_edges_from([[0,1],[0,2],[2,1]]) nx.draw(Graph1,with_labels=True) solution_max_cut(Graph1) graph2 = nx.random_regular_graph(3, 4, seed=1234) nx.draw(graph2) #drawing the graph plt.show() #plotting the graph solution_max_cut(graph2) graph3 = nx.random_regular_graph(3, 12, seed=1234) nx.draw(graph3) #drawing the graph plt.show() #plotting the graph solution_max_cut(graph3)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import ZFeatureMap, RealAmplitudes from qiskit.utils import algorithm_globals from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN # set random seed algorithm_globals.random_seed = 42 num_qubits = 3 # create a feature map feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) # create a variational circuit ansatz = RealAmplitudes(num_qubits, reps=1) # combine feature map and ansatz into a single circuit qc = QuantumCircuit(num_qubits) qc.append(feature_map, range(num_qubits)) qc.append(ansatz, range(num_qubits)) qc.decompose().draw("mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, sparse=False, ) # we can set the total number of input samples and weight samples for random selection num_input_samples = 10 num_weight_samples = 10 global_ed = EffectiveDimension( qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples ) # we can also provide user-defined samples and parameters input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs)) weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights)) global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples) # finally, we will define ranges to test different numbers of data, n n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000] global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0]) d = qnn.num_weights print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0)) print( "Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d) ) global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n) print("Effective dimension: {}".format(global_eff_dim_1)) print("Number of weights: {}".format(d)) # plot the normalized effective dimension for the model plt.plot(n, np.array(global_eff_dim_1) / d) plt.xlabel("Number of data") plt.ylabel("Normalized GLOBAL effective dimension") plt.show() num_inputs = 3 num_samples = 50 X, y = make_classification( n_samples=num_samples, n_features=num_inputs, n_informative=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, ) X = MinMaxScaler().fit_transform(X) y = 2 * y - 1 # labels in {-1, 1} estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct classifier initial_point = algorithm_globals.random.random(estimator_qnn.num_weights) estimator_classifier = NeuralNetworkClassifier( neural_network=estimator_qnn, optimizer=COBYLA(maxiter=80), initial_point=initial_point, callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function (callback) objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) trained_weights = estimator_classifier.weights # get Local Effective Dimension for set of trained weights local_ed_trained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X ) local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for trained QNN: ", local_eff_dim_trained / estimator_qnn.num_weights, ) # get Local Effective Dimension for set of untrained weights local_ed_untrained = LocalEffectiveDimension( qnn=estimator_qnn, weight_samples=initial_point, input_samples=X ) local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n) print( "normalized local effective dimensions for untrained QNN: ", local_eff_dim_untrained / estimator_qnn.num_weights, ) # plot the normalized effective dimension for the model plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights") plt.plot( n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights" ) plt.xlabel("Number of data") plt.ylabel("Normalized LOCAL effective dimension") plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem from qiskit_nature.settings import settings settings.dict_aux_operators = True driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["VibrationalEnergy"] print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) # this is now done explicitly and already requires the basis problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianLogResult from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis from qiskit_nature.settings import settings settings.dict_aux_operators = True log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") hamiltonian = log_result.get_vibrational_energy() print(hamiltonian) hamiltonian.basis = HarmonicBasis([2, 2, 3, 4]) op = hamiltonian.second_q_ops()["VibrationalEnergy"] print("\n".join(str(op).splitlines()[:10] + ["..."])) from qiskit_nature.second_q.drivers import GaussianLogResult from qiskit_nature.second_q.formats import watson_to_problem from qiskit_nature.second_q.problems import HarmonicBasis log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log") watson = log_result.get_watson_hamiltonian() print(watson) basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = watson_to_problem(watson, basis) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers.second_quantization import GaussianForcesDriver from qiskit_nature.problems.second_quantization import VibrationalStructureProblem driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("VibrationalEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import GaussianForcesDriver from qiskit_nature.second_q.problems import HarmonicBasis driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") basis = HarmonicBasis(num_modals=[2, 2, 3, 4]) problem = driver.run(basis=basis) problem.hamiltonian.truncation_order = 2 hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
from tsp_qaoa import test_solution from qiskit.visualization import plot_histogram import networkx as nx import numpy as np import json import csv # Array of JSON Objects header = ['p', 'state', 'probability', 'mean'] length_p = 10 with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) first_p = False for p in range(length_p): p = p+1 if first_p == False: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p) first_p = True else: job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p) # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"] print(mean) state = 0 for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]: state += 1 writer.writerow([p,state, probability,mean])
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
PavanCyborg
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=1 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 use_XX_YY_ZZ_gates = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends gate_counts_plots = True #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import os,json from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hamiltonian Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # import precalculated data to compare against filename = os.path.join("precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits): # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] return correct_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### for circuit_id in range(num_circuits): print("*********************************************") print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}") #creation of Quantum Circuit. ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/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/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 the BasicSwap pass""" import unittest from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.layout import Layout from qiskit.transpiler import CouplingMap, Target from qiskit.circuit.library import CXGate from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestBasicSwap(QiskitTestCase): """Tests the BasicSwap pass.""" def test_trivial_case(self): """No need to have any swap, the CX are distance 1 to each other q0:--(+)-[U]-(+)- | | q1:---.-------|-- | q2:-----------.-- CouplingMap map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """No need to have any swap, two CXs distance 1 to each other, in the same layer q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- CouplingMap map: [0]--[1]--[2]--[3] """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(dag, after) def test_a_single_swap(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_with_target(self): """Adding a swap q0:------- q1:--(+)-- | q2:---.--- CouplingMap map: [1]--[0]--[2] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ target = Target() target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None}) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(target) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_a_single_swap_bigger_cm(self): """Swapper in a bigger coupling map q0:------- q1:---.--- | q2:--(+)-- CouplingMap map: [1]--[0]--[2]--[3] q0:--X---.--- | | q1:--X---|--- | q2:-----(+)-- """ coupling = CouplingMap([[0, 1], [0, 2], [2, 3]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[0]) expected.cx(qr[0], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_keep_layout(self): """After a swap, the following gates also change the wires. qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- CouplingMap map: [0]--[1]--[2] qr0:--X----------- | qr1:--X---.--[H]-- | qr2:-----(+)------ """ coupling = CouplingMap([[1, 0], [1, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.h(qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.cx(qr[1], qr[2]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap(self): """A far swap that affects coming CXs. qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- CouplingMap map: [0]--[1]--[2]--[3] qr0:--X-------------- | qr1:--X--X----------- | qr2:-----X--(+)---.-- | | qr3:---------.---(+)- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[1], qr[2]) expected.cx(qr[2], qr[3]) expected.cx(qr[3], qr[2]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_front(self): """A far swap with a gate in the front. q0:------(+)-- | q1:-------|--- | q2:-------|--- | q3:--[H]--.--- CouplingMap map: [0]--[1]--[2]--[3] q0:-----------(+)-- | q1:---------X--.--- | q2:------X--X------ | q3:-[H]--X--------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.h(qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_back(self): """A far swap with a gate in the back. q0:--(+)------ | q1:---|------- | q2:---|------- | q3:---.--[H]-- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)------ | q1:-----X--.--[H]-- | q2:--X--X---------- | q3:--X------------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_far_swap_with_gate_the_middle(self): """A far swap with a gate in the middle. q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.swap(qr[3], qr[2]) expected.swap(qr[2], qr[1]) expected.cx(qr[1], qr[0]) expected.h(qr[1]) expected.cx(qr[0], qr[1]) pass_ = BasicSwap(coupling) after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_fake_run(self): """A fake run, doesn't change dag q0:--(+)-------.-- | | q1:---|--------|-- | q2:---|--------|-- | | q3:---.--[H]--(+)- CouplingMap map: [0]--[1]--[2]--[3] q0:-------(+)-------.--- | | q1:-----X--.--[H]--(+)-- | q2:--X--X--------------- | q3:--X------------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) circuit.cx(qr[0], qr[3]) fake_pm = PassManager([BasicSwap(coupling, fake_run=True)]) real_pm = PassManager([BasicSwap(coupling, fake_run=False)]) self.assertEqual(circuit, fake_pm.run(circuit)) self.assertNotEqual(circuit, real_pm.run(circuit)) self.assertIsInstance(fake_pm.property_set["final_layout"], Layout) self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"]) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# External imports from pylab import cm from sklearn import metrics import numpy as np import matplotlib.pyplot as plt # Qiskit imports from qiskit import QuantumCircuit from qiskit.circuit import ParameterVector from qiskit.visualization import circuit_drawer from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import ZZFeatureMap from qiskit_machine_learning.kernels import TrainableFidelityQuantumKernel from qiskit_machine_learning.kernels.algorithms import QuantumKernelTrainer from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.datasets import ad_hoc_data class QKTCallback: """Callback wrapper class.""" def __init__(self) -> None: self._data = [[] for i in range(5)] def callback(self, x0, x1=None, x2=None, x3=None, x4=None): """ Args: x0: number of function evaluations x1: the parameters x2: the function value x3: the stepsize x4: whether the step was accepted """ self._data[0].append(x0) self._data[1].append(x1) self._data[2].append(x2) self._data[3].append(x3) self._data[4].append(x4) def get_callback_data(self): return self._data def clear_callback_data(self): self._data = [[] for i in range(5)] adhoc_dimension = 2 X_train, y_train, X_test, y_test, adhoc_total = ad_hoc_data( training_size=20, test_size=5, n=adhoc_dimension, gap=0.3, plot_data=False, one_hot=False, include_sample_total=True, ) plt.figure(figsize=(5, 5)) plt.ylim(0, 2 * np.pi) plt.xlim(0, 2 * np.pi) plt.imshow( np.asmatrix(adhoc_total).T, interpolation="nearest", origin="lower", cmap="RdBu", extent=[0, 2 * np.pi, 0, 2 * np.pi], ) plt.scatter( X_train[np.where(y_train[:] == 0), 0], X_train[np.where(y_train[:] == 0), 1], marker="s", facecolors="w", edgecolors="b", label="A train", ) plt.scatter( X_train[np.where(y_train[:] == 1), 0], X_train[np.where(y_train[:] == 1), 1], marker="o", facecolors="w", edgecolors="r", label="B train", ) plt.scatter( X_test[np.where(y_test[:] == 0), 0], X_test[np.where(y_test[:] == 0), 1], marker="s", facecolors="b", edgecolors="w", label="A test", ) plt.scatter( X_test[np.where(y_test[:] == 1), 0], X_test[np.where(y_test[:] == 1), 1], marker="o", facecolors="r", edgecolors="w", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Ad hoc dataset for classification") plt.show() # Create a rotational layer to train. We will rotate each qubit the same amount. training_params = ParameterVector("θ", 1) fm0 = QuantumCircuit(2) fm0.ry(training_params[0], 0) fm0.ry(training_params[0], 1) # Use ZZFeatureMap to represent input data fm1 = ZZFeatureMap(2) # Create the feature map, composed of our two circuits fm = fm0.compose(fm1) print(circuit_drawer(fm)) print(f"Trainable parameters: {training_params}") # Instantiate quantum kernel quant_kernel = TrainableFidelityQuantumKernel(feature_map=fm, training_parameters=training_params) # Set up the optimizer cb_qkt = QKTCallback() spsa_opt = SPSA(maxiter=10, callback=cb_qkt.callback, learning_rate=0.05, perturbation=0.05) # Instantiate a quantum kernel trainer. qkt = QuantumKernelTrainer( quantum_kernel=quant_kernel, loss="svc_loss", optimizer=spsa_opt, initial_point=[np.pi / 2] ) # Train the kernel using QKT directly qka_results = qkt.fit(X_train, y_train) optimized_kernel = qka_results.quantum_kernel print(qka_results) # Use QSVC for classification qsvc = QSVC(quantum_kernel=optimized_kernel) # Fit the QSVC qsvc.fit(X_train, y_train) # Predict the labels labels_test = qsvc.predict(X_test) # Evalaute the test accuracy accuracy_test = metrics.balanced_accuracy_score(y_true=y_test, y_pred=labels_test) print(f"accuracy test: {accuracy_test}") plot_data = cb_qkt.get_callback_data() # callback data K = optimized_kernel.evaluate(X_train) # kernel matrix evaluated on the training samples plt.rcParams["font.size"] = 20 fig, ax = plt.subplots(1, 2, figsize=(14, 5)) ax[0].plot([i + 1 for i in range(len(plot_data[0]))], np.array(plot_data[2]), c="k", marker="o") ax[0].set_xlabel("Iterations") ax[0].set_ylabel("Loss") ax[1].imshow(K, cmap=cm.get_cmap("bwr", 20)) fig.tight_layout() plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/bibscore/qiskit_kindergarten
bibscore
import os from qiskit import * import qiskit.tools.visualization as qt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi import matplotlib.pyplot as plt %matplotlib inline qreg_q = QuantumRegister(3, 'q') creg_c = ClassicalRegister(3, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.x(qreg_q[0]) circuit.x(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.toffoli(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[2], creg_c[2]) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots = 1024).result() counts = result.get_counts() print(counts) qt.plot_histogram(counts, title="Histogram with the evaluating of |011> state under Toffoli transformation")
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
AlphaMiyaL
import qiskit qiskit.__qiskit_version__ from qiskit import IBMQ IBMQ.save_account('d3d29913a9b505c699f877ab1ade9d7729ee46bf49670047e44a106ff692c5efec8ff03873c1fe6f1d4e76e090e6177ab37bd7c5beb08c2fa1096316c0dc1006') IBMQ.load_account()
https://github.com/muehlhausen/vqls-bachelor-thesis
muehlhausen
# all libraries used by some part of the VQLS-implementation from qiskit import ( QuantumCircuit, QuantumRegister, ClassicalRegister, 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 import params # import the vqls algorithm and corresponding code from vqls import ( generate_ansatz, hadamard_test, calculate_beta, calculate_delta, calculate_local_cost_function, minimize_local_cost_function, postCorrection, _format_alpha, _calculate_expectationValue_HadamardTest, _U_primitive ) # 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 a simulation of the VQLS-algorithm " + "with 4 qubits, 4 layers in the Ansatz and a single Id-gate acting" + " on the second qubit.\n" + "To simulate another problem, one can either alter _U_primitive " + "in vqls.py to change |x_0>, GlobalParameters.py to change A " + "or its decomposition respectively." ) # Executing the 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})$ and copy $A$ ansatz = generate_ansatz(alpha_min).to_gate() A_copy = params.A.copy() if isinstance(params.A, Operator): A_copy = A_copy.to_instruction() # apply $V(\vec{alpha})$ and $A$ to the circuit # this results in a state that is approximately $\ket{b}$ circ_min.append(ansatz, qr_min) circ_min.append(A_copy, qr_min) # 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_primitive() """ 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 simulation.\n" + "Reminder: 4 qubits and an Id-gate on the second qubit." + "|x_0> was defined by Hadamard gates acting on qubits 0 and 3.\n" + "The return value of the minimizer (alpha_min):\n" + str(alpha_min) + "\nThe resulting statevector for a circuit to which " + "V(alpha_min) and A and the post correction were applied:\n" + str(result.get_statevector()) ) 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()) ) print("these were Id gates and in U y on 0 and 1")
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/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/qBraid/qBraid
qBraid
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Module for configuring IBM provider credentials and authentication. """ import os from typing import TYPE_CHECKING, Optional import qiskit from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_ibm_runtime.accounts import ChannelType from qbraid.programs import ProgramSpec from qbraid.runtime.enums import DeviceType from qbraid.runtime.profile import TargetProfile from qbraid.runtime.provider import QuantumProvider from .device import QiskitBackend if TYPE_CHECKING: import qiskit_ibm_runtime import qbraid.runtime.qiskit class QiskitRuntimeProvider(QuantumProvider): """ This class is responsible for managing the interactions and authentications with the IBM Quantum services. Attributes: token (str): IBM Cloud API key or IBM Quantum API token. runtime_service (qiskit_ibm_runtime.QiskitRuntimeService): IBM Quantum runtime service. """ def __init__( self, token: Optional[str] = None, channel: Optional[ChannelType] = None, **kwargs ): """ Initializes the QbraidProvider object with optional AWS and IBM Quantum credentials. Args: token (str, optional): IBM Quantum token. Defaults to None. """ self.token = token or os.getenv("QISKIT_IBM_TOKEN") self.channel = channel or os.getenv("QISKIT_IBM_CHANNEL", "ibm_quantum") self._runtime_service = QiskitRuntimeService( token=self.token, channel=self.channel, **kwargs ) @property def runtime_service(self) -> "qiskit_ibm_runtime.QiskitRuntimeService": """Returns the IBM Quantum runtime service.""" return self._runtime_service def save_config( self, token: Optional[str] = None, channel: Optional[str] = None, overwrite: bool = True, **kwargs, ) -> None: """Saves IBM runtime service account to disk for future use.""" token = token or self.token channel = channel or self.channel QiskitRuntimeService.save_account( token=token, channel=channel, overwrite=overwrite, **kwargs ) def _build_runtime_profile( self, backend: "qiskit_ibm_runtime.IBMBackend", program_spec: Optional[ProgramSpec] = None ) -> TargetProfile: """Builds a runtime profile from a backend.""" program_spec = program_spec or ProgramSpec(qiskit.QuantumCircuit) config = backend.configuration() if config.local: device_type = DeviceType.LOCAL_SIMULATOR elif config.simulator: device_type = DeviceType.SIMULATOR else: device_type = DeviceType.QPU return TargetProfile( device_id=backend.name, device_type=device_type, num_qubits=config.n_qubits, program_spec=program_spec, instance=backend._instance, max_shots=config.max_shots, provider_name="IBM", ) def get_devices( self, operational=True, **kwargs ) -> list["qbraid.runtime.qiskit.QiskitBackend"]: """Returns the IBM Quantum provider backends.""" backends = self.runtime_service.backends(operational=operational, **kwargs) program_spec = ProgramSpec(qiskit.QuantumCircuit) return [ QiskitBackend( profile=self._build_runtime_profile(backend, program_spec=program_spec), service=self.runtime_service, ) for backend in backends ] def get_device( self, device_id: str, instance: Optional[str] = None ) -> "qbraid.runtime.qiskit.QiskitBackend": """Returns the IBM Quantum provider backends.""" backend = self.runtime_service.backend(device_id, instance=instance) return QiskitBackend( profile=self._build_runtime_profile(backend), service=self.runtime_service ) def least_busy( self, simulator=False, operational=True, **kwargs ) -> "qbraid.runtime.qiskit.QiskitBackend": """Return the least busy IBMQ QPU.""" backend = self.runtime_service.least_busy( simulator=simulator, operational=operational, **kwargs ) return QiskitBackend( profile=self._build_runtime_profile(backend), service=self.runtime_service )
https://github.com/tuf65651/quantum-research
tuf65651
#!/usr/bin/env python # coding: utf-8 # In[13]: get_ipython().run_line_magic('matplotlib', 'inline') # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import math # Loading your IBM Q account(s) IBMQ.load_accounts() # In[14]: backend = Aer.get_backend("qasm_simulator") # In[26]: n_reg = QuantumRegister(4, 'n') m_reg = QuantumRegister(8, 'm') c_reg = ClassicalRegister(8, 'y') qc = QuantumCircuit(n_reg, m_reg,c_reg) # In[27]: # Register n set to 5 qc.x(n_reg[0]) qc.x(n_reg[2]) # Register m set to 3 qc.x(m_reg[0]) qc.x(m_reg[1]) # In[24]: def bit_shift_x_bits(circuit, control_reg, acc_reg, power): """Implement bit shift. @param circuit: QuantumCircuit containing operands @param control_reg: QuantumRegister containing qubit that defines power (all operations conditional on this) @param acc_reg: QuantumRegister containing integer to shift @param power: int number of places to shift (if control_reg[power])""" ## NOTE: Power is the number of places to shift. Power 1 is controlled by ## control register's 2nd bit, which is control_reg[1] ## and refers to shift of 2^1, or shift one place # Flip all qubits in accumulator to allow ripple carry # for qubit in range(len(acc_reg)): # circuit.x(acc_reg[qubit]) for target_bit in range(len(acc_reg) - 1): # shift bit by correct number of places circuit.ccx(control_reg[power], acc_reg[target_bit], acc_reg[target_bit + power]) # Flip next bit if carry occurs for flipped_bit in range(target_bit, len(acc_reg) - 1): ## Carry occurs if target now 0 (if flip makes it 1). circuit.cx(control_reg[power], acc_reg[flipped_bit]) circuit.ccx(control_reg[power], acc_reg[flipped_bit], acc_reg[flipped_bit + 1]) circuit.cx(control_reg[power], acc_reg[flipped_bit]) # Flip bit that's being shifted # circuit.cx(control_reg[power], acc_reg[target_bit]) # In[28]: bit_shift_x_bits(qc, n_reg, m_reg, 1) for index in range(len(n_reg)): qc.measure(n_reg[index], c_reg[index]) qc.draw() # In[29]: simulate = execute(qc, backend=backend, shots=1024).result() # In[30]: simulate.get_counts() # In[6]: print([x for x in range(9, 4, -1)]) # In[ ]:
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
import sympy from sympy import * import numpy as np from numpy import random import math import scipy init_printing(use_unicode=True) from matplotlib import pyplot as plt %matplotlib inline from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum import TensorProduct as tp from mpmath import factorial as fact import io import base64 #from IPython.core.display import display, HTML, clear_output from IPython import * from ipywidgets import interactive, interact, fixed, interact_manual, widgets import csv import importlib import scipy.interpolate from mpl_toolkits.mplot3d import Axes3D, proj3d from itertools import product, combinations from matplotlib.patches import FancyArrowPatch from matplotlib import cm, colors from sympy.functions.special.tensor_functions import KroneckerDelta from scipy.linalg import polar, lapack import mpmath # constantes físicas e = 1.60217662*10**-19 # C (carga elementar) k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb) eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo) mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo) h = 6.626069*10**-34 # Js (constante de Planck) heV = h/e # em eV hb = h/(2*math.pi) # hbar hbeV = hb/e # em eV c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo) G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional) kB = 1.38065*10**-23 # J/K (constante de Boltzmann) me = 9.109382*10**-31 # kg (massa do elétron) mp = 1.6726219*10**-27 # kg (massa do próton) mn = 1.67492749804*10**-27 # kg (massa do nêutron) mT = 5.9722*10**24 # kg (massa da Terra) mS = 1.98847*10**30 # kg (massa do Sol) u = 1.660538921*10**-27 # kg (unidade de massa atômica) dTS = 1.496*10**11 # m (distância Terra-Sol) rT = 6.3781*10**6 # m (raio da Terra) sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann) Ri = 10973734.848575922 # m^-1 (constante de Rydberg) al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina) a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr) ge = 2 # (fator giromagnetico do eletron) gp = 5.58 # (fator giromagnetico do proton) def id(n): '''retorna a matriz identidade nxn''' id = zeros(n,n) for j in range(0,n): id[j,j] = 1 return id #id(2) def pauli(j): '''retorna as matrizes de Pauli''' if j == 1: return Matrix([[0,1],[1,0]]) elif j == 2: return Matrix([[0,-1j],[1j,0]]) elif j == 3: return Matrix([[1,0],[0,-1]]) #pauli(1), pauli(2), pauli(3) def tr(A): '''retorna o traço de uma matriz''' d = A.shape[0] tr = 0 for j in range(0,d): tr += A[j,j] return tr #tr(pauli(1)) def comm(A,B): '''retorna a função comutador''' return A*B-B*A #comm(pauli(1),pauli(2)) def acomm(A,B): '''retorna a função anti-comutador''' return A*B+B*A #acomm(pauli(1),pauli(2)) def cb(n,j): '''retorna um vetor da base padrão de C^n''' vec = zeros(n,1) vec[j] = 1 return vec #cb(2,0) def proj(psi): '''retorna o projeto no vetor psi''' d = psi.shape[0] P = zeros(d,d) for j in range(0,d): for k in range(0,d): P[j,k] = psi[j]*conjugate(psi[k]) return P #proj(cb(2,0)) def bell(j,k): if j == 0 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1))) elif j == 0 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0))) elif j == 1 and k == 0: return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0))) elif j == 1 and k == 1: return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1))) #bell(0,0), bell(0,1), bell(1,0), bell(1,1) def inner_product(v,w): d = len(v); ip = 0 for j in range(0,d): ip += conjugate(v[j])*w[j] return ip #a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w) def norm(v): d = len(v) return sqrt(inner_product(v,v)) #v = [2,2]; norm(v) def tp(x,y): return tensorproduct(x,y) A = tp(pauli(3),pauli(1)); A
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/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Test linear mcx with ancilla """ from unittest import TestCase import numpy as np from qiskit import QuantumCircuit, QuantumRegister, transpile from qiskit.quantum_info import Operator from qclib.gates.mcx import McxVchainDirty, LinearMcx def apply_control_state_on_quantum_circuit( quantum_circuit: QuantumCircuit, control_qubits: QuantumRegister, ctrl_state: str ): """ Applies the X gate to the corresponding qubit in which the bit string describes it to be in state 0 as a means to simulate open controlled operations on a specific set of qubits. This operations are applied using Qiskit's QuantumCircuit object instead of Gate object. Parameters ---------- quantum_circuit : QuantumCircuit object on which the X gates are to be applied control_bits : QuantumRegister containing with the qubits to be used as control ctrl_state : String of binary digits describing wich state is used as control in the multicontrolled operation """ if ctrl_state is not None: for i, ctrl in enumerate(ctrl_state[::-1]): if ctrl == "0": quantum_circuit.x(control_qubits[i]) class TestLinearMCX(TestCase): """Testing qclib.gates.mcx_gate""" def test_linear_mcx(self): """Test if linear_mcx is correct""" for num_qubits in range(8, 9): self._operator_cmp( num_qubits=num_qubits, mcx_method=LinearMcx, mode="recursion" ) def _compare_linear_mcx_action_only(self, num_qubits, ctrl_state=None): """Test if linear_mcx is correct""" linear_circuit = QuantumCircuit(num_qubits) qiskit_circuit = QuantumCircuit(num_qubits) theta = np.random.uniform(0.0, 2.0 * np.pi) mcx_method = LinearMcx( num_qubits - 2, ctrl_state=ctrl_state, action_only=True ).definition linear_circuit.append(mcx_method, list(range(num_qubits))) linear_circuit.rz(theta, num_qubits - 1) linear_circuit.append(mcx_method.inverse(), list(range(num_qubits))) mcx_qiskit = self._build_qiskit_method_mcx_recursive( num_qubits=num_qubits, ctrl_state=ctrl_state, mode="recursion" ) qiskit_circuit.append(mcx_qiskit, list(range(num_qubits))) qiskit_circuit.rz(theta, num_qubits - 1) qiskit_circuit.append(mcx_qiskit, list(range(num_qubits))) linear_op = Operator(linear_circuit).data qiskit_op = Operator(qiskit_circuit).data self.assertTrue(np.allclose(linear_op, qiskit_op)) def test_linear_mcx_action_only(self): """Test linear mcx action only""" for num_qubits in range(8, 9): self._compare_linear_mcx_action_only(num_qubits) def test_linear_mcx_action_only_random_ctrl_state(self): """Test if linear_mcx is correct""" num_qubit_range = list(range(8, 9)) basis_states = [ f"{np.random.randint(2 ** (n_ctrl - 2)):0{n_ctrl - 2}b}" for n_ctrl in num_qubit_range ] for num_qubits, ctrl_state in zip(num_qubit_range, basis_states): self._compare_linear_mcx_action_only(num_qubits, ctrl_state) def test_linear_mcx_depth(self): """Test linear_mcx depth""" for num_qubits in range(10, 11): mcx_dirty_ancilla = LinearMcx(num_qubits - 2).definition mcx_qiskit = QuantumCircuit(num_qubits) mcx_qiskit.mcx( control_qubits=list(range(num_qubits - 2)), target_qubit=num_qubits - 2, ancilla_qubits=num_qubits - 1, mode="recursion", ) tr_mcx_dirty_ancilla = transpile(mcx_dirty_ancilla, basis_gates=["u", "cx"]) tr_mcx_qiskit = transpile(mcx_qiskit, basis_gates=["u", "cx"]) self.assertLess(tr_mcx_dirty_ancilla.depth(), tr_mcx_qiskit.depth()) def _operator_cmp( self, num_qubits, mcx_method: LinearMcx, mode: str, ctrl_state: str = None, action_only=False, ): """ Compares if the custom operator defined by the custom MCX method is the same as the one defined by Qiskit MCX method. Parameters ---------- params: qubit_range : The number of qubits with which our method needs to be tested McxMethod : The class definition of the method to be used. It must be `LinearMcx` action_only : Decide wether or not use only the action of the V-Chain of Toffoli gates """ # for num_qubits in qubit_range: mcx_method = mcx_method( num_qubits - 2, ctrl_state=ctrl_state, action_only=action_only ).definition mcx_qiskit = self._build_qiskit_method_mcx_recursive( num_qubits=num_qubits, ctrl_state=ctrl_state, mode=mode ) mcx_method_op = Operator(mcx_method).data mcx_qiskit_op = Operator(mcx_qiskit).data self.assertTrue(np.allclose(mcx_method_op, mcx_qiskit_op)) def _build_qiskit_method_mcx_recursive( self, num_qubits, ctrl_state: str = None, mode="recursive", ): """ Bulds qiskit quantum circuit with mcx-recursive method to be used as reference for comparison Parameters ---------- num_qubits : Total number of qubits on the system ctrl_state : string with binary digits that specifies the control state mode : Decomposition mode to be used for multicontrolled operation """ num_controls = num_qubits - 2 control_qubits = QuantumRegister(num_controls) target_qubit = QuantumRegister(1) ancilla_qubits = QuantumRegister(1) mcx_qiskit = QuantumCircuit( control_qubits, target_qubit, ancilla_qubits, ) apply_control_state_on_quantum_circuit( quantum_circuit=mcx_qiskit, control_qubits=control_qubits, ctrl_state=ctrl_state, ) mcx_qiskit.mcx( control_qubits=control_qubits, target_qubit=target_qubit, ancilla_qubits=ancilla_qubits, mode=mode, ) apply_control_state_on_quantum_circuit( quantum_circuit=mcx_qiskit, control_qubits=control_qubits, ctrl_state=ctrl_state, ) return mcx_qiskit class TestMcxVchainDirty(TestCase): """Test class McxVchainDirty""" def test_mcx_v_chain_dirty_depth(self): """Test mcx_v_chain_dirty depth""" for num_controls in range(10, 11): num_ancilla = num_controls - 2 control_qubits = QuantumRegister(num_controls) ancilla_qubits = QuantumRegister(num_ancilla) target_qubit = QuantumRegister(1) mcx_v_chain = McxVchainDirty(num_controls).definition mcx_v_chain_qiskit = QuantumCircuit( control_qubits, ancilla_qubits, target_qubit ) mcx_v_chain_qiskit.mcx( control_qubits=control_qubits, target_qubit=target_qubit, ancilla_qubits=ancilla_qubits, mode="v-chain-dirty", ) tr_mcx_v_chain = transpile(mcx_v_chain, basis_gates=["u", "cx"]) tr_mcx_v_chain_qiskit = transpile( mcx_v_chain_qiskit, basis_gates=["u", "cx"] ) self.assertTrue(8 * num_controls - 6 == tr_mcx_v_chain.count_ops()["cx"]) self.assertLess(tr_mcx_v_chain.depth(), tr_mcx_v_chain_qiskit.depth()) def test_mcx_v_chain_dirty(self): """Test McxVchainDirty""" for num_controls in range(6, 7): self._operator_cmp( num_controls=num_controls, mcx_method=McxVchainDirty, mode="v-chain-dirty", ) def test_mcx_v_chain_dirty_random_ctrl_state(self): """ Test if mcx_v_chain_dirty is correct with non trivial randomly generated control states """ control_qubit_range = list(range(6, 7)) basis_states = [ f"{np.random.randint(2 ** n_ctrl):0{n_ctrl}b}" for n_ctrl in control_qubit_range ] for num_controls, ctrl_state in zip(control_qubit_range, basis_states): self._operator_cmp( num_controls=num_controls, mcx_method=McxVchainDirty, mode="v-chain-dirty", ctrl_state=ctrl_state, ) def test_mcx_v_chain_3targets(self): """Test multiple targets McxVchainDirty""" # mcx_v_chain_circuit num_controls = 4 num_target_qubit = 3 mcx_v_chain_circuit = McxVchainDirty( num_controls, num_target_qubit=num_target_qubit ).definition # qiskit_circuit qiskit_circuit = QuantumCircuit(9) controls_idx = list(np.arange(4)) for target_idx in range(6, 9): qiskit_circuit.mcx(controls_idx, [target_idx]) mcx_v_chain_op = Operator(mcx_v_chain_circuit).data qiskit_mcx_op = Operator(qiskit_circuit).data tr_mcx_v_chain = transpile(mcx_v_chain_circuit, basis_gates=["u", "cx"]) self.assertTrue(np.allclose(mcx_v_chain_op, qiskit_mcx_op)) if num_controls > 3: self.assertTrue( 10 + 8 * (num_controls - 2) + 2 * (num_target_qubit - 1) == tr_mcx_v_chain.count_ops()["cx"] ) def _operator_cmp( self, num_controls, mcx_method: McxVchainDirty, mode: str, ctrl_state: str = None, action_only=False, ): """ Compares if the custom operator defined by the custom MCX method is the same as the one defined by Qiskit MCX method. Parameters ---------- control_qubit_range: The number of control qubits mcx_method: The class definition of the method to be used. It must be `McxVchainDirty` action_only: Decide wether or not use only the action of the V-Chain of Toffoli gates """ mcx_method = mcx_method( num_controls, ctrl_state=ctrl_state, action_only=action_only ).definition # defining quiskit's mcx_v_chain_qiskit = self._build_qiskit_method_mcx_vchain_dirty( num_controls=num_controls, mode=mode, ctrl_state=ctrl_state ) mcx_method_op = Operator(mcx_method).data mcx_v_chain_qiskit_op = Operator(mcx_v_chain_qiskit).data self.assertTrue(np.allclose(mcx_method_op, mcx_v_chain_qiskit_op)) def _build_qiskit_method_mcx_vchain_dirty( self, num_controls, mode: str, ctrl_state: str = None, ): """ Bulds qiskit quantum circuit with mcx-vchain-dirty method to be used as reference for comparison Parameters ---------- num_controls : Total number of control qubits on the system ctrl_state : string with binary digits that specifies the control state mode : Decomposition mode to be used for multicontrolled operation """ num_ancilla = num_controls - 2 control_qubits = QuantumRegister(num_controls) ancilla_qubits = QuantumRegister(num_ancilla) target_qubit = QuantumRegister(1) mcx_qiskit = QuantumCircuit(control_qubits, ancilla_qubits, target_qubit) apply_control_state_on_quantum_circuit( quantum_circuit=mcx_qiskit, control_qubits=control_qubits, ctrl_state=ctrl_state, ) mcx_qiskit.mcx( control_qubits=control_qubits, target_qubit=target_qubit, ancilla_qubits=ancilla_qubits, mode=mode, ) apply_control_state_on_quantum_circuit( quantum_circuit=mcx_qiskit, control_qubits=control_qubits, ctrl_state=ctrl_state, ) return mcx_qiskit
https://github.com/joe5218/Quantum-Distortions
joe5218
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, QuantumRegister from qiskit.qasm import pi from qiskit.tools.visualization import plot_histogram, circuit_drawer from qiskit import execute, Aer, BasicAer import numpy as np import random import keras from keras.models import Sequential from keras.layers import Dense, Activation from keras.datasets import mnist import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, mean_absolute_error, mutual_info_score, r2_score from PIL import Image from resizeimage import resizeimage def margolus(circ, t, c0, c1): circ.ry(np.pi / 4, t) circ.cx(c0, t) circ.ry(np.pi / 4, t) circ.cx(c1, t) circ.ry(-np.pi / 4, t) circ.cx(c0, t) circ.ry(-np.pi / 4, t) def rccx(circ, t, c0, c1): circ.h(t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.cx(c1, t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.h(t) def rcccx(circ, t, c0, c1, c2): circ.h(t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.h(t) circ.cx(c1, t) circ.t(t) circ.cx(c2, t) circ.tdg(t) circ.cx(c1, t) circ.t(t) circ.cx(c2, t) circ.tdg(t) circ.h(t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.h(t) def ccry(circ, angle, t, c0, c1): circ.cu3(angle / 2, 0, 0, c1, t) circ.cx(c1, c0) circ.cu3(-angle / 2, 0, 0, c0, t) circ.cx(c1, c0) circ.cu3(angle / 2, 0, 0, c0, t) def mary(circ, angle, t, c0, c1): circ.ry(angle / 4, t) circ.cx(c0, t) circ.ry(-angle / 4, t) circ.cx(c1, t) circ.ry(angle / 4, t) circ.cx(c0, t) circ.ry(-angle / 4, t) circ.cx(c1, t) def cccry(circ, angle, t, a, c0, c1, c2): margolus(circ, a, c1, c2) mary(circ, angle, t, a, c0) margolus(circ, a, c1, c2) def mary_4(circ, angle, t, c0, c1, c2): circ.h(t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.h(t) circ.cx(c1, t) circ.rz(angle / 4, t) circ.cx(c2, t) circ.rz(-angle / 4, t) circ.cx(c1, t) circ.rz(angle / 4, t) circ.cx(c2, t) circ.rz(-angle / 4, t) circ.h(t) circ.t(t) circ.cx(c0, t) circ.tdg(t) circ.h(t) def mary_8(circ, angle, t, c0, c1, c2, c3, c4, c5, c6): circ.h(t) circ.t(t) rccx(circ, t, c0, c1) circ.tdg(t) circ.h(t) rccx(circ, t, c2, c3) circ.rz(angle / 4, t) rcccx(circ, t, c4, c5, c6) circ.rz(-angle / 4, t) rccx(circ, t, c2, c3) circ.rz(angle / 4, t) rcccx(circ, t, c4, c5, c6) circ.rz(-angle / 4, t) circ.h(t) circ.t(t) rccx(circ, t, c0, c1) circ.tdg(t) circ.h(t) def c10ry(circ, angle, bin, target, anc, controls): # c10mary(qc, 2 * x_train[img_num][i], format(i, '010b'), 0, 1, [i for i in range(2,12)]) print(bin) clist = [] for i in bin: clist.append(int(i)) for i in range(len(clist)): if clist[i] == 0: circ.x(controls[-i - 1]) margolus(circ, anc, controls[0], controls[1]) circ.x(controls[0]) circ.x(controls[1]) margolus(circ, controls[1], controls[2], controls[3]) circ.x(controls[2]) circ.x(controls[3]) margolus(circ, controls[3], controls[4], controls[5]) circ.x(controls[4]) circ.x(controls[5]) margolus(circ, controls[5], controls[8], controls[9]) margolus(circ, controls[4], controls[6], controls[7]) margolus(circ, controls[2], controls[4], controls[5]) margolus(circ, controls[0], controls[2], controls[3]) mary_4(circ, angle, target, anc, controls[0], controls[1]) margolus(circ, controls[0], controls[2], controls[3]) margolus(circ, controls[2], controls[4], controls[5]) margolus(circ, controls[4], controls[6], controls[7]) margolus(circ, controls[5], controls[8], controls[9]) circ.x(controls[5]) circ.x(controls[4]) margolus(circ, controls[3], controls[4], controls[5]) circ.x(controls[3]) circ.x(controls[2]) margolus(circ, controls[1], controls[2], controls[3]) circ.x(controls[1]) circ.x(controls[0]) margolus(circ, anc, controls[0], controls[1]) for i in range(len(clist)): if clist[i] == 0: circ.x(controls[-i - 1]) def c10mary(circ, angle, bin, target, anc, controls): # c10mary(qc, 2 * x_train[img_num][i], format(i, '010b'), 0, 1, [i for i in range(2,12)]) clist = [] for i in bin: clist.append(int(i)) # print("angle", angle) # print("clist - bin",clist) for i in range(len(clist)): if clist[i] == 0: circ.x(controls[-i - 1]) rccx(circ, anc, controls[4], controls[5]) # circuit_drawer(circ,output='mpl', filename='my_circuit_rccx.png') circ.x(controls[4]) circ.x(controls[5]) rccx(circ, controls[4], controls[6], controls[7]) rccx(circ, controls[5], controls[8], controls[9]) mary_8(circ, angle, target, anc, controls[0], controls[1], controls[2], controls[3], controls[4], controls[5]) rccx(circ, controls[5], controls[8], controls[9]) rccx(circ, controls[4], controls[6], controls[7]) circ.x(controls[5]) circ.x(controls[4]) rccx(circ, anc, controls[4], controls[5]) for i in range(len(clist)): if clist[i] == 0: circ.x(controls[-i - 1]) # for i in range(len(clist)): # circ.x(controls[i]) def image_normalization(image): image = resizeimage.resize_cover(image, [32, 32]) w, h = 32, 32 image = np.array([[image.getpixel((x, y))[0] for x in range(w)] for y in range(h)]) # 2-dimentional data convert to 1-dimentional array image = image.flatten() # change type image = image.astype('float64') # Normalization(0~pi/2) image /= 255.0 generated_image = np.arcsin(image) return generated_image if __name__ == '__main__': # (x_train, y_train), (x_test, y_test) = mnist.load_data() # img_num = 1 # #show original image # plt.imshow(x_train[img_num], cmap='gray') # #plt.savefig('mnistimg'+str(img_num)+'.png') # plt.show() # # 2-dimentional data convert to 1-dimentional array # x_train = x_train.reshape(60000, 784) # # change type # x_train = x_train.astype('float64') # # Normalization(0~pi/2) # x_train /= 255.0 # x_train = np.arcsin(x_train) x_train = image_normalization(Image.open("cat.png").convert('LA')) backends = Aer.backends() # print("Aer backends:",backends) qubit = 12 qc = QuantumCircuit(qubit, qubit) # apply hadamard gates qc.h(range(2, qubit)) # image1 = image_normalization(image1) # apply c10Ry gates (representing color data) for i in range(len(x_train)): if x_train[i] != 0: c10mary(qc, 2 * x_train[i], format(i, '010b'), 0, 1, [i for i in range(2, 12)]) # qc.x(range(2,qubit)) qc.measure(range(qubit), range(qubit)) backend_sim = Aer.get_backend('qasm_simulator') # print(qc.depth()) numOfShots = 1000000 result = execute(qc, backend_sim, shots=numOfShots).result() # circuit_drawer(qc).show() # plot_histogram(result.get_counts(qc)) print(result.get_counts(qc)) # generated image genimg = np.array([]) #### decode for i in range(len(x_train)): try: genimg = np.append(genimg, [np.sqrt(result.get_counts(qc)[format(i, '010b') + '01'] / numOfShots)]) except KeyError: genimg = np.append(genimg, [0.0]) # inverse nomalization genimg *= 32.0 * 255.0 x_train = np.sin(x_train) x_train *= 255.0 # convert type genimg = genimg.astype('int') # back to 2-dimentional data genimg = genimg.reshape((32, 32)) plt.imshow(genimg, cmap='gray', vmin=0, vmax=255) # plt.savefig('gen_'+str(img_num)+'.png') plt.show()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/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/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
import qiskit qiskit.__qiskit_version__ from math import pi import numpy as np import scipy as sp import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import BasicAer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor # Load saved IBMQ accounts IBMQ.load_account() # We first define controlled gates used in the IPEA def cu1fixed(qProg, c, t, a): qProg.u1(-a, t) qProg.cx(c, t) qProg.u1(a, t) qProg.cx(c, t) def cu5pi8(qProg, c, t): cu1fixed(qProg, c, t, -5.0*pi/8.0) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(2) cr = ClassicalRegister(4) circuitName="IPEAonSimulator" ipeaCircuit = QuantumCircuit(qr, cr) # Apply IPEA ipeaCircuit.h(qr[0]) for i in range(8): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[0]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(4): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 1) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[1]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) for i in range(2): cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/4, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-pi/2, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/4, qr[0]).c_if(cr, 3) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[2]) ipeaCircuit.reset(qr[0]) ipeaCircuit.h(qr[0]) cu5pi8(ipeaCircuit, qr[0], qr[1]) ipeaCircuit.u1(-pi/8, qr[0]).c_if(cr, 1) ipeaCircuit.u1(-2*pi/8, qr[0]).c_if(cr, 2) ipeaCircuit.u1(-3*pi/8, qr[0]).c_if(cr, 3) ipeaCircuit.u1(-4*pi/8, qr[0]).c_if(cr, 4) ipeaCircuit.u1(-5*pi/8, qr[0]).c_if(cr, 5) ipeaCircuit.u1(-6*pi/8, qr[0]).c_if(cr, 6) ipeaCircuit.u1(-7*pi/8, qr[0]).c_if(cr, 7) ipeaCircuit.h(qr[0]) ipeaCircuit.measure(qr[0], cr[3]) backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(ipeaCircuit, backend=backend, shots=shots).result() plot_histogram(results.get_counts()) # We then prepare quantum and classical registers and the circuit qr = QuantumRegister(5) cr = ClassicalRegister(5) realStep1Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep1Circuit.h(qr[0]) for i in range(8): cu5pi8(realStep1Circuit, qr[0], qr[1]) realStep1Circuit.h(qr[0]) realStep1Circuit.measure(qr[0], cr[0]) #connect to remote API to be able to use remote simulators and real devices print("Available backends:", [BasicAer.backends(), IBMQ.backends()]) backend = IBMQ.get_backend("ibmq_5_yorktown") shots = 1000 job_exp1 = execute(realStep1Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results1 = job_exp1.result() plot_histogram(results1.get_counts()) realStep2Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep2Circuit.h(qr[0]) for i in range(4): cu5pi8(realStep2Circuit, qr[0], qr[1]) realStep2Circuit.u1(-pi/2, qr[0]) # Assuming the value of the measurement on Step 1 realStep2Circuit.h(qr[0]) realStep2Circuit.measure(qr[0], cr[0]) job_exp2 = execute(realStep2Circuit, backend=backend, shots=shots) job_monitor(job_exp1) results2 = job_exp2.result() plot_histogram(results2.get_counts()) realStep3Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep3Circuit.h(qr[0]) for i in range(2): cu5pi8(realStep3Circuit, qr[0], qr[1]) realStep3Circuit.u1(-3*pi/4, qr[0]) # Assuming the value of the measurement on Step 1 and Step 2 realStep3Circuit.h(qr[0]) realStep3Circuit.measure(qr[0], cr[0]) job_exp3 = execute(realStep3Circuit, backend=backend, shots=shots) job_monitor(job_exp3) results3 = job_exp3.result() plot_histogram(results3.get_counts()) realStep4Circuit = QuantumCircuit(qr, cr) # Apply IPEA realStep4Circuit.h(qr[0]) cu5pi8(realStep4Circuit, qr[0], qr[1]) realStep4Circuit.u1(-3*pi/8, qr[0]) # Assuming the value of the measurement on Step 1, 2, and 3 realStep4Circuit.h(qr[0]) realStep4Circuit.measure(qr[0], cr[0]) job_exp4 = execute(realStep4Circuit, backend=backend, shots=shots) job_monitor(job_exp4) results4 = job_exp4.result() plot_histogram(results4.get_counts())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring import unittest import os from unittest.mock import patch from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.utils import optionals from qiskit import visualization from qiskit.visualization.circuit import text from qiskit.visualization.exceptions import VisualizationError if optionals.HAS_MATPLOTLIB: from matplotlib import figure if optionals.HAS_PIL: from PIL import Image _latex_drawer_condition = unittest.skipUnless( all( ( optionals.HAS_PYLATEX, optionals.HAS_PIL, optionals.HAS_PDFLATEX, optionals.HAS_PDFTOCAIRO, ) ), "Skipped because not all of PIL, pylatex, pdflatex and pdftocairo are available", ) class TestCircuitDrawer(QiskitTestCase): def test_default_output(self): with patch("qiskit.user_config.get_config", return_value={}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "mpl"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_output_with_user_config_not_set(self): with patch("qiskit.user_config.get_config", return_value={"other_option": True}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_kwarg_priority_over_user_config_default_output(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit, output="mpl") self.assertIsInstance(out, figure.Figure) @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available") def test_default_backend_auto_output_with_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, figure.Figure) def test_default_backend_auto_output_without_mpl(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}): with optionals.HAS_MATPLOTLIB.disable_locally(): circuit = QuantumCircuit() out = visualization.circuit_drawer(circuit) self.assertIsInstance(out, text.TextDrawing) @_latex_drawer_condition def test_latex_unsupported_image_format_error_message(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() with self.assertRaises(VisualizationError, msg="Pillow could not write the image file"): visualization.circuit_drawer(circuit, filename="file.spooky") @_latex_drawer_condition def test_latex_output_file_correct_format(self): with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}): circuit = QuantumCircuit() filename = "file.gif" visualization.circuit_drawer(circuit, filename=filename) with Image.open(filename) as im: if filename.endswith("jpg"): self.assertIn(im.format.lower(), "jpeg") else: self.assertIn(im.format.lower(), filename.split(".")[-1]) os.remove(filename) def test_wire_order(self): """Test wire_order See: https://github.com/Qiskit/qiskit-terra/pull/9893""" 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, 10) expected = "\n".join( [ " ", " q_2: ────────────", " ┌───┐ ┌───┐ ", " q_3: ┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", " q_0: ┤ H ├───╫───", " ├───┤ ║ ", " q_1: ┤ X ├───╫───", " └───┘┌──╨──┐", " c: 4/═════╡ 0xa ╞", " └─────┘", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1]) self.assertEqual(result.__str__(), expected) def test_wire_order_cregbundle(self): """Test wire_order with cregbundle=True See: https://github.com/Qiskit/qiskit-terra/pull/9893""" 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, 10) expected = "\n".join( [ " ", " q_2: ────────────", " ┌───┐ ┌───┐ ", " q_3: ┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", " q_0: ┤ H ├───╫───", " ├───┤ ║ ", " q_1: ┤ X ├───╫───", " └───┘┌──╨──┐", " c: 4/═════╡ 0xa ╞", " └─────┘", "ca: 2/════════════", " ", ] ) result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1], cregbundle=True) self.assertEqual(result.__str__(), expected) def test_wire_order_raises(self): """Verify we raise if using wire order incorrectly.""" circuit = QuantumCircuit(3, 3) circuit.x(1) with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"): visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5]) with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"): visualization.circuit_drawer(circuit, wire_order=[0, 1, 2, 5, 4, 3], reverse_bits=True) with self.assertWarnsRegex(RuntimeWarning, "cregbundle set"): visualization.circuit_drawer(circuit, cregbundle=True, wire_order=[0, 1, 2, 5, 4, 3]) def test_reverse_bits(self): """Test reverse_bits should not raise warnings when no classical qubits: See: https://github.com/Qiskit/qiskit-terra/pull/8689""" circuit = QuantumCircuit(3) circuit.x(1) expected = "\n".join( [ " ", "q_2: ─────", " ┌───┐", "q_1: ┤ X ├", " └───┘", "q_0: ─────", " ", ] ) result = visualization.circuit_drawer(circuit, output="text", reverse_bits=True) self.assertEqual(result.__str__(), expected) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc for LaTeX conversion") def test_no_explict_cregbundle(self): """Test no explicit cregbundle should not raise warnings about being disabled See: https://github.com/Qiskit/qiskit-terra/issues/8690""" inner = QuantumCircuit(1, 1, name="inner") inner.measure(0, 0) circuit = QuantumCircuit(2, 2) circuit.append(inner, [0], [0]) expected = "\n".join( [ " ┌────────┐", "q_0: ┤0 ├", " │ │", "q_1: ┤ inner ├", " │ │", "c_0: ╡0 ╞", " └────────┘", "c_1: ══════════", " ", ] ) result = circuit.draw("text") self.assertEqual(result.__str__(), expected) # Extra tests that no cregbundle (or any other) warning is raised with the default settings # for the other drawers, if they're available to test. circuit.draw("latex_source") if optionals.HAS_MATPLOTLIB and optionals.HAS_PYLATEX: circuit.draw("mpl")
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# -*- 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/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, backend=FakeBoeblingen())
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/AbeerVaishnav13/Quantum-Programs
AbeerVaishnav13
from qiskit import QuantumCircuit alice_key = '11100100010001001001001000001111111110100100100100010010010001010100010100100100101011111110001010100010010001001010010010110010' alice_bases = '11000110011000100001100101110000111010011001111111110100010111010100000100011001101010100001010010101011010001011001110011111111' def alice_prepare_qubit(qubit_index): ## WRITE YOUR CODE HERE qc = QuantumCircuit(1, 1) if alice_key[qubit_index] == '1': qc.x(0) if alice_bases[qubit_index] == '1': qc.h(0) return qc ## WRITE YOUR CODE HERE
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QuantumCircuit.find_bit.""" from ddt import ddt, data, unpack from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase @ddt class TestQuantumCircuitFindBit(QiskitTestCase): """Test cases for QuantumCircuit.find_bit.""" @data(Qubit, Clbit) def test_bit_not_in_circuit(self, bit_type): """Verify we raise if the bit has not been attached to the circuit.""" qc = QuantumCircuit() bit = bit_type() with self.assertRaisesRegex(CircuitError, r"Could not locate provided bit"): qc.find_bit(bit) @data(Qubit, Clbit) def test_registerless_bit_constructor(self, bit_type): """Verify we find individual bits added via QuantumCircuit constructor.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) @data(Qubit, Clbit) def test_registerless_add_bits(self, bit_type): """Verify we find individual bits added via QuantumCircuit.add_bits.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) def test_registerless_add_int(self): """Verify we find bits and implicit registers added via QuantumCircuit(int, int).""" qc = QuantumCircuit(5, 2) qubits = qc.qubits clbits = qc.clbits # N.B. After deprecation of implicit register creation via # QuantumCircuit(int, int) in PR#6582 and subsequent removal, this test # should be updated to verify no registers are found. qr = qc.qregs[0] cr = qc.cregs[0] for idx, bit in enumerate(qubits): self.assertEqual(qc.find_bit(bit), (idx, [(qr, idx)])) for idx, bit in enumerate(clbits): self.assertEqual(qc.find_bit(bit), (idx, [(cr, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_reg_constructor(self, reg_type): """Verify we find register bits added via QuantumCicrcuit(reg).""" reg = reg_type(5, "reg") qc = QuantumCircuit(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_add_reg(self, reg_type): """Verify we find register bits added QuantumCircuit.add_register.""" reg = reg_type(5, "reg") qc = QuantumCircuit() qc.add_register(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) def test_ancilla_register_add_register(self): """Verify AncillaRegisters are found by find_bit by their locations in qubits/qregs.""" qreg = QuantumRegister(3, "qr") areg = AncillaRegister(5, "ar") qc = QuantumCircuit() qc.add_register(qreg) qc.add_register(areg) for idx, bit in enumerate(areg): self.assertEqual(qc.find_bit(bit), (idx + len(qreg), [(areg, idx)])) @data([Qubit, QuantumRegister], [Clbit, ClassicalRegister]) @unpack def test_multiple_register_from_bit(self, bit_type, reg_type): """Verify we find individual bits in multiple registers.""" bits = [bit_type() for _ in range(10)] even_reg = reg_type(bits=bits[::2]) odd_reg = reg_type(bits=bits[1::2]) fwd_reg = reg_type(bits=bits) rev_reg = reg_type(bits=bits[::-1]) qc = QuantumCircuit() qc.add_bits(bits) qc.add_register(even_reg, odd_reg, fwd_reg, rev_reg) for idx, bit in enumerate(bits): if idx % 2: self.assertEqual( qc.find_bit(bit), (idx, [(odd_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) else: self.assertEqual( qc.find_bit(bit), (idx, [(even_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) @data(QuantumRegister, ClassicalRegister) def test_multiple_register_from_reg(self, reg_type): """Verify we find register bits in multiple registers.""" reg1 = reg_type(6, "reg1") reg2 = reg_type(4, "reg2") even_reg = reg_type(bits=(reg1[:] + reg2[:])[::2]) odd_reg = reg_type(bits=(reg1[:] + reg2[:])[1::2]) qc = QuantumCircuit(reg1, reg2, even_reg, odd_reg) for idx, bit in enumerate(reg1): if idx % 2: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (odd_reg, idx // 2)])) else: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (even_reg, idx // 2)])) for idx, bit in enumerate(reg2): circ_idx = len(reg1) + idx if idx % 2: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (odd_reg, circ_idx // 2)]) ) else: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (even_reg, circ_idx // 2)]) )
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for eigenvalue estimators. """ from qiskit.aqua import Pluggable from qiskit import QuantumCircuit from abc import abstractmethod class Eigenvalues(Pluggable): """Base class for eigenvalue estimation. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: params (dict): configuration dictionary """ @abstractmethod def __init__(self): super().__init__() @classmethod def init_params(cls, params): eigs_params = params.get(Pluggable.SECTION_KEY_EIGS) args = {k: v for k, v in eigs_params.items() if k != 'name'} return cls(**args) @abstractmethod def get_register_sizes(self): raise NotImplementedError() @abstractmethod def get_scaling(self): raise NotImplementedError() @abstractmethod def construct_circuit(self, mode, register=None): """Construct the eigenvalue estimation quantum circuit. Args: mode (str): 'matrix' or 'circuit' register (QuantumRegister): register for circuit construction where eigenvalues will be stored. Returns: QuantumCircuit object for the eigenvalue estimation circuit. """ raise NotImplementedError() def construct_inverse(self, mode, circuit): """Construct the inverse eigenvalue estimation quantum circuit. Args: mode (str): consctruction mode, 'matrix' not supported circuit (QuantumCircuit): the quantum circuit to invert Returns: QuantumCircuit object for of the inverted eigenvalue estimation circuit. """ if mode == 'matrix': raise NotImplementedError('The matrix mode is not supported.') if circuit is None: raise ValueError('Circuit was not constructed beforehand.') self._inverse = circuit.inverse() return self._inverse
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 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. """Test the NormalizeRXAngle pass""" import unittest import numpy as np from ddt import ddt, named_data from qiskit import QuantumCircuit from qiskit.transpiler.passes.optimization.normalize_rx_angle import ( NormalizeRXAngle, ) from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import Target from qiskit.circuit.library.standard_gates import SXGate from test import QiskitTestCase # pylint: disable=wrong-import-order @ddt class TestNormalizeRXAngle(QiskitTestCase): """Tests the NormalizeRXAngle pass.""" def test_not_convert_to_x_if_no_calib_in_target(self): """Check that RX(pi) is NOT converted to X, if X calibration is not present in the target""" empty_target = Target() tp = NormalizeRXAngle(target=empty_target) qc = QuantumCircuit(1) qc.rx(90, 0) transpiled_circ = tp(qc) self.assertEqual(transpiled_circ.count_ops().get("x", 0), 0) def test_sx_conversion_works(self): """Check that RX(pi/2) is converted to SX, if SX calibration is present in the target""" target = Target() target.add_instruction(SXGate(), properties={(0,): None}) tp = NormalizeRXAngle(target=target) qc = QuantumCircuit(1) qc.rx(np.pi / 2, 0) transpiled_circ = tp(qc) self.assertEqual(transpiled_circ.count_ops().get("sx", 0), 1) def test_rz_added_for_negative_rotation_angles(self): """Check that RZ is added before and after RX, if RX rotation angle is negative""" backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(target=backend.target) # circuit to transpile and test qc = QuantumCircuit(1) qc.rx((-1 / 3) * np.pi, 0) transpiled_circ = tp(qc) # circuit to show the correct answer qc_ref = QuantumCircuit(1) qc_ref.rz(np.pi, 0) qc_ref.rx(np.pi / 3, 0) qc_ref.rz(-np.pi, 0) self.assertQuantumCircuitEqual(transpiled_circ, qc_ref) @named_data( {"name": "-0.3pi", "raw_theta": -0.3 * np.pi, "correct_wrapped_theta": 0.3 * np.pi}, {"name": "1.7pi", "raw_theta": 1.7 * np.pi, "correct_wrapped_theta": 0.3 * np.pi}, {"name": "2.2pi", "raw_theta": 2.2 * np.pi, "correct_wrapped_theta": 0.2 * np.pi}, ) def test_angle_wrapping_works(self, raw_theta, correct_wrapped_theta): """Check that RX rotation angles are correctly wrapped to [0, pi]""" backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(target=backend.target) # circuit to transpile and test qc = QuantumCircuit(1) qc.rx(raw_theta, 0) transpiled_circuit = tp(qc) wrapped_theta = transpiled_circuit.get_instructions("rx")[0].operation.params[0] self.assertAlmostEqual(wrapped_theta, correct_wrapped_theta) @named_data( { "name": "angles are within resolution", "resolution": 0.1, "rx_angles": [0.3, 0.303], "correct_num_of_cals": 1, }, { "name": "angles are not within resolution", "resolution": 0.1, "rx_angles": [0.2, 0.4], "correct_num_of_cals": 2, }, { "name": "same angle three times", "resolution": 0.1, "rx_angles": [0.2, 0.2, 0.2], "correct_num_of_cals": 1, }, ) def test_quantize_angles(self, resolution, rx_angles, correct_num_of_cals): """Test that quantize_angles() adds a new calibration only if the requested angle is not in the vicinity of the already generated angles. """ backend = GenericBackendV2(num_qubits=5) tp = NormalizeRXAngle(backend.target, resolution_in_radian=resolution) qc = QuantumCircuit(1) for rx_angle in rx_angles: qc.rx(rx_angle, 0) transpiled_circuit = tp(qc) angles = [ inst.operation.params[0] for inst in transpiled_circuit.data if inst.operation.name == "rx" ] angles_without_duplicate = list(dict.fromkeys(angles)) self.assertEqual(len(angles_without_duplicate), correct_num_of_cals) if __name__ == "__main__": unittest.main()
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): for target_qubit_index in range(qubit_index + 1, num_of_qubits): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit initial_thetas = np.random.uniform(low=0, high=360, size=32) initial_eigenvector = np.identity(16)[0] print(get_linear_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_linear_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_linear_entangelment_ansatz(2, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32) initial_eigenvector = np.identity(16)[0] print(get_full_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_full_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_full_entangelment_ansatz(2, initial_thetas, 3))
https://github.com/IceKhan13/purplecaffeine
IceKhan13
import os from qiskit.circuit.random import random_circuit from qiskit.quantum_info.random import random_pauli from qiskit.primitives import Estimator from purplecaffeine.core import Trial, LocalStorage n_qubits = 4 depth = 3 shots = 2000 circuit = random_circuit(n_qubits, depth) circuit.draw(fold=-1) obs = random_pauli(n_qubits) obs local_storage = LocalStorage("./trials") #You could also set the API storage or S3 storage by calling : #api_storage = ApiStorage(host="http://localhost:8000", username="MY_USERNAME", password="MY_PASS") #s3_storage = S3Storage("bucket", access_key="MY_KEY", secret_access_key="MY_SECRET") with Trial("Example trial", storage=local_storage) as trial: # track some parameters trial.add_parameter("estimator", "qiskit.primitives.Estimator") trial.add_parameter("depth", depth) trial.add_parameter("n_qubits", n_qubits) trial.add_parameter("shots", shots) # track objects of interest trial.add_circuit("circuit", circuit) trial.add_operator("obs", obs) # run exp_value = Estimator().run(circuit, obs, shots=shots).result().values.item() # track results of run trial.add_metric("exp_value", exp_value) local_storage.list() trials = local_storage.list() random_trial = trials[0] trial_uuid = random_trial.uuid local_storage.get(trial_uuid)
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. """Non-string identifiers for circuit and record identifiers test""" import unittest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestAnonymousIds(QiskitTestCase): """Test the anonymous use of registers.""" def test_create_anonymous_classical_register(self): """ClassicalRegister with no name.""" cr = ClassicalRegister(size=3) self.assertIsInstance(cr, ClassicalRegister) def test_create_anonymous_quantum_register(self): """QuantumRegister with no name.""" qr = QuantumRegister(size=3) self.assertIsInstance(qr, QuantumRegister) def test_create_anonymous_classical_registers(self): """Several ClassicalRegister with no name.""" cr1 = ClassicalRegister(size=3) cr2 = ClassicalRegister(size=3) self.assertNotEqual(cr1.name, cr2.name) def test_create_anonymous_quantum_registers(self): """Several QuantumRegister with no name.""" qr1 = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) self.assertNotEqual(qr1.name, qr2.name) def test_create_anonymous_mixed_registers(self): """Several Registers with no name.""" cr0 = ClassicalRegister(size=3) qr0 = QuantumRegister(size=3) # Get the current index count of the registers cr_index = int(cr0.name[1:]) qr_index = int(qr0.name[1:]) cr1 = ClassicalRegister(size=3) _ = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) # Check that the counters for each kind are incremented separately. cr_current = int(cr1.name[1:]) qr_current = int(qr2.name[1:]) self.assertEqual(cr_current, cr_index + 1) self.assertEqual(qr_current, qr_index + 2) def test_create_circuit_noname(self): """Create_circuit with no name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) qc = QuantumCircuit(qr, cr) self.assertIsInstance(qc, QuantumCircuit) class TestInvalidIds(QiskitTestCase): """Circuits and records with invalid IDs""" def test_invalid_type_circuit_name(self): """QuantumCircuit() with invalid type name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import torch from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 _ = torch.manual_seed(123456) # suppress output import numpy as np num_dim = 2 num_discrete_values = 8 num_qubits = num_dim * int(np.log2(num_discrete_values)) from scipy.stats import multivariate_normal coords = np.linspace(-2, 2, num_discrete_values) rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed) grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))]) prob_data = rv.pdf(grid_elements) prob_data = prob_data / np.sum(prob_data) import matplotlib.pyplot as plt from matplotlib import cm mesh_x, mesh_y = np.meshgrid(coords, coords) grid_shape = (num_discrete_values, num_discrete_values) fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"}) prob_grid = np.reshape(prob_data, grid_shape) surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 qc = QuantumCircuit(num_qubits) qc.h(qc.qubits) ansatz = EfficientSU2(num_qubits, reps=6) qc.compose(ansatz, inplace=True) qc.decompose().draw("mpl") qc.num_parameters from qiskit.primitives import Sampler shots = 10000 sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed}) from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks import SamplerQNN def create_generator() -> TorchConnector: qnn = SamplerQNN( circuit=qc, sampler=sampler, input_params=[], weight_params=qc.parameters, sparse=False, ) initial_weights = algorithm_globals.random.random(qc.num_parameters) return TorchConnector(qnn, initial_weights) from torch import nn class Discriminator(nn.Module): def __init__(self, input_size): super(Discriminator, self).__init__() self.linear_input = nn.Linear(input_size, 20) self.leaky_relu = nn.LeakyReLU(0.2) self.linear20 = nn.Linear(20, 1) self.sigmoid = nn.Sigmoid() def forward(self, input: torch.Tensor) -> torch.Tensor: x = self.linear_input(input) x = self.leaky_relu(x) x = self.linear20(x) x = self.sigmoid(x) return x generator = create_generator() discriminator = Discriminator(num_dim) def adversarial_loss(input, target, w): bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input) weighted_loss = w * bce_loss total_loss = -torch.sum(weighted_loss) return total_loss from torch.optim import Adam lr = 0.01 # learning rate b1 = 0.7 # first momentum parameter b2 = 0.999 # second momentum parameter generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005) discriminator_optimizer = Adam( discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005 ) from IPython.display import clear_output def plot_training_progress(): # we don't plot if we don't have enough data if len(generator_loss_values) < 2: return clear_output(wait=True) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9)) # Generator Loss ax1.set_title("Loss") ax1.plot(generator_loss_values, label="generator loss", color="royalblue") ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta") ax1.legend(loc="best") ax1.set_xlabel("Iteration") ax1.set_ylabel("Loss") ax1.grid() # Relative Entropy ax2.set_title("Relative entropy") ax2.plot(entropy_values) ax2.set_xlabel("Iteration") ax2.set_ylabel("Relative entropy") ax2.grid() plt.show() import time from scipy.stats import multivariate_normal, entropy n_epochs = 50 num_qnn_outputs = num_discrete_values**num_dim generator_loss_values = [] discriminator_loss_values = [] entropy_values = [] start = time.time() for epoch in range(n_epochs): valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float) fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float) # Configure input real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1) # Configure samples samples = torch.tensor(grid_elements, dtype=torch.float) disc_value = discriminator(samples) # Generate data gen_dist = generator(torch.tensor([])).reshape(-1, 1) # Train generator generator_optimizer.zero_grad() generator_loss = adversarial_loss(disc_value, valid, gen_dist) # store for plotting generator_loss_values.append(generator_loss.detach().item()) generator_loss.backward(retain_graph=True) generator_optimizer.step() # Train Discriminator discriminator_optimizer.zero_grad() real_loss = adversarial_loss(disc_value, valid, real_dist) fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach()) discriminator_loss = (real_loss + fake_loss) / 2 # Store for plotting discriminator_loss_values.append(discriminator_loss.detach().item()) discriminator_loss.backward() discriminator_optimizer.step() entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data) entropy_values.append(entropy_value) plot_training_progress() elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} sec") with torch.no_grad(): generated_probabilities = generator().numpy() fig = plt.figure(figsize=(18, 9)) # Generated CDF gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape) ax1 = fig.add_subplot(1, 3, 1, projection="3d") ax1.set_title("Generated CDF") ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax1.set_zlim(-0.05, 1.05) # Real CDF real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape) ax2 = fig.add_subplot(1, 3, 2, projection="3d") ax2.set_title("True CDF") ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax2.set_zlim(-0.05, 1.05) # Difference ax3 = fig.add_subplot(1, 3, 3, projection="3d") ax3.set_title("Difference between CDFs") ax3.plot_surface( mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm ) ax3.set_zlim(-0.05, 0.1) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/yaleqc/vqe-error-mitigation
yaleqc
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=4 max_qubits=15 #reference files are upto 12 Qubits only skip_qubits=2 max_circuits=3 num_shots=4092 gate_counts_plots = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute from qiskit.opflow import PauliTrotterEvolution, Suzuki from qiskit.opflow.primitive_ops import PauliSumOp import time,os,json import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "VQE Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits for display QC_ = None Hf_ = None CO_ = None ################### Circuit Definition ####################################### # Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz # param: n_spin_orbs - The number of spin orbitals. # return: return a Qiskit circuit for this VQE ansatz def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1): # number of alpha spin orbitals norb_a = int(n_spin_orbs / 2) # construct the Hamiltonian qubit_op = ReadHamiltonian(n_spin_orbs) # allocate qubits num_qubits = n_spin_orbs qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}") # initialize the HF state Hf = HartreeFock(num_qubits, na, nb) qc.append(Hf, qr) # form the list of single and double excitations excitationList = [] for occ_a in range(na): for vir_a in range(na, norb_a): excitationList.append((occ_a, vir_a)) for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_b, vir_b)) for occ_a in range(na): for vir_a in range(na, norb_a): for occ_b in range(norb_a, norb_a+nb): for vir_b in range(norb_a+nb, n_spin_orbs): excitationList.append((occ_a, vir_a, occ_b, vir_b)) # get cluster operators in Paulis pauli_list = readPauliExcitation(n_spin_orbs, circuit_id) # loop over the Pauli operators for index, PauliOp in enumerate(pauli_list): # get circuit for exp(-iP) cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index]) # add to ansatz qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)]) # method 1, only compute the last term in the Hamiltonian if method == 1: # last term in Hamiltonian qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits) # return the circuit return qc_with_mea # now we need to add the measurement parts to the circuit # circuit list qc_list = [] diag = [] off_diag = [] global normalization normalization = 0.0 # add the first non-identity term identity_qc = qc.copy() identity_qc.measure_all() qc_list.append(identity_qc) # add to circuit list diag.append(qubit_op[1]) normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms # loop over rest of terms for index, p in enumerate(qubit_op[2:]): # get the circuit with expectation measurements qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits) # accumulate normalization normalization += abs(p.coeffs[0]) # add to circuit list if non-diagonal if not is_diag: qc_list.append(qc_with_mea) else: diag_coeff += abs(p.coeffs[0]) # diagonal term if is_diag: diag.append(p) # off-diagonal term else: off_diag.append(p) # modify the name of diagonal circuit qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff)) normalization /= len(qc_list) return qc_list # Function that constructs the circuit for a given cluster operator def ClusterOperatorCircuit(pauli_op, excitationIndex): # compute exp(-iP) exp_ip = pauli_op.exp_i() # Trotter approximation qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip) # convert to circuit qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}' global CO_ if CO_ == None or qc.num_qubits <= 4: if qc.num_qubits < 7: CO_ = qc # return this circuit return qc # Function that adds expectation measurements to the raw circuits def ExpectationCircuit(qc, pauli, nqubit, method=2): # copy the unrotated circuit raw_qc = qc.copy() # whether this term is diagonal is_diag = True # primitive Pauli string PauliString = pauli.primitive.to_list()[0][0] # coefficient coeff = pauli.coeffs[0] # basis rotation for i, p in enumerate(PauliString): target_qubit = nqubit - i - 1 if (p == "X"): is_diag = False raw_qc.h(target_qubit) elif (p == "Y"): raw_qc.sdg(target_qubit) raw_qc.h(target_qubit) is_diag = False # perform measurements raw_qc.measure_all() # name of this circuit raw_qc.name = PauliString + " " + str(np.real(coeff)) # save circuit global QC_ if QC_ == None or nqubit <= 4: if nqubit < 7: QC_ = raw_qc return raw_qc, is_diag # Function that implements the Hartree-Fock state def HartreeFock(norb, na, nb): # initialize the quantum circuit qc = QuantumCircuit(norb, name="Hf") # alpha electrons for ia in range(na): qc.x(ia) # beta electrons for ib in range(nb): qc.x(ib+int(norb/2)) # Save smaller circuit global Hf_ if Hf_ == None or norb <= 4: if norb < 7: Hf_ = qc # return the circuit return qc ################ Helper Functions # Function that converts a list of single and double excitation operators to Pauli operators def readPauliExcitation(norb, circuit_id=0): # load pre-computed data filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt') with open(filename) as f: data = f.read() ansatz_dict = json.loads(data) # initialize Pauli list pauli_list = [] # current coefficients cur_coeff = 1e5 # current Pauli list cur_list = [] # loop over excitations for ext in ansatz_dict: if cur_coeff > 1e4: cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4: pauli_list.append(PauliSumOp.from_list(cur_list)) cur_coeff = ansatz_dict[ext] cur_list = [(ext, ansatz_dict[ext])] else: cur_list.append((ext, ansatz_dict[ext])) # add the last term pauli_list.append(PauliSumOp.from_list(cur_list)) # return Pauli list return pauli_list # Get the Hamiltonian by reading in pre-computed file def ReadHamiltonian(nqubit): # load pre-computed data filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt') with open(filename) as f: data = f.read() ham_dict = json.loads(data) # pauli list pauli_list = [] for p in ham_dict: pauli_list.append( (p, ham_dict[p]) ) # build Hamiltonian ham = PauliSumOp.from_list(pauli_list) # return Hamiltonian return ham # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(qc,references,num_qubits): # total circuit name (pauli string + coefficient) total_name = qc.name # pauli string pauli_string = total_name.split()[0] # get the correct measurement if (len(total_name.split()) == 2): correct_dist = references[pauli_string] else: circuit_id = int(total_name.split()[2]) correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"] return correct_dist,total_name # Max qubits must be 12 since the referenced files only go to 12 qubits MAX_QUBITS = 12 method = 1 def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2, max_circuits=max_circuits, num_shots=num_shots): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() max_qubits = max(max_qubits, min_qubits) # max must be >= min # validate parameters (smallest circuit is 4 qubits and largest is 10 qubits) max_qubits = min(max_qubits, MAX_QUBITS) min_qubits = min(max(4, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) if method == 2: max_circuits = 1 if max_qubits < 4: print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm") return global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for input_size in range(min_qubits, max_qubits + 1, skip_qubits): # reset random seed np.random.seed(0) # determine the number of circuits to execute for this group num_circuits = min(3, max_circuits) num_qubits = input_size fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # decides number of electrons na = int(num_qubits/4) nb = int(num_qubits/4) # random seed np.random.seed(0) numckts.append(num_circuits) # create the circuit for given qubit size and simulation parameters, store time metric ts = time.time() # circuit list qc_list = [] # Method 1 (default) if method == 1: # loop over circuits for circuit_id in range(num_circuits): # construct circuit qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method) qc_single.name = qc_single.name + " " + str(circuit_id) # add to list qc_list.append(qc_single) # method 2 elif method == 2: # construct all circuits qc_list = VQEEnergy(num_qubits, na, nb, 0, method) print(qc_list) print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}") for qc in qc_list: print("*********************************************") #print(f"qc of {qc} qubits for qc_list value: {qc_list}") # get circuit id if method == 1: circuit_id = qc.name.split()[2] else: circuit_id = qc.name.split()[0] #creation time creation_time = time.time() - ts creation_times.append(creation_time) #print(qc) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value print("operations: ",operations) algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() # load pre-computed data if len(qc.name.split()) == 2: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json') with open(filename) as f: references = json.load(f) else: filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json') with open(filename) as f: references = json.load(f) #Correct distribution to compare with counts correct_dist,total_name = analyzer(qc,references,num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) print(fidelity_dict) # modify fidelity based on the coefficient if (len(total_name.split()) == 2): fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization ) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!") print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!") return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
import scipy as sp import numpy as np import matplotlib.pyplot as plt import qiskit from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.providers.aer.noise import NoiseModel from qiskit.utils import QuantumInstance # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_obs(qc, shots, backend_name='ibmq_santiago'): """Helper function to get the expected value of the | 11 > state. """ # Get device noise model device = provider.get_backend(backend_name) noise_model = NoiseModel.from_backend(device) coupling_map = device.configuration().coupling_map seed = 42 # Define the backend backend = QuantumInstance( backend=Aer.get_backend("qasm_simulator"), seed_transpiler=seed, optimization_level=1, noise_model=noise_model, shots=shots, ) qc = qc.copy() qc.measure_all() counts = backend.execute(qc).get_counts() return counts['11']/shots qc = QuantumCircuit(2) qc.x(0) qc.cx(0, 1) qc.draw('mpl') run_obs(qc, 1000) def fold_cx(qc, alpha): """ Fold the cx on the circuit given an alpha value. """ d = qc.depth() k = np.ceil(d*(alpha - 1)/2) n = k//d s = k%d instructions = [] for instruction, qargs, cargs in qc: if instruction.name == 'cx': instruction = qiskit.circuit.library.CXGate() barrier = qiskit.circuit.library.Barrier(len(qc)) instructions.append((instruction, qargs, cargs)) instructions.append((barrier, qargs, cargs)) for _ in range(2*int(n + s)): instructions.append((instruction, qargs, cargs)) instructions.append((barrier, qargs, cargs)) else: instructions.append((instruction, qargs, cargs)) folded_qc = qc.copy() folded_qc.data = instructions return folded_qc alpha_list = [1, 2, 5, 7, 9, 11] folds = [] for alpha in alpha_list: folds.append(fold_cx(qc, alpha)) expected_vals = [] for i in range(len(alpha_list)): expected_vals.append(run_obs(folds[i], shots=1000)) print(f"Alphas: {alpha_list}\nExpected values{expected_vals}") plt.plot(alpha_list, expected_vals, 'o') plt.xlabel(r"$\alpha$", size=14) plt.ylabel(r"E($\alpha$)", size=14) plt.show() def linear(x, a, b): """Linear fit """ return a*x + b y = expected_vals x = alpha_list x, y = np.array(x), np.array(y) popt, _ = sp.optimize.curve_fit(linear, x, y) print("Mitigated expectation value:", np.round(popt[1],3)) print("Unmitigated expectation value:", expected_vals[0]) print("Absolute error with mitigation:", np.round(np.abs(1 - popt[1]), 3)) print("Absolute error without mitigation:", np.round(np.abs(1 - expected_vals[0]), 3)) plt.plot(alpha_list, expected_vals, 'o') plt.plot(0, popt[1], '*', label="mitigated") plt.xlabel(r"$\alpha$", size=14) plt.ylabel(r"E($\alpha$)", size=14) plt.legend() plt.show() import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Qiskit/qiskit-neko
Qiskit
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Qiskit Aer default backend plugin.""" import qiskit_aer as aer from qiskit_ibm_runtime import fake_provider from qiskit_neko import backend_plugin class AerBackendPlugin(backend_plugin.BackendPlugin): """A backend plugin for using qiskit-aer as the backend.""" def __init__(self): super().__init__() self.mock_provider = fake_provider.FakeProvider() self.mock_provider_backend_names = set() for backend in self.mock_provider.backends(): if backend.version == 1: self.mock_provider_backend_names.add(backend.name()) elif backend.version == 2: self.mock_provider_backend_names.add(backend.name) def get_backend(self, backend_selection=None): """Return the Backend object to run tests on. :param str backend_selection: An optional selection string to specify the backend object returned from this method. This can be used in two different ways. Either it can be used to specify a fake backend name from ``qiskit.test.mock`` in ``qiskit-terra`` such as ``fake_quito`` which will return that fake backend object or alternatively if the string starts with ``method=`` an ideal :class:`~qiskit.providers.aer.AerSimulator` object with that method will be set. If this is not specified a :class:`~qiskit.providers.aer.AerSimulator` will be returned with the defailt settings. :raises ValueError: If an invalid backend selection string is passed in """ if backend_selection is None: return aer.AerSimulator() if backend_selection.startswith("method="): method = backend_selection.split("=")[1] return aer.AerSimulator(method=method) if backend_selection in self.mock_provider_backend_names: return self.mock_provider.get_backend(backend_selection) raise ValueError(f"Invalid selection string {backend_selection}.")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import YouTubeVideo YouTubeVideo('BYKc2RnQMqo', width=858, height=540) !pip install qiskit --quiet !pip install qiskit-aer --quiet !pip install pylatexenc --quiet # @markdown ### **1. Import `Qiskit` and essential packages** { display-mode: "form" } from qiskit import QuantumCircuit, transpile, assemble from qiskit.circuit.library import QFT from qiskit_aer import AerSimulator from fractions import Fraction import random import sympy import math # @markdown ### **2. Controlled Modular Multiplication for $U(x) = a^x mod N$** { display-mode: "form" } class CtrlMultCircuit(QuantumCircuit): def __init__(self, a, binary_power, N): super().__init__(N.bit_length()) self.a = a self.power = 2 ** binary_power # Convert binary to decimal self.N = N self.name = f'{self.a}^{self.power} mod {self.N}' self._create_circuit() def _create_circuit(self): for dec_power in range(self.power): a_exp = self.a ** dec_power % self.N for i in range(self.num_qubits): if a_exp >> i & 1: self.x(i) for j in range(i + 1, self.num_qubits): if a_exp >> j & 1: self.swap(i, j) # @markdown ### **3. Quantum Phase Estimation with `Modular Exponentiation` and `Quantum Fourier Transform` to find period $r$** { display-mode: "form" } # @markdown ![](https://reneroliveira.github.io/quantum-shors-algorithm/images/shor_circuit.png) class QPECircuit(QuantumCircuit): def __init__(self, a, N): super().__init__(2 * N.bit_length(), N.bit_length()) self.a = a self.N = N self._create_circuit() def _modular_exponentiation(self): for qbit_idx in range(self.num_qubits // 2): self.append( CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(), [qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2)) ) def _create_circuit(self): self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits self.x(self.num_qubits - 1) self.barrier() self._modular_exponentiation() # Apply controlled modular exponentiation self.barrier() self.append( QFT(self.num_qubits // 2, inverse=True), range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits ) def collapse(self, simulator): self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2)) transpiled_circuit = transpile(self, simulator) self.collapse_result = simulator.run(transpiled_circuit, memory=True).result() return self.collapse_result # @markdown ### **4. Completed Shor's Algorithm for Integer Factorization** { display-mode: "form" } class ShorAlgorithm: def __init__(self, N, max_attempts=-1, random_coprime_only=False, simulator=None): self.N = N self.simulator = simulator self.max_attempts = max_attempts # -1 for all possible values of a self.random_coprime_only = random_coprime_only # True to select only coprime values of a and N def execute(self): is_N_invalid = self._is_N_invalid() if is_N_invalid: return is_N_invalid # Only coprime values remain if random_coprime_only is enabled, # Otherwise select a random integer in [2, N) as initial guess a_values = [a for a in range(2, self.N) if not self.random_coprime_only or (math.gcd(a, self.N) == 1)] print(f'[INFO] {len(a_values)} possible values of a: {a_values}') self.max_attempts = len(a_values) if self.max_attempts <= -1 else min(self.max_attempts, len(a_values)) attempts_count = 0 while attempts_count < self.max_attempts: print(f'\n===== Attempt {attempts_count + 1}/{self.max_attempts} =====') attempts_count += 1 self.chosen_a = random.choice(a_values) self.r = 1 print(f'[START] Chosen base a: {self.chosen_a}') if not self.random_coprime_only: gcd = math.gcd(self.chosen_a, self.N) if gcd != 1: print(f'=> {self.chosen_a} and {self.N} share common factor: {self.N} = {gcd} * {self.N // gcd}') return gcd, self.N // gcd print(f'>>> {self.chosen_a} and {self.N} are coprime => Perform Quantum Phase Estimation to find {self.chosen_a}^r - 1 = 0 (MOD {self.N})') if not self._quantum_period_finding(): a_values.remove(self.chosen_a) self.r = self.chosen_a = self.qpe_circuit = None continue factors = self._classical_postprocess() if factors: return factors a_values.remove(self.chosen_a) self.r = self.chosen_a = self.qpe_circuit = None print(f'[FAIL] No non-trivial factors found after {self.max_attempts} attempts.') def _is_N_invalid(self): if self.N <= 3: print('[ERR] N must be > 3') return 1, self.N if self.N % 2 == 0: print(f'=> {self.N} is an even number: {self.N} = 2 * {self.N // 2}') return 2, self.N // 2 if sympy.isprime(self.N): print(f'=> {self.N} is a prime number: {self.N} = 1 * {self.N}') return 1, self.N max_exponent = int(math.log2(self.N)) # Start with a large exponent and reduce for k in range(max_exponent, 1, -1): p = round(self.N ** (1 / k)) if p ** k == self.N: print(f'=> {self.N} is a power of prime: {self.N} = {p}^{k}') return p, k return False def _quantum_period_finding(self): while self.chosen_a ** self.r % self.N != 1: # QPE + continued fractions may find wrong r self.qpe_circuit = QPECircuit(self.chosen_a, self.N) # Find phase s/r result = self.qpe_circuit.collapse(self.simulator) state_bin = result.get_memory()[0] state_dec = int(state_bin, 2) # Convert to decimal bits_count = 2 ** (self.N.bit_length() - 1) phase = state_dec / bits_count # Continued fraction to find r self.r = Fraction(phase).limit_denominator(self.N).denominator # Get fraction that most closely approximates phase if self.r > self.N or self.r == 1: # Safety check to avoid infinite loops print(f'[ERR] Invalid period found: r = {self.r} => Retry with different a.') return False print(f'>>> Output State: |{state_bin}⟩ = {state_dec} (dec) => Phase = {state_dec} / {bits_count} = {phase:.3f}') return True def _classical_postprocess(self): # Classical postprocessing to find factors from the period print(f'>>> Found r = {self.r} => a^{{r/2}} ± 1 = {self.chosen_a:.0f}^{self.r/2:.0f} ± 1') if self.r % 2 != 0: print(f'[ERR] r = {self.r} is odd => Retry with different a.') return None int1, int2 = self.chosen_a ** (self.r // 2) - 1, self.chosen_a ** (self.r // 2) + 1 if int1 % self.N == 0 or int2 % self.N == 0: print(f'[ERR] {self.chosen_a}^{self.r/2:.0f} ± 1 is a multiple of {self.N} => Retry with different a.') return None factor1, factor2 = math.gcd(int1, self.N), math.gcd(int2, self.N) if factor1 not in [1, self.N] and factor2 not in [1, self.N]: # Check to see if factor is non-trivial print(f'[DONE] Successfully found non-trivial factors: {self.N} = {factor1} * {factor2}') return factor1, factor2 print(f'[FAIL] Trivial factors found: [1, {self.N}] => Retry with different a.') return None # @markdown ### **5. Run the Factorization** { display-mode: "form" } number_to_factor = 21 # @param {type:"slider", min: 15, max: 55, step: 1} max_attempts = -1 # @param {type:"slider", min:-1, max:100, step:10} random_coprime_only = False # @param {type:"boolean"} # @markdown ***Note**: `max_attempts` will be limited to number of available values. shor = ShorAlgorithm(number_to_factor, max_attempts, random_coprime_only, AerSimulator()) factors = shor.execute() try: display(shor.qpe_circuit.draw(output='mpl', fold=-1)) except Exception: pass
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import * from qiskit.tools.visualization import plot_histogram from IPython.display import display, Math, Latex def Decrement(n): U = QuantumCircuit(n) control = [x for x in range(n-1)] for k in range(n-1): U.x(control) U.mcx(control, control[-1]+1) U.x(control) control.pop() U.x(0) U = U.to_gate() U.name = 'Decrement' #ctl_U = U.control() make it a controlled gate return U n = 3 mc = QuantumCircuit(n, n) U = Decrement(n) mc.append(U, range(n)) mc.measure(range(n), range(n)) backend = BasicAer.get_backend('qasm_simulator') atp = 1024 res = execute(mc, backend=backend, shots=atp).result() ans = res.get_counts() mc.draw('mpl') plot_histogram(ans)
https://github.com/quantumyatra/quantum_computing
quantumyatra
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import plot_histogram, plot_bloch_multivector import numpy as np import pylab as plt def NOT(input_bit): # initialize the QC q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) # for input 1 flip the q[0] to 1 if input_bit=='1': qc.x(q[0]) # now do a NOT gate by flipping the q[0] qc.x(q[0]) qc.measure( q[0], c[0] ) # now exectue the circuit backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend,shots=1000).result().get_counts() return counts NOT('1') def XOR(input1, input2): # initialize the QC q = QuantumRegister(2) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) #################################### # # DO something here... # the code in the book doesn't do anything # so it gives 0 always irrespective of the inputs #################################### qc.measure( q[1], c[0] ) # now exectue the circuit backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend,shots=1000, memory=True).result().get_memory()[0] return counts XOR('1', '1') def AND(input1, input2): # initialize the QC q = QuantumRegister(3) c = ClassicalRegister(1) qc = QuantumCircuit(q,c) #################################### # # DO something here... # the code in the book only gives 0 always #################################### qc.measure( q[2], c[0] ) # now exectue the circuit backend = Aer.get_backend('qasm_simulator') counts = execute(qc,backend,shots=1000, memory=True).result().get_memory()[0] return counts XOR('1', '1') def AND(input1,input2): q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output
https://github.com/abbarreto/qiskit3
abbarreto
%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/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import IBMQ from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import TruthTableOracle IBMQ.enable_account('ENTER API KEY HERE') provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_qasm_simulator') expression = '11000001' oracle = TruthTableOracle(expression) print(oracle) grover = Grover(oracle) result = grover.run(backend, shots=1024) counts = result['measurement'] print('\nTruth tables with Grovers Search') print('--------------------------------\n') print('Bit string is ', expression) print('\nResults ',counts) print('\nPress any key to close') input()
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from transpile_benchy.metrics.gate_counts import ( DepthMetric, TotalMetric, TotalSwaps, ) from qiskit.circuit.library import iSwapGate from qiskit.transpiler import CouplingMap from mirror_gates.pass_managers import Mirage, QiskitLevel3 from mirror_gates.utilities import SubsMetric from mirror_gates.logging import transpile_benchy_logger N = 8 coupling_map = CouplingMap.from_line(N) # coupling_map = CouplingMap.from_heavy_hex(5) from transpile_benchy.library import CircuitLibrary library = CircuitLibrary.from_txt("../../../circuits/twolocal.txt") # XXX set consolidate to False # this is allowed only because my pass manager will preserve consolidation # see post_stage, I call fastconsolidate manually # NOTE: use TotalSwaps to verify baselines have > 0 swaps # otherwise, there is no room for improvement. # we can include these if we want to show our methods will still work # but somewhat trivial since we just append VF2Layout metrics = [ DepthMetric(consolidate=False), TotalMetric(consolidate=False), TotalSwaps(consolidate=False), SubsMetric(), ] transpilers = [ QiskitLevel3(coupling_map, cx_basis=True), Mirage( coupling_map, logger=transpile_benchy_logger, cx_basis=True, ), QiskitLevel3(coupling_map, cx_basis=False), Mirage( coupling_map, logger=transpile_benchy_logger, cx_basis=False, ), ] from transpile_benchy.benchmark import Benchmark benchmark = Benchmark( transpilers=transpilers, circuit_library=library, metrics=metrics, logger=transpile_benchy_logger, num_runs=3, ) benchmark.run() # print(benchmark) print(benchmark) benchmark.summary_statistics(transpilers[0], transpilers[1]) from transpile_benchy.render import plot_benchmark plot_benchmark( benchmark, save=1, legend_show=1, filename="twolocal", color_override=[6, 9, 0, 3], fixed_bar_width=3, )
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import logging from itertools import product import networkx as nx import matplotlib.pyplot as plt from qiskit import IBMQ, QuantumCircuit, execute, transpile from qiskit.test.mock import FakeMumbai as FakeDevice from qiskit.providers.aer.noise import NoiseModel from qiskit.visualization import plot_histogram logging.getLogger().setLevel(logging.INFO) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') device = FakeDevice() noise_model = NoiseModel.from_backend(device) conf = device.configuration() print(conf.basis_gates) G = nx.Graph() G.add_nodes_from(range(0,conf.n_qubits)) G.add_edges_from(conf.coupling_map) pos = nx.kamada_kawai_layout(G) nx.draw_networkx(G, pos, with_labels = True) simBackends = provider.backends(filters=lambda x: x.configuration().n_qubits >= conf.n_qubits and x.configuration().simulator and x.status().operational==True and all(basis_gate in x.configuration().basis_gates for basis_gate in conf.basis_gates if basis_gate!="reset")) # we exclude reset because this is not physically implemented yet simBackends n_entangled = 4 n_pairs = 5 n_qubits = n_entangled * n_pairs qc = QuantumCircuit(n_qubits, n_qubits) qubits_in_superpos = [i for i in range(0,n_qubits, n_entangled)] qubits_to_entangle = {i:[i + j for j in range(1, n_entangled)] for i in qubits_in_superpos} for control in qubits_in_superpos: qc.h(control) for target in qubits_to_entangle[control]: qc.cx(control, target) qc.measure_all() qc.draw(output='mpl') circuit_transpiled = transpile(qc, backend=device, optimization_level=3) circuit_transpiled.draw(output='mpl') bell_states = [x * n_entangled for x in ["0", "1"]] possible_states = ["".join(state) for state in product(bell_states, repeat=n_pairs)] possible_states backend = provider.get_backend('simulator_statevector') shots = 4096 result = execute(qc, backend, shots=shots, coupling_map=conf.coupling_map, basis_gates=conf.basis_gates, noise_model=noise_model).result() # took about 2 hours for problem with 26 qubits counts = result.get_counts(0) noise_ct = 0 for measurement, count in counts.items(): measurement = measurement[:n_qubits] # drop ancillary qubits if measurement in possible_states: print(f"{measurement=} : {count=}") else: noise_ct = noise_ct + count print(f"{noise_ct=} valid states: {100 * (shots - noise_ct) / shots : 0.2f}%")
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from crypto.six_state.participant import Participant from qiskit import QuantumCircuit ## The Sender entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Sender(Participant): ## Constructor def __init__(self, name='', original_bits_size=0): super().__init__(name, original_bits_size) ## Encode the message (values) using a quantum circuit def encode_quantum_message(self): encoded_message = [] for i in range(len(self.axes)): qc = QuantumCircuit(1, 1) if self.values[i] == 1: qc.x(0) if self.axes[i] == 1: qc.h(0) elif self.axes[i] == 2: qc.append(self.hy, [0]) encoded_message.append(qc) return encoded_message
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, 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 the MergeAdjacentBarriers pass""" import random import unittest from qiskit.transpiler.passes import MergeAdjacentBarriers from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestMergeAdjacentBarriers(QiskitTestCase): """Test the MergeAdjacentBarriers pass""" def test_two_identical_barriers(self): """Merges two barriers that are identical into one ░ ░ ░ q_0: |0>─░──░─ -> q_0: |0>─░─ ░ ░ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_numerous_identical_barriers(self): """Merges 5 identical barriers in a row into one ░ ░ ░ ░ ░ ░ ░ q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─ ░ ░ ░ ░ ░ ░ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_of_different_sizes(self): """Test two barriers of different sizes are merged into one ░ ░ ░ q_0: |0>─░──░─ q_0: |0>─░─ ░ ░ -> ░ q_1: |0>────░─ q_1: |0>─░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_not_overlapping_barriers(self): """Test two barriers with no overlap are not merged (NB in these pictures they look like 1 barrier but they are actually 2 distinct barriers, this is just how the text drawer draws them) ░ ░ q_0: |0>─░─ q_0: |0>─░─ ░ -> ░ q_1: |0>─░─ q_1: |0>─░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.barrier(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_before(self): """Test with an obstacle before the larger barrier ░ ░ ░ q_0: |0>──░───░─ q_0: |0>──────░─ ┌───┐ ░ -> ┌───┐ ░ q_1: |0>┤ H ├─░─ q_1: |0>┤ H ├─░─ └───┘ ░ └───┘ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.h(qr[1]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_obstacle_after(self): """Test with an obstacle after the larger barrier ░ ░ ░ q_0: |0>─░───░── q_0: |0>─░────── ░ ┌───┐ -> ░ ┌───┐ q_1: |0>─░─┤ H ├ q_1: |0>─░─┤ H ├ ░ └───┘ ░ └───┘ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.barrier(qr[0]) circuit.h(qr[1]) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[1]) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ -> q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ ░ └───┘ ░ """ qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_long(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ -> ░ └───┘ ░ q_1: |0>─────────░─ q_1: |0>─────────░─ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr[0]) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_narrow(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ┌───┐ ░ ░ ┌───┐ ░ q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─ ░ └───┘ ░ -> ░ └───┘ ░ q_1: |0>─░───────░─ q_1: |0>─░───────░─ ░ ░ ░ ░ """ qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.barrier(qr) circuit.h(qr[0]) circuit.barrier(qr) expected = QuantumCircuit(qr) expected.barrier(qr) expected.h(qr[0]) expected.barrier(qr) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_barriers_with_blocking_obstacle_twoQ(self): """Test that barriers don't merge if there is an obstacle that is blocking ░ ░ ░ ░ q_0: |0>─░───────░─ q_0: |0>─░───────░─ ░ ░ ░ ░ q_1: |0>─░───■───── -> q_1: |0>─░───■───── ░ ┌─┴─┐ ░ ░ ┌─┴─┐ ░ q_2: |0>───┤ X ├─░─ q_2: |0>───┤ X ├─░─ └───┘ ░ └───┘ ░ """ qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.barrier(0, 1) circuit.cx(1, 2) circuit.barrier(0, 2) expected = QuantumCircuit(qr) expected.barrier(0, 1) expected.cx(1, 2) expected.barrier(0, 2) pass_ = MergeAdjacentBarriers() result = pass_.run(circuit_to_dag(circuit)) self.assertEqual(result, circuit_to_dag(expected)) def test_output_deterministic(self): """Test that the output barriers have a deterministic ordering (independent of PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations through the circuit are also deterministic; it's in general not possible for all transpiler passes to produce identical outputs across all valid topological orderings, especially if those passes have some stochastic element.""" order = list(range(20)) random.Random(2023_02_10).shuffle(order) circuit = QuantumCircuit(20) circuit.barrier([5, 2, 3]) circuit.barrier([7, 11, 14, 2, 4]) circuit.barrier(order) # All the barriers should get merged together. expected = QuantumCircuit(20) expected.barrier(range(20)) output = MergeAdjacentBarriers()(circuit) self.assertEqual(expected, output) # This assertion is that the ordering of the arguments in the barrier is fixed. self.assertEqual(list(output.data[0].qubits), list(output.qubits)) if __name__ == "__main__": unittest.main()
https://github.com/NesyaLab/qaoa
NesyaLab
import warnings warnings.filterwarnings('ignore') import os path = os.getcwd() os.chdir(os.path.dirname(path)) from classes import Problems instance = Problems.Problems(verbose=True) instance.get_draw() print(instance.G == instance.get_graph()) print(instance.get_graph()) print(instance.G.nodes == instance.get_nodes()) print(instance.get_nodes()) print(instance.G.edges == instance.get_edges()) print(instance.get_edges()) print(instance.G.number_of_nodes() == instance.get_number_of_nodes()) print(instance.get_number_of_nodes()) print(instance.G.number_of_edges() == instance.get_number_of_edges()) print(instance.get_number_of_edges()) import networkx print((networkx.to_numpy_array(instance.G) == instance.get_adjacency_matrix()).all()) print(instance.get_adjacency_matrix()) print(instance.get_adjacency_spectrum()) print(instance.get_laplacian()) print(instance.get_laplacian_spectrum()) print(instance.get_adjacency_dict()) from classes import Qaoa p = 1 G = instance qaoa = Qaoa.Qaoa(p, G) gamma = 0 cost = qaoa.cost_operator(gamma) print(cost) beta = 0 mixer = qaoa.x_mixer_operator(beta) print(mixer) beta = 0 mixer = qaoa.xx_mixer_operator(beta) print(mixer) beta = 0 mixer = qaoa.y_mixer_operator(beta) print(mixer) beta = 0 mixer = qaoa.yy_mixer_operator(beta) print(mixer) phi = 0 psi = 2 mixer = qaoa.xy_mixer_operator(phi, psi) print(mixer) circuit = qaoa.get_circuit() print(circuit)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Contains functions used by the basic provider simulators. """ from __future__ import annotations from string import ascii_uppercase, ascii_lowercase import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = { "U": gates.UGate, "u": gates.UGate, "u1": gates.U1Gate, "u2": gates.U2Gate, "u3": gates.U3Gate, "h": gates.HGate, "p": gates.PhaseGate, "s": gates.SGate, "sdg": gates.SdgGate, "sx": gates.SXGate, "sxdg": gates.SXdgGate, "t": gates.TGate, "tdg": gates.TdgGate, "x": gates.XGate, "y": gates.YGate, "z": gates.ZGate, "id": gates.IGate, "i": gates.IGate, "r": gates.RGate, "rx": gates.RXGate, "ry": gates.RYGate, "rz": gates.RZGate, } def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarray: """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate in SINGLE_QUBIT_GATES: gc = SINGLE_QUBIT_GATES[gate] else: raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) return gc(*params).to_matrix() # Two qubit gates WITHOUT parameters: name -> matrix TWO_QUBIT_GATES = { "CX": gates.CXGate().to_matrix(), "cx": gates.CXGate().to_matrix(), "ecr": gates.ECRGate().to_matrix(), "cy": gates.CYGate().to_matrix(), "cz": gates.CZGate().to_matrix(), "swap": gates.SwapGate().to_matrix(), "iswap": gates.iSwapGate().to_matrix(), "ch": gates.CHGate().to_matrix(), "cs": gates.CSGate().to_matrix(), "csdg": gates.CSdgGate().to_matrix(), "csx": gates.CSXGate().to_matrix(), "dcx": gates.DCXGate().to_matrix(), } # Two qubit gates WITH parameters: name -> class TWO_QUBIT_GATES_WITH_PARAMETERS = { "cp": gates.CPhaseGate, "crx": gates.CRXGate, "cry": gates.CRYGate, "crz": gates.CRZGate, "cu": gates.CUGate, "cu1": gates.CU1Gate, "cu3": gates.CU3Gate, "rxx": gates.RXXGate, "ryy": gates.RYYGate, "rzz": gates.RZZGate, "rzx": gates.RZXGate, "xx_minus_yy": gates.XXMinusYYGate, "xx_plus_yy": gates.XXPlusYYGate, } # Three qubit gates: name -> matrix THREE_QUBIT_GATES = { "ccx": gates.CCXGate().to_matrix(), "ccz": gates.CCZGate().to_matrix(), "rccx": gates.RCCXGate().to_matrix(), "cswap": gates.CSwapGate().to_matrix(), } def einsum_matmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}{tens_r}->{tens_lout}{tens_r}" def einsum_vecmul_index(gate_indices: list[int], number_of_qubits: int) -> str: """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, {tens_lin}->{tens_lout}" def _einsum_matmul_index_helper( gate_indices: list[int], number_of_qubits: int ) -> tuple[str, str, str, str]: """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
JessicaJohnBritto
# initialization import numpy as np import matplotlib # importing Qiskit from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram style = {'backgroundcolor': 'lightyellow'} # Style of the circuits # set the length of the n-bit input string. n = 3 # set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw(output='mpl', style=style) balanced_oracle = QuantumCircuit(n+1) b_str = "101" balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw(output='mpl', style=style) balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() balanced_oracle.draw(output='mpl', style=style) balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw(output='mpl', style=style) dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw(output='mpl', style=style) dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw(output='mpl', style=style) dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw(output='mpl', style=style) # use local simulator aer_sim = Aer.get_backend('aer_simulator') qobj = assemble(dj_circuit, aer_sim) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) print(b) print(str(n)) b=7 # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') print(b_str) # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw(output='mpl', style=style) transpiled_dj_circuit = transpile(dj_circuit, aer_sim) qobj = assemble(transpiled_dj_circuit) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
# Importando módulos from qiskit import * from qiskit.tools.visualization import plot_histogram # Inicializando o circuito nQubits = 2 nBits = 2 circuitoQuantico = QuantumCircuit(nQubits, nBits) # Para aplicar uma porta no circuito devemos seguir o seguinte exemplo onde aplicamos uma Hadamard Gate circuitoQuantico.h(0) # Nesse exemplo h() é a função que usamos para aplicar uma Hadamard Gate e o argumento é o índice do qubit # onde se deseja aplica a porta # Podemos ver ao chamar draw() que a Hadamard Gate fica no qubit desejado circuitoQuantico.draw(output = 'mpl') # Podemos aplicar também portas que envolvem mais de um qubit, como a CNOT(Controlled NOT) Gate circuitoQuantico.cx(0,1) # Visualização do circuito após chamar a CNOT Gate circuitoQuantico.draw(output = 'mpl') # Agora podemos medir esses qubits após as operações chamando measure() circuitoQuantico.measure(0,0) circuitoQuantico.measure(1,1) # Visualização do circuito após chamar measure() circuitoQuantico.draw(output = 'mpl') # Para simular um circuito quântico usamos um elemento do Qiskit chamado Aer, que tem como # uma de suas funções a simulação de circuitos simulador = Aer.get_backend('qasm_simulator') # Para executar o circuito chamamos execute() que leva como argumento o circuito a ser executado e o # backend(aonde o circuito vai ser executado) que nesse caso é no simulador do Aer resultado = execute(circuitoQuantico, backend = simulador).result() # Usamos a variável resultado para guardar os dados do resultado # Para exibir os resultados chamamos plot_histogram() plot_histogram(resultado.get_counts(circuitoQuantico)) # Antes de tudo é necessário importar o módulo da IBMQ Experience e carregar a sua conta from qiskit import IBMQ IBMQ.load_account() # Agora precisamos inicializar a variável de provider que vai ser responsável por ter o acesso a # um dos computadores quanticos da IBM provedor = IBMQ.get_provider('ibm-q') # Podemos agora escolher um dos computadores disponíveis da IBM para podermos rodar nosso circuito computadorQuantico = provedor.get_backend('ibmq_16_melbourne') # Para simular no nosso próprio computado tivemos que usar # " execute(circuitoQuantico, backend = simulador) " # Agora vamos ter que fazer algo similar executar = execute(circuitoQuantico, backend=computadorQuantico) # Depois de rodar o comando " execute(circuitoQuantico, backend=computadorQuantico).result() " # o nosso circuito entra numa fila do computador da IBM que escolhemos roda. Como se fosse uma # lista de pedidos num restaurante para o cozinheiro preparar. # Podemos checar o status do nosso "pedido" chamando o job_monitor from qiskit.tools.monitor import job_monitor job_monitor(executar) # Para pegar o resultado do circuito fazemos o seguinte resultado = executar.result() # Da mesma forma como na simulação no próprio computador podemos exibir os resultados num histograma plot_histogram(resultado.get_counts(circuitoQuantico))
https://github.com/matheusmtta/Quantum-Machine-Learning
matheusmtta
import numpy as np import pennylane as qml from pennylane.optimize import NesterovMomentumOptimizer n = 6 backend = qml.device("default.qubit", wires = n) def layerBlock(wgt): for q_i in range(n): qml.Rot(wgt[q_i, 0], wgt[q_i, 1], wgt[q_i, 2], wires = q_i) for q_i in range(n): qml.CNOT(wires = [q_i, (q_i+1)%n]) def preparation(x_n): qb = [i for i in range(n)] qml.BasisState(x_n, wires=qb) @qml.qnode(backend) def circuit(weights, x_n = None): preparation(x_n) for w in weights: layerBlock(w) return qml.expval(qml.PauliZ(0)) def variationalCircuit(param, x_n = None): weights = param[0] bias = param[1] return circuit(weights, x_n = x_n) + bias def squareLoss(target, predictions): loss = 0 for l, p in zip(target, predictions): loss += (l - p) ** 2 loss /= len(target) return loss def accuracy(target, predictions): loss = 0 for l, p in zip(target, predictions): if abs(l - p) < 1e-5: loss += 1 loss /= len(target) return loss def cost(param, x_n, y_n): predictions = [variationalCircuit(param, x_n = x) for x in x_n] return squareLoss(y_n, predictions) data = np.loadtxt("data/dataset1.txt") dataset = data[:, :n] target = data[:, n] #maps {0, 1} -> {-1, 1} target = target * 2 - np.ones(len(target)) np.random.seed(0) blocks = 3 m = 4 initialParams = (0.01 * np.random.randn(blocks, n, m), 0.0) optimizer = NesterovMomentumOptimizer(0.5) batchSize = 5 params = initialParams steps = 15 for i in range(steps): batchIdx = np.random.randint(0, len(dataset), (batchSize,)) batchX = dataset[batchIdx] batchY = target[batchIdx] params = optimizer.step(lambda f :cost(f, batchX, batchY), params) predictions = [np.sign(variationalCircuit(params, x)) for x in dataset] acc = accuracy(target, predictions) print( "Step: {:5d} | Cost: {:0.7f} | Accuracy: {:0.7f} ".format( i + 1, cost(params, dataset, target), acc ) )
https://github.com/goodrahstar/hello-quantum-world
goodrahstar
pip install pylatexenc !pip install qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector from qiskit.visualization import plot_histogram # Create a Quantum Register called "qr" with 2 qubits. qr = QuantumRegister(2,'qr') # Create a Classical Register called "cr" with 2 bits. cr = ClassicalRegister(2,'cr') qc = QuantumCircuit(qr,cr) # Add the H gate in the Qubit 1, putting this qubit in superposition. qc.h(qr[1]) # Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement qc.cx(qr[1], qr[0]) # Add a Measure gate to see the state. qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) # Compile and execute the Quantum Program in the ibmqx5 qc.draw(output='mpl') qasm_simulator = Aer.get_backend('qasm_simulator') shots = 1024 result = results = execute(qc, backend=qasm_simulator, shots=shots).result() Ans=result.get_counts() plot_histogram(Ans)
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.x(0) qc.y(0) qc.draw('mpl') from qiskit.visualization import visualize_transition visualize_transition(qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw()
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
rodneyosodo
# Basis encoding example with PennyLane import pandas as pd import pennylane as qml from pennylane import numpy as np # import the template from pennylane.templates.layers import StronglyEntanglingLayers from sklearn.utils import shuffle from sklearn.preprocessing import normalize from pennylane.templates.embeddings import AngleEmbedding, BasisEmbedding, AmplitudeEmbedding, DisplacementEmbedding from pennylane.init import strong_ent_layers_uniform np.random.seed(42) # Constants DATA_PATH = "../../Data/Processed/data.csv" num_qubits = 4 data = pd.read_csv(DATA_PATH) X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values # normalize the data X = normalize(X) print(X[:5]) device = qml.device("default.qubit", wires=num_qubits) @qml.qnode(device) def circuit(data): for i in range(num_qubits): # Create superposition qml.Hadamard(wires=i) AngleEmbedding(features=data, wires=range(num_qubits), rotation="Y") return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3)) circuit(X[0])
https://github.com/jmamczynska/QiskitLabs
jmamczynska
from qiskit import * from qiskit.visualization import plot_histogram from qiskit.visualization import plot_state_qsphere, plot_bloch_vector from qiskit.quantum_info import Statevector import numpy as np sim = Aer.get_backend('aer_simulator') qr = QuantumRegister(3) qc_3qx = QuantumCircuit(qr) ### your code goes here. ### qc_3qx.h(0) qc_3qx.s(0) qc_3qx.cx(0,1) qc_3qx.cx(0,2) ####### qc_3qx.draw('mpl') from qiskit.visualization import array_to_latex state_ve = Statevector.from_instruction(qc_3qx) array_to_latex(state_ve) ### your code goes here ### state_ve = Statevector.from_instruction(qc_3qx) plot_state_qsphere(state_ve) def apply_err(n, err): qc = QuantumCircuit(int(n), name='Error') which_qubit = np.random.randint(n) if err=='bit': qc.x(which_qubit) elif err=='phase': qc.z(which_qubit) else: pass err = qc.to_gate() return err, which_qubit err, which_qubit = apply_err(3, 'bit') print('Error applied to qubit: ', which_qubit) qc_3qx.append(err,range(3)) qc_3qx.draw('mpl') # Execute this cell to add the extra registers k = int(input('number of auxiliary qubits ( / syndrome bits): ')) ar = QuantumRegister(k, 'auxiliary') cr = ClassicalRegister(k, 'syndrome') qc_3qx.add_register(ar) qc_3qx.add_register(cr) # Apply the parity check gates and measure the parities on the syndrome bits to localize a single bit-flip ( X ) error on the code. ### your code goes here. ### qc_3qx.draw('mpl') qc_3qx.cx(qr[0], ar[0]) qc_3qx.cx(qr[1], ar[0]) qc_3qx.cx(qr[1], ar[1]) qc_3qx.cx(qr[2], ar[1]) qc_3qx.barrier() qc_3qx.measure(ar, cr) ###### qc_3qx.draw('mpl') #### complete the dictionary ### table_syndrome = {'00': 'I[0]I[1]I[2]', '01':'I[0]I[1]X[2]', '10': 'X[0]I[1]I[2]', '11':'I[0]X[1]I[2]'} ###### print(table_syndrome) qc_3qx_trans = transpile(qc_3qx, sim) syndrome = sim.run(qc_3qx_trans, shots=1, memory=True).result().get_memory() print(syndrome) your_answer = input('Enter the index of the code qubit that underwent bit-flip error: ') print('\n') print(which_qubit == int(your_answer)) ### your code goes here ### def get_logical_x(): qr_xl = QuantumRegister(3, 'qubit') ar_xl = QuantumRegister(2, 'auxiliary') sr_xl = ClassicalRegister(2, 'syndrome') qc_xl = QuantumCircuit(qr_xl, ar_xl, sr_xl) qc_xl.x(range(3)) qc_xl.cx([qr_xl[0], qr_xl[1]], [ar_xl[0], ar_xl[0]]) qc_xl.cx([qr_xl[1], qr_xl[2]], [ar_xl[1], ar_xl[1]]) qc_xl.barrier() qc_xl.measure(ar_xl, sr_xl) # correct errors qc_xl.x(qr_xl[2]).c_if(sr_xl, 2) qc_xl.x(qr_xl[0]).c_if(sr_xl, 1) qc_xl.x(qr_xl[1]).c_if(sr_xl, 3) return qc_xl logical_x = get_logical_x() bits_out = sim.run(logical_x, shots=1, memory=True).result().get_memory() print(bits_out) logical_x.draw('mpl') from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram aer_sim = Aer.get_backend('aer_simulator') def get_noise(p_gate): error_gate1 = depolarizing_error(p_gate, 1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_gate1, ["x"]) # single qubit gate error is applied to x gates return noise_model noise_model = get_noise(0.01) qr = QuantumRegister(3, 'qubit') ar = QuantumRegister(2, 'auxiliary') sr = ClassicalRegister(2, 'syndrome') cr = ClassicalRegister(3, 'measure') qc_000 = QuantumCircuit(qr, ar, sr, cr) qc_000 = qc_000.compose(logical_x) qc_000.barrier() qc_000.measure(qr, cr) qc_000.draw('mpl') # run the circuit with the noise model and extract the counts qobj = assemble(qc_000) counts = aer_sim.run(qobj, noise_model=noise_model).result().get_counts() plot_histogram(counts) qc_3qz = QuantumCircuit(3) ### your code goes here. ### ######## qc_3qz.draw('mpl') err, which_qubit = apply_err(3, 'phase') qc_3qz.append(err, range(3)) ### your code goes here ### ########## qc_3qz.draw('mpl') qc_3qz_trans = transpile(qc_3qz, sim) syndrome = sim.run(qc_3qz_trans, shots=1, memory=True).result().get_memory() print(syndrome) your_answer = input('Enter the index of the code qubit that underwent phase-flip error: ') print('\n') print(which_qubit == int(your_answer)) ## Your answer goes here t = int(input('The number of counting qubit: ')) qc0 = QuantumCircuit(t+3, 1) qc0.h(-1) qc0.barrier() ## your code goes here ## ###### qc0.measure(0, 0) qc0.draw('mpl') counts_qc0 = sim.run(qc0, shots=8192).result().get_counts() plot_histogram(counts_qc0) qc1 = QuantumCircuit(t+3, 1) qc1.h(-1) qc1.barrier() ## your code goes here ## ###### qc1.measure(0, 0) qc1.draw('mpl') counts_qc1 = sim.run(qc1, shots=8192).result().get_counts() plot_histogram(counts_qc1)
https://github.com/a24l/IBM_Qiskit_QGSS
a24l
# General Imports import numpy as np # Visualisation Imports import matplotlib.pyplot as plt # Scikit Imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler # Qiskit Imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load digits dataset digits = datasets.load_digits(n_class=2) # Plot example '0' and '1' fig, axs = plt.subplots(1, 2, figsize=(6,3)) axs[0].set_axis_off() axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest') axs[1].set_axis_off() axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Reduce dimensions n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 100 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] label_test = label_test[:test_size] print(sample_train[0], label_train[0]) print(sample_test[0], label_test[0]) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.draw('mpl') # 3 features, depth 1 map_zz = ZZFeatureMap(feature_dimension=3, reps=1) map_zz.draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.draw('mpl') def custom_data_map_func(x): coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x)) return coeff map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'], data_map_func=custom_data_map_func) #map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.draw('mpl') # rotation block: rot = QuantumCircuit(2) params = ParameterVector('r', 2) rot.ry(params[0], 0) rot.rz(params[1], 1) # entanglement block: ent = QuantumCircuit(4) params = ParameterVector('e', 3) ent.crx(params[0], 0, 1) ent.crx(params[1], 1, 2) ent.crx(params[2], 2, 3) nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent, entanglement='linear', insert_barriers=True) nlocal.draw('mpl') qubits = 3 repeats = 2 x = ParameterVector('x', length=qubits) var_custom = QuantumCircuit(qubits) for _ in range(repeats): for i in range(qubits): var_custom.rx(x[i], i) for i in range(qubits): for j in range(i + 1, qubits): var_custom.cx(i, j) var_custom.p(x[i] * x[j], j) var_custom.cx(i, j) var_custom.barrier() var_custom.draw('mpl') print(sample_train[0]) encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.draw(output='mpl') x = [-0.1,0.2] encode_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True, data_map_func = None ) encode_circuit = encode_map.bind_parameters(x) encode_circuit.draw(output='mpl') # YOUR CODE HERE from qc_grader import grade_lab3_ex1 # Note that the grading function is expecting a quantum circuit grade_lab3_ex1(encode_circuit) zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() x = [-0.1,0.2] y = [0.4,-0.6] # YOUR CODE HERE fmap = ZZFeatureMap(feature_dimension = 2, reps = 4, insert_barriers = True) zz_kernel = QuantumKernel(feature_map = fmap, quantum_instance = Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x,y) backend = Aer.get_backend("qasm_simulator") job = execute(zz_circuit,backend,seed_simulator=1024, seed_transpiler = 1024, shots = 8192) result = job.result().get_counts(zz_circuit) amplitude = result['00']/sum(result.values()) print(result,"amplitude:",amplitude) zz_circuit.decompose().decompose().draw('mpl') from qc_grader import grade_lab3_ex2 # Note that the grading function is expecting a floating point number grade_lab3_ex2(amplitude) zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, label_train) zzpc_score = zzpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(sample_train, label_train) zzcb_score = zzcb_svc.score(sample_test, label_test) print(f'Callable kernel classification test score: {zzcb_score}') classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid'] for kernel in classical_kernels: classical_svc = SVC(kernel=kernel) classical_svc.fit(sample_train, label_train) classical_score = classical_svc.score(sample_test, label_test) print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit import Aer from qiskit_aqua.input import SVMInput from qiskit_aqua import run_algorithm, QuantumInstance from qiskit_aqua.algorithms import QSVMVariational from qiskit_aqua.components.optimizers import SPSA from qiskit_aqua.components.feature_maps import SecondOrderExpansion from qiskit_aqua.components.variational_forms import RYRZ feature_dim = 2 # dimension of each data point training_dataset_size = 20 testing_dataset_size = 10 random_seed = 10598 shots = 1024 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, n=feature_dim, gap=0.3, PLOT_DATA=True) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) params = { 'problem': {'name': 'svm_classification', 'random_seed': 10598}, 'algorithm': {'name': 'QSVM.Variational', 'override_SPSA_params': True}, 'backend': {'shots': 1024}, 'optimizer': {'name': 'SPSA', 'max_trials': 200, 'save_steps': 1}, 'variational_form': {'name': 'RYRZ', 'depth': 3}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2} } svm_input = SVMInput(training_input, test_input, datapoints[0]) backend = Aer.get_backend('qasm_simulator') result = run_algorithm(params, svm_input, backend=backend) print("testing success ratio: ", result['testing_accuracy']) print("predicted classes:", result['predicted_classes']) backend = Aer.get_backend('qasm_simulator') optimizer = SPSA(max_trials=100, c0=4.0, skip_calibration=True) optimizer.set_options(save_steps=1) feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2) var_form = RYRZ(num_qubits=feature_dim, depth=3) svm = QSVMVariational(optimizer, feature_map, var_form, training_input, test_input) quantum_instance = QuantumInstance(backend, shots=shots, seed=random_seed, seed_mapper=random_seed) result = svm.run(quantum_instance) print("testing success ratio: ", result['testing_accuracy']) predicted_probs, predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print("prediction: {}".format(predicted_labels))
https://github.com/alexyev/quantum_options_pricing
alexyev
#!pip install qiskit #!pip install qiskit_finance import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import Aer, QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_finance.circuit.library import LogNormalDistribution num_uncertainty_qubits = 3 spot = 3.0 vol = 0.2 #volatility rate = 0.05 #annual interest rate T = 100 / 365 #100 days until expiry # returns are log-normally distributed, values relating to this distribution shown here mu = (rate - 0.5 * vol ** 2) * T + np.log(spot) 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) # setting the lowest and highest values considered by our model low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # loading the option's probability distribution onto the quantum computer uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma ** 2, bounds=(low, high) ) 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 strike_price = 3.40 # scalar that determines accuracy of final output # the lower the better c_approx = 0.25 # setup piecewise linear # only works if stock price at maturity is above strike 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, ) # use the uncertainty model and the our objective function # to create a quantum circuit 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() # show the behaviour of the payoff function 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() exact_value = np.dot(uncertainty_model.probabilities, y) print("exact expected value:\t%.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=1024) problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi) 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))
https://github.com/Qubico-Hack/tutorials
Qubico-Hack
!pip install qiskit !pip install qiskit-aer import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw() class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) import numpy as np import matplotlib.pyplot as plt n_samples_show = 8 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() #axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' ) #plt.imshow((tf.squeeze(images[0]))) #plt.imshow( tf.shape( tf.squeeze(x_train) ) ) #axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 #Testing data transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels1 = cifar_testset.targets # get the labels for the data labels1 = np.array(labels1) idx1_ae = np.where(labels1 == 0) # filter on aeroplanes idx2_au = np.where(labels1 == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=50 # concatenate the data indices idxa = np.concatenate((idx1_ae[0][0:n],idx2_au[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idxa] cifar_testset.data = cifar_testset.data[idxa] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) 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(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) # Asumiendo que `hybrid` es una instancia de `Hybrid` x = (x + 1) / 2 x = torch.cat((x, 1 - x), -1) return x # qc = TorchCircuit.apply """ Ignore this cell """ class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.h1 = nn.Linear(500, 500) self.h2 = nn.Linear(500, 1) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 500) x = F.relu(self.h1(x)) x = F.dropout(x, training=self.training) x = self.h2(x) x = qc(x) x = (x + 1) / 2 # Normalise the inputs to 1 or 0 x = torch.cat((x, 1 - x), -1) return x model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list1 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list1.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list1[-1])) #Alongside, let's also plot the data plt.plot(loss_list1) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list2 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list2.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list2[-1])) #Alongside, let's also plot the data plt.plot(loss_list2) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 30 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) #Alongside, let's also plot the data plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) import torch import torchvision import torchvision.transforms as transforms plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list[-1])) plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') #Testing the quantum hybrid in order to comapre it with the classical one model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500,49) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) 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(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 99) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.softmax(x)
https://github.com/Qiskit/feedback
Qiskit
import numpy as np from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.opflow.gradients import Gradient from qiskit_nature.algorithms import AdaptVQE, VQEUCCFactory from qiskit_nature.circuit.library import HartreeFock, UCC from qiskit_nature.drivers import UnitsType from qiskit_nature.drivers.second_quantization import PySCFDriver, HDF5Driver from qiskit_nature.mappers.second_quantization import ParityMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.properties.second_quantization.electronic import ( ElectronicEnergy, ParticleNumber, ) from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer from qiskit_nature.properties.second_quantization.electronic.bases import ElectronicBasis from qiskit_nature.properties.second_quantization.electronic.integrals import ( OneBodyElectronicIntegrals, TwoBodyElectronicIntegrals,) #OLD CODE class AdaptVQE(GroundStateEigensolver): """A ground state calculation employing the AdaptVQE algorithm.""" def __init__( self, qubit_converter: QubitConverter, solver: MinimumEigensolverFactory, threshold: float = 1e-5, delta: float = 1, max_iterations: Optional[int] = None, ) -> None: #NEW CODE class AdaptVQE(GroundStateEigensolver): """A ground state calculation employing the AdaptVQE algorithm.""" def __init__( self, qubit_converter: QubitConverter, solver: MinimumEigensolverFactory, threshold: float = 1e-5, delta: float = 1, #this is going to be deprecated max_iterations: Optional[int] = None, gradient: Optional[Gradient] = None, ) -> None: def _compute_gradients( self, theta: List[float], vqe: VQE, ) -> List[Tuple[float, PauliSumOp]]: res = [] for exc in self._excitation_pool: # add next excitation to ansatz self._ansatz.operators = self._excitation_list + [exc] # set the current ansatz vqe.ansatz = self._ansatz # evaluate energies parameter_sets = theta + [-self._delta] + theta + [self._delta] energy_evaluation = vqe.get_energy_evaluation(self._main_operator) energy_results = energy_evaluation(np.asarray(parameter_sets)) # compute gradient gradient = (energy_results[0] - energy_results[1]) / (2 * self._delta) res.append((np.abs(gradient), exc)) return res def _compute_gradients( self, theta: List[float], vqe: VQE, ) -> List[Tuple[float, PauliSumOp]]: res=[] for exc in self._excitation_pool: self._ansatz.operators = self._excitation_list + [exc] if self.gradient.grad_method.analytic: vqe.ansatz = self._ansatz else: vqe.ansatz = self._ansatz.decompose() param_sets = vqe._ansatz_params op = vqe.construct_expectation(theta, self._main_operator) state_grad = self.gradient.convert(operator=op, params=param_sets) # Assign the parameters and evaluate the gradient value_dict = {param_sets[-1]:0.0} state_grad_result = state_grad.assign_parameters(value_dict).eval() logger.info("State gradient computed with parameter shift", state_grad_result) res.append((np.abs(state_grad_result[-1]), exc)) return res driver = PySCFDriver( atom="H .0 .0 .0; H .0 .0 0.735", unit=UnitsType.ANGSTROM, basis="sto3g" ) problem = ElectronicStructureProblem(driver) expected = -1.85727503 qubit_converter = QubitConverter(ParityMapper()) solver=VQEUCCFactory(QuantumInstance(BasicAer.get_backend("statevector_simulator"))) %%time #logging.basicConfig(level = logging.DEBUG) grad=Gradient(grad_method="fin_diff") calc= AdaptVQE(qubit_converter,solver,gradient=grad) res = calc.solve(problem) print("Energy calculated: ",res.electronic_energies[0]) print("Expected energy: ", expected) %%time grad=Gradient(grad_method="param_shift") calc= AdaptVQE(qubit_converter,solver,gradient=grad) res = calc.solve(problem) print("Energy calculated: ",res.electronic_energies[0]) print("Expected energy: ", expected) qubit_converter = QubitConverter(ParityMapper()) solver=VQEUCCFactory(QuantumInstance(BasicAer.get_backend("statevector_simulator"))) inter_dist = 1.6 driver1 = PySCFDriver( atom="Li .0 .0 .0; H .0 .0 " + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis="sto3g", ) transformer = ActiveSpaceTransformer( num_electrons=2, num_molecular_orbitals=3, ) problem1 = ElectronicStructureProblem(driver1, [transformer]) solver = VQEUCCFactory(QuantumInstance(BasicAer.get_backend("statevector_simulator"))) %%time grad=Gradient(grad_method="fin_diff") calc = AdaptVQE(qubit_converter, solver,gradient=grad) res = calc.solve(problem1) print("Energy calculated: ",res.electronic_energies[0]) %%time grad=Gradient(grad_method="param_shift") calc = AdaptVQE(qubit_converter, solver,gradient=grad) res = calc.solve(problem1) print("Energy calculated: ",res.electronic_energies[0])
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma): ### create a Rabi schedule (already done) ### create a Gaussian Rabi pulse using pulse_lib ### play Rabi pulse on the Rabi schedule and return rabi_schedule = pulse.Schedule(name='rabi_experiment') ### WRITE YOUR CODE BETWEEN THESE LINES - START rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma) rabi_schedule = pulse.Schedule() rabi_schedule += Play(rabi_pulse, drive_chan) ### WRITE YOUR CODE BETWEEN THESE LINES - END # add measurement to rabi_schedule # << indicates time shift the beginning to the start of the schedule rabi_schedule += measure << rabi_schedule.duration return rabi_schedule # Gaussian pulse parameters, with varying amplitude drive_duration = 128 num_rabi_points = 41 drive_amps = np.linspace(0, 0.9, num_rabi_points) drive_sigma = 16 # now vary the amplitude for each drive amp rabi_schedules = [] for drive_amp in drive_amps: rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma)) rabi_schedules[-1].draw() # assemble the schedules into a Qobj from qiskit import assemble rabi_qobj = assemble(**helper.get_params('rabi', globals())) answer1a = rabi_qobj # run the simulation rabi_result = backend_sim.run(rabi_qobj, duffing_model).result() # retrieve the data from the experiment rabi_values = helper.get_values_from_result(rabi_result, qubit) fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(0, color='red', linestyle='--') plt.axvline(drive_period/2, color='red', linestyle='--') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print("Pi pulse amplitude is %f"%float(drive_period/2)) # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_period/4, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 0.4 time_step_us = 0.0035 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt def build_ramsey_pulse_schedule(delay): ### create a Ramsey pulse schedule (already done) ### play an x90 pulse on the drive channel ### play another x90 pulse after delay ### add measurement pulse to schedule ramsey_schedule = pulse.Schedule(name='ramsey_experiment') ### HINT: include delay by adding it to the duration of the schedule ### round delay to nearest integer with int(delay) ### WRITE YOUR CODE BETWEEN THESE LINES - START ramsey_schedule = pulse.Schedule() ramsey_schedule += Play(x90_pulse, drive_chan) ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay) ramsey_schedule += measure << ramsey_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - END return ramsey_schedule # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: ramsey_schedules.append(build_ramsey_pulse_schedule(delay)) ramsey_schedules[-1].draw() # assemble the schedules into a Qobj # the helper will drive the pulses off-resonantly by an unknown value ramsey_qobj = assemble(**helper.get_params('ramsey', globals())) answer1b = ramsey_qobj # run the simulation ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result() # retrieve the data from the experiment ramsey_values = helper.get_values_from_result(ramsey_result, qubit) # off-resonance component fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25]) _, _, ramsey_period_us, _, = fit_params del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz") plt.xlim(np.min(times_us), np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend(loc=3) plt.show() print("Drive is off-resonant by %f MHz"%float(del_f_MHz)) name = 'Saasha Joshi' email = 'saashajoshi08@gmail.com' from grading_tools import grade grade(answer1a, name, email, 'lab6', 'ex1a') grade(answer1b, name, email, 'lab6', 'ex1b') from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Deutsch-Jozsa algorithm. """ import logging import operator import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.utils import get_subsystem_density_matrix logger = logging.getLogger(__name__) class DeutschJozsa(QuantumAlgorithm): """The Deutsch-Jozsa algorithm.""" CONFIGURATION = { 'name': 'DeutschJozsa', 'description': 'Deutsch Jozsa', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'dj_schema', 'type': 'object', 'properties': { }, 'additionalProperties': False }, 'problems': ['functionevaluation'], 'depends': [ { 'pluggable_type': 'oracle', 'default': { 'name': 'TruthTableOracle', }, }, ], } def __init__(self, oracle): self.validate(locals()) super().__init__() self._oracle = oracle self._circuit = None self._ret = {} @classmethod def init_params(cls, params, algo_input): if algo_input is not None: raise AquaError("Input instance not supported.") oracle_params = params.get(Pluggable.SECTION_KEY_ORACLE) oracle = get_pluggable_class( PluggableType.ORACLE, oracle_params['name']).init_params(params) return cls(oracle) def construct_circuit(self, measurement=False): """ Construct the quantum circuit Args: measurement (bool): Boolean flag to indicate if measurement should be included in the circuit. Returns: the QuantumCircuit object for the constructed circuit """ if self._circuit is not None: return self._circuit # preoracle circuit qc_preoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_preoracle.h(self._oracle.variable_register) qc_preoracle.x(self._oracle.output_register) qc_preoracle.h(self._oracle.output_register) qc_preoracle.barrier() # oracle circuit qc_oracle = self._oracle.circuit # postoracle circuit qc_postoracle = QuantumCircuit( self._oracle.variable_register, self._oracle.output_register, ) qc_postoracle.h(self._oracle.variable_register) qc_postoracle.barrier() self._circuit = qc_preoracle + qc_oracle + qc_postoracle # measurement circuit if measurement: measurement_cr = ClassicalRegister(len(self._oracle.variable_register), name='m') self._circuit.add_register(measurement_cr) self._circuit.measure(self._oracle.variable_register, measurement_cr) return self._circuit def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) max_amplitude = max( variable_register_density_matrix_diag.min(), variable_register_density_matrix_diag.max(), key=abs ) max_amplitude_idx = np.where(variable_register_density_matrix_diag == max_amplitude)[0][0] top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register)) else: qc = self.construct_circuit(measurement=True) measurement = self._quantum_instance.execute(qc).get_counts(qc) self._ret['measurement'] = measurement top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0] self._ret['result'] = 'constant' if int(top_measurement) == 0 else 'balanced' return self._ret
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A swap strategy pass for blocks of commuting gates.""" from __future__ import annotations from collections import defaultdict from qiskit.circuit import Gate, QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler import TransformationPass, Layout, TranspilerError from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import ( Commuting2qBlock, ) class Commuting2qGateRouter(TransformationPass): """A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as :class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map .. parsed-literal:: 0 -- 1 -- 2 | 3 | 4 To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. .. code-block:: python from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw("mpl") This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the ``current_layout`` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the ``current_layout`` into account. """ def __init__( self, swap_strategy: SwapStrategy | None = None, edge_coloring: dict[tuple[int, int], int] | None = None, ) -> None: r""" Args: swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given if should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as ``RZZGate``\s next to swap gates to exploit CX cancellations. """ super().__init__() self._swap_strategy = swap_strategy self._bit_indices: dict[Qubit, int] | None = None self._edge_coloring = edge_coloring def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the pass by decomposing the nodes it applies on. Args: dag: The dag to which we will add swaps. Returns: A dag where swaps have been added for the intended gate type. Raises: TranspilerError: If the swap strategy was not given at init time and there is no swap strategy in the property set. TranspilerError: If the quantum circuit contains more than one qubit register. TranspilerError: If there are qubits that are not contained in the quantum register. """ if self._swap_strategy is None: swap_strategy = self.property_set["swap_strategy"] if swap_strategy is None: raise TranspilerError("No swap strategy given at init or in the property set.") else: swap_strategy = self._swap_strategy if len(dag.qregs) != 1: raise TranspilerError( f"{self.__class__.__name__} runs on circuits with one quantum register." ) if len(dag.qubits) != next(iter(dag.qregs.values())).size: raise TranspilerError("Circuit has qubits not contained in the qubit register.") new_dag = dag.copy_empty_like() current_layout = Layout.generate_trivial_layout(*dag.qregs.values()) # Used to keep track of nodes that do not decompose using swap strategies. accumulator = new_dag.copy_empty_like() for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) # Compose any accumulated non-swap strategy gates to the dag accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag) # Decompose the swap-strategy node and add to the dag. new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy)) else: accumulator.apply_operation_back(node.op, node.qargs, node.cargs) self._compose_non_swap_nodes(accumulator, current_layout, new_dag) return new_dag def _compose_non_swap_nodes( self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit ) -> DAGCircuit: """Add all the non-swap strategy nodes that we have accumulated up to now. This method also resets the node accumulator to an empty dag. Args: layout: The current layout that keeps track of the swaps. new_dag: The new dag that we are building up. accumulator: A DAG to keep track of nodes that do not decompose using swap strategies. Returns: A new accumulator with the same registers as ``new_dag``. """ # Add all the non-swap strategy nodes that we have accumulated up to now. order = layout.reorder_bits(new_dag.qubits) order_bits: list[int | None] = [None] * len(layout) for idx, val in enumerate(order): order_bits[val] = idx new_dag.compose(accumulator, qubits=order_bits) # Re-initialize the node accumulator return new_dag.copy_empty_like() def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]: """A helper function to track the movement of virtual qubits through the swaps. Args: j: The index of decision variable j (i.e. virtual qubit). k: The index of decision variable k (i.e. virtual qubit). layout: The current layout that takes into account previous swap gates. Returns: The position in the coupling map of the virtual qubits j and k as a tuple. """ bit0 = dag.find_bit(layout.get_physical_bits()[j]).index bit1 = dag.find_bit(layout.get_physical_bits()[k]).index return bit0, bit1 def _build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """A helper method to build-up sets of gates to simultaneously apply. This is done with an edge coloring if the ``edge_coloring`` init argument was given or with a greedy algorithm if not. With an edge coloring all gates on edges with the same color will be applied simultaneously. These sublayers are applied in the order of their color, which is an int, in increasing color order. Args: current_layer: All gates in the current layer can be applied given the qubit ordering of the current layout. However, not all gates in the current layer can be applied simultaneously. This function creates sub-layers by building up sub-layers of gates. All gates in a sub-layer can simultaneously be applied given the coupling map and current qubit configuration. Returns: A list of gate dicts that can be applied. The gates a position 0 are applied first. A gate dict has the qubit tuple as key and the gate to apply as value. """ if self._edge_coloring is not None: return self._edge_coloring_build_sub_layers(current_layer) else: return self._greedy_build_sub_layers(current_layer) def _edge_coloring_build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The edge coloring method of building sub-layers of commuting gates.""" sub_layers: list[dict[tuple[int, int], Gate]] = [ {} for _ in set(self._edge_coloring.values()) ] for edge, gate in current_layer.items(): color = self._edge_coloring[edge] sub_layers[color][edge] = gate return sub_layers @staticmethod def _greedy_build_sub_layers( current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The greedy method of building sub-layers of commuting gates.""" sub_layers = [] while len(current_layer) > 0: current_sub_layer, remaining_gates = {}, {} blocked_vertices: set[tuple] = set() for edge, evo_gate in current_layer.items(): if blocked_vertices.isdisjoint(edge): current_sub_layer[edge] = evo_gate # A vertex becomes blocked once a gate is applied to it. blocked_vertices = blocked_vertices.union(edge) else: remaining_gates[edge] = evo_gate current_layer = remaining_gates sub_layers.append(current_sub_layer) return sub_layers def swap_decompose( self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy ) -> DAGCircuit: """Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. Args: dag: The dag which contains the :class:`.Commuting2qBlock` we route. node: A node whose operation is a :class:`.Commuting2qBlock`. current_layout: The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. swap_strategy: The swap strategy used to decompose the node. Returns: A dag that is compatible with the coupling map where swap gates have been added to map the gates in the :class:`.Commuting2qBlock` to the hardware. """ trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy) # Iterate over and apply gate layers max_distance = max(gate_layers.keys()) circuit_with_swap = QuantumCircuit(len(dag.qubits)) for i in range(max_distance + 1): # Get current layer and replace the problem indices j,k by the corresponding # positions in the coupling map. The current layer corresponds # to all the gates that can be applied at the ith swap layer. current_layer = {} for (j, k), local_gate in gate_layers.get(i, {}).items(): current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate # Not all gates that are applied at the ith swap layer can be applied at the same # time. We therefore greedily build sub-layers. sub_layers = self._build_sub_layers(current_layer) # Apply sub-layers for sublayer in sub_layers: for edge, local_gate in sublayer.items(): circuit_with_swap.append(local_gate, edge) # Apply SWAP gates if i < max_distance: for swap in swap_strategy.swap_layer(i): (j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap] circuit_with_swap.swap(j, k) current_layout.swap(j, k) return circuit_to_dag(circuit_with_swap) def _make_op_layers( self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy ) -> dict[int, dict[tuple, Gate]]: """Creates layers of two-qubit gates based on the distance in the swap strategy.""" gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict) for node in op.node_block: edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index) bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]] bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]] distance = swap_strategy.distance_matrix[bit0, bit1] gate_layers[distance][edge] = node.op return gate_layers def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy): """Check if the swap strategy can create the required connectivity. Args: node: The dag node for which to check if the swap strategy provides enough connectivity. swap_strategy: The swap strategy that is being used. Raises: TranspilerError: If there is an edge that the swap strategy cannot accommodate and if the pass has been configured to raise on such issues. """ required_edges = set() for sub_node in node.op: edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index) required_edges.add(edge) # Check that the swap strategy supports all required edges if not required_edges.issubset(swap_strategy.possible_edges): raise TranspilerError( f"{swap_strategy} cannot implement all edges in {required_edges}." )
https://github.com/Axect/QuantumAlgorithms
Axect
import qiskit qiskit.__qiskit_version__ #initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.compiler import transpile from qiskit.tools.monitor import job_monitor # import basic plot tools from qiskit.tools.visualization import plot_histogram # Load our saved IBMQ accounts. IBMQ.load_account() nQubits = 14 # number of physical qubits a = 101 # the hidden integer whose bitstring is 1100101 # make sure that a can be represented with nQubits a = a % 2**(nQubits) # Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # for recording the measurement on qr cr = ClassicalRegister(nQubits) circuitName = "BernsteinVazirani" bvCircuit = QuantumCircuit(qr, cr) # Apply Hadamard gates before querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Apply barrier so that it is not optimized by the compiler bvCircuit.barrier() # Apply the inner-product oracle for i in range(nQubits): if (a & (1 << i)): bvCircuit.z(qr[i]) else: bvCircuit.iden(qr[i]) # Apply barrier bvCircuit.barrier() #Apply Hadamard gates after querying the oracle for i in range(nQubits): bvCircuit.h(qr[i]) # Measurement bvCircuit.barrier(qr) bvCircuit.measure(qr, cr) bvCircuit.draw(output='mpl') # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1000 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) backend = IBMQ.get_backend('ibmq_16_melbourne') shots = 1000 bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1) job_exp = execute(bvCircuit, backend=backend, shots=shots) job_monitor(job_exp) results = job_exp.result() answer = results.get_counts(bvCircuit) threshold = int(0.01 * shots) #the threshold of plotting significant measurements filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index plot_histogram(filteredAnswer) print(filteredAnswer)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/GroenteLepel/qiskit-quantum-knn
GroenteLepel
# -*- 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/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit grid = CreativeQiskit.random_grid(5,4) grid.neighbours( (2,2) ) grid_stats,grid_data = grid.get_samples(shots=3) for sample in grid_stats: print(grid_stats[sample],'shots returned the grid state\n') print(sample,'\n') for sample in grid_data: print(sample,'\n') grid.NOT((0,0)) grid.NOT((4,3),frac=0.5) control = (4,3) for target in grid.neighbours( control ): grid.CNOT(control,target) grid_stats,grid_data = grid.get_samples(shots=10) def show_results (grid): for sample in grid_stats: print(grid_stats[sample],'shots returned the grid state\n') print(sample,'\n') show_results(grid) grid.NOT( (0,3) ) grid.CNOT((0,3), (1,3), frac=0.5) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='x' ) grid.NOT( (0,0), frac=0.5, axis='x' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='y' ) grid.NOT( (0,0), frac=0.5, axis='y' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) grid = CreativeQiskit.random_grid(2,2) grid.NOT( (0,0), frac=0.5, axis='x' ) grid.NOT( (0,0), frac=0.5, axis='y' ) grid_stats,grid_data = grid.get_samples(shots=10) show_results(grid) from qiskit import IBMQ IBMQ.load_accounts() grid = CreativeQiskit.random_grid(5,5) grid.NOT( (0,0), frac=0.5, ) for j in range(5): control = (j,j) grid.NOT( control, frac=(1/(j+1)) ) for target in grid.neighbours( control ): grid.CNOT(control,target) grid_stats,grid_data = grid.get_samples(shots=10,device='ibmq_qasm_simulator') show_results(grid)
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumRegister, QuantumCircuit qrx = QuantumRegister(3, 'x') qry = QuantumRegister(1, 'y') qc = QuantumCircuit(qrx, qry) qc.cx(qrx[0], qry) qc.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.algorithms import ( MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer, SolutionSample, OptimizationResultStatus, ) from qiskit_optimization import QuadraticProgram from qiskit.visualization import plot_histogram from typing import List, Tuple import numpy as np # create a QUBO qubo = QuadraticProgram() qubo.binary_var("x") qubo.binary_var("y") qubo.binary_var("z") qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2}) print(qubo.prettyprint()) op, offset = qubo.to_ising() print("offset: {}".format(offset)) print("operator:") print(op) qp = QuadraticProgram() qp.from_ising(op, offset, linear=True) print(qp.prettyprint()) algorithm_globals.random_seed = 10598 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver exact_result = exact.solve(qubo) print(exact_result.prettyprint()) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) print("variable order:", [var.name for var in qaoa_result.variables]) for s in qaoa_result.samples: print(s) def get_filtered_samples( samples: List[SolutionSample], threshold: float = 0, allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,), ): res = [] for s in samples: if s.status in allowed_status and s.probability > threshold: res.append(s) return res filtered_samples = get_filtered_samples( qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) for s in filtered_samples: print(s) fvals = [s.fval for s in qaoa_result.samples] probabilities = [s.probability for s in qaoa_result.samples] np.mean(fvals) np.std(fvals) samples_for_plot = { " ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact) rqaoa_result = rqaoa.solve(qubo) print(rqaoa_result.prettyprint()) filtered_samples = get_filtered_samples( rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,) ) samples_for_plot = { " ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability for s in filtered_samples } samples_for_plot plot_histogram(samples_for_plot) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright