repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/taalexander/IEEE-Quantum-Week-2021
taalexander
import os from typing import Any, List, Dict, Union import numpy as np import matplotlib.pyplot as plt from qiskit import IBMQ, QuantumCircuit, QuantumRegister, ClassicalRegister, quantum_info as qi from qiskit.providers.ibmq import RunnerResult from qiskit.result import marginal_counts import qiskit.tools.jupyter %matplotlib inline import warnings warnings.filterwarnings("ignore") hub = 'ibm-q-community' group = 'ieee-session' project = 'event-2021' backend_name = 'ibm_perth' from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub=hub, group=group, project=project) backend = provider.get_backend(backend_name) import qiskit.tools.jupyter backend from qiskit import QuantumCircuit # Fill in Readout test and draw from qiskit import QuantumCircuit qc_prep_excited = QuantumCircuit(1, 1) qc_prep_excited.x(0) qc_prep_excited.measure(0, 0) qc_prep_excited.draw(output="mpl", idle_wires=False) qubit = 3 shots = 1000 from qiskit import transpile # Transpile for qubit and draw from qiskit import transpile qc_prep_excited_transpiled = transpile(qc_prep_excited, backend, initial_layout=[qubit]) qc_prep_excited_transpiled.draw(output="mpl", idle_wires=False) from run_openqasm3 import run_openqasm3 # Run the circuit / QASM3 from run_openqasm3 import run_openqasm3 job = run_openqasm3(qc_prep_excited_transpiled, backend, verbose=True) runtime_params = { 'circuits': [qc_prep_excited_transpiled], } options = {'backend_name': backend.name()} from qiskit.providers.ibmq import RunnerResult prep_excited_job = provider.runtime.run( program_id="qasm3-runner", options=options, inputs=runtime_params, image="qiskit-program-qasm3:latest", result_decoder=RunnerResult, ) prep_excited_result = prep_excited_job.result() print(prep_excited_result.get_counts()) try: from qiskit import qasm3 except ImportError: print("You likely do not have the main branch of Qiskit installed. Please install it to run this code") raise basis_gates = backend.configuration().basis_gates def dump_qasm3(circuit, backend=backend): return qasm3.Exporter(includes=[], basis_gates=basis_gates).dumps(circuit) excited_prep_source_string = dump_qasm3(qc_prep_excited_transpiled) print(excited_prep_source_string) runtime_params = { 'circuits': [excited_prep_source_string], } options = {'backend_name': backend.name()} prep_excited_job_source_str = provider.runtime.run( program_id="qasm3-runner", options=options, inputs=runtime_params, image="qiskit-program-qasm3:latest", result_decoder=RunnerResult, ) print(prep_excited_job_source_str.result().get_counts()) qc_real_time = QuantumCircuit(1, 2) # Program a builtin reset test circuit named job real time and draw qc_real_time = QuantumCircuit(1, 2) qc_real_time.x(0) qc_real_time.measure(0, 0) qc_real_time.reset(0) qc_real_time.measure(0, 1) qc_real_time.draw(output="mpl", idle_wires=False) # Run the reset job and check the results real_time_job = backend.run(transpile(qc_real_time, backend, initial_layout=[qubit]), shots=1000) print(real_time_job.job_id()) print(f" Our reset counts were: {real_time_job.result().get_counts(0)}") job_real_time = backend.run(qc_real_time) print(f"Job id: {job_real_time.job_id()}") result_real_time = job_real_time.result() print(f"Reset results: {result_real_time.get_counts(0)}") from qiskit import QuantumRegister, ClassicalRegister qr = QuantumRegister(1) crx = ClassicalRegister(1, name="xresult") crm = ClassicalRegister(1, name="measureresult") qc_reset = QuantumCircuit(qr, crx, crm, name="Reset") # Program a reset directly using control flow and draw from qiskit import QuantumRegister, ClassicalRegister qr = QuantumRegister(1) crx = ClassicalRegister(1, name="xresult") crm = ClassicalRegister(1, name="measureresult") qc_reset = QuantumCircuit(qr, crx, crm, name="Reset") qc_reset.x(0) qc_reset.measure(0, crx) qc_reset.x(0).c_if(crx, 1) qc_reset.measure(0, crm) qc_reset = transpile(qc_reset, backend, initial_layout=[1]) qc_reset.draw(output="mpl", idle_wires=False) print(dump_qasm3(qc_reset)) reset_job = run_openqasm3(qc_reset, backend, verbose=True) from qiskit.result import marginal_counts reset_result = reset_job.result() reset_counts = reset_result.get_counts(0) mitigated_reset_results = marginal_counts(reset_counts, indices=[1]) print(f"Full counts including reset: {reset_counts}") print(f"Results from our reset - |0>s prepared {mitigated_reset_results.get('0')}, |1>s prepared {mitigated_reset_results['1']}" ) # Program several rounds of reset using QASM3 #print(dump_qasm3(qc_reset)) qubit_init_qasm3 = """ """ qubit_init_qasm3 = """ OPENQASM 3; bit reset_result0; bit reset_result1; bit reset_result2; bit[1] measureresult; x $1; reset_result0 = measure $1; // three rounds of reset. if (reset_result0 == 1) { x $1; } reset_result1 = measure $1; if (reset_result1 == 1) { x $1; } reset_result2 = measure $1; if (reset_result2 == 1) { x $1; } // Final measurement measureresult[0] = measure $1; """ init_job = run_openqasm3(qubit_init_qasm3, backend, verbose=False) print(init_job.job_id()) better_reset_result_1s = sum(count for key, count in init_job.result().get_counts(0).items() if (len(key)==4)) print(f"Results from our better reset - |0>s prepared {shots-better_reset_result_1s}, |1>s prepared {better_reset_result_1s} ") qr = QuantumRegister(3) crz = ClassicalRegister(1, name="crz") crx = ClassicalRegister(1, name="crx") result = ClassicalRegister(1, name="result") qc_teleport = QuantumCircuit(qr, crz, crx, result, name="Teleport") # Apply teleportation circuit qc_teleport.h(qr[1]) qc_teleport.cx(qr[1], qr[2]) #qc_teleport.barrier(qr) qc_teleport.cx(qr[0], qr[1]) qc_teleport.h(qr[0]) qc_teleport.measure(qr[0], crz) qc_teleport.measure(qr[1], crx) qc_teleport.z(qr[2]).c_if(crz, 1) qc_teleport.x(qr[2]).c_if(crx, 1) qc_teleport.draw(output="mpl") qc_state_prep = QuantumCircuit(1) qc_state_prep.x(0) print(qc_state_prep) target_state_prep = qi.Statevector.from_instruction(qc_state_prep) print(target_state_prep) teleport_qubits = [0, 1, 2] qc_teleport_state = QuantumCircuit(qr, crz, crx, result, name="Teleport Hadamard") def init(qc, qr): qc.barrier(qr) qc.reset(qr) qc.barrier(qr) qc.reset(qr) qc.barrier(qr) qc.reset(qr) qc.barrier(qr) init(qc_teleport_state, qr) # Prepare state to teleport qc_teleport_state.compose(qc_state_prep, [qr[0]], inplace=True) qc_teleport_state.barrier(qr) # Compose with teleportation circuit qc_teleport_state.compose(qc_teleport, inplace=True) qc_teleport_state.draw(output="mpl") qc_teleport_experiment = qc_teleport_state.copy() qc_teleport_experiment.measure(qr[2], result) qc_teleport_experiment = transpile(qc_teleport_experiment, backend, initial_layout=teleport_qubits, optimization_level=3) qc_teleport_experiment.draw(output="mpl") teleport_job = run_openqasm3(qc_teleport_experiment, backend, verbose=False) print(teleport_job.job_id()) teleport_result = teleport_job.result() print(f"All teleportation reults: {teleport_result.get_counts(0)}") marginal_teleport_counts = marginal_counts(teleport_result.get_counts(0), indices=[2]) print(f"Marginalized teleportation counts: {marginal_teleport_counts}") from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.visualization import plot_state_city, plot_state_paulivec meas_calibs, state_labels = complete_meas_cal(qr=[qr[2]], circlabel='mcal') meas_calibs = transpile(meas_calibs, backend, initial_layout={qr[2]: teleport_qubits[-1]}) meas_calibs[1].draw(idle_wires=False, output="mpl") meas_calib_job = run_openqasm3(meas_calibs, backend, verbose=False) print(f"Job id: {meas_calib_job.job_id()}") meas_calib_result = meas_calib_job.result() meas_fitter = CompleteMeasFitter(meas_calib_result, state_labels, circlabel='mcal') meas_fitter.cal_matrix meas_filter = meas_fitter.filter mitigated_teleport_counts = meas_filter.apply(marginal_teleport_counts) print(f"Unmitigated teleportation counts {marginal_teleport_counts}") print(f"Mitigated teleportation counts {mitigated_teleport_counts}") def build_state_tomo_circuits(qc_prep, qr, clbits, tomo_qubits, layout): qst_tomography_circuits = state_tomography_circuits(QuantumCircuit(qr), tomo_qubits) tomography_circuits = [] for tomo_circuit in qst_tomography_circuits: tomo_circ = qc_prep.compose(tomo_circuit, clbits=clbits) tomo_circ.name = tomo_circuit.name tomography_circuits.append(tomo_circ) return transpile(tomography_circuits, backend, initial_layout=layout) qt_qst_tomography_circuits = build_state_tomo_circuits(qc_teleport_state, qr, [result[0]], [qr[2]], teleport_qubits) teleport_qst_jobs = run_openqasm3(qt_qst_tomography_circuits, backend, verbose=False) qt_qst_tomography_circuits[1].draw(output="mpl") teleport_qst_result = teleport_qst_jobs.result() marginal_teleport_qst_result = marginal_counts(teleport_qst_result, indices=[2]) mitigated_qst_results = meas_filter.apply(marginal_teleport_qst_result) qt_qst_tomo_fitter = StateTomographyFitter(mitigated_qst_results, qt_qst_tomography_circuits) qt_qst_rho_fit = qt_qst_tomo_fitter.fit(method='lstsq') qt_qst_F = qi.state_fidelity(qt_qst_rho_fit, target_state_prep) print('State Fidelity: F = {:.5f}'.format(qt_qst_F)) fig, axes = plt.subplots(1, 2, sharey=True) plot_state_paulivec(qt_qst_rho_fit, ax=axes[0]); plot_state_paulivec(qi.DensityMatrix.from_instruction(qc_state_prep), ax=axes[1]) axes[1].set_ylabel(None); axes[0].set_title("Experiment") axes[1].set_title("Ideal") plt.tight_layout() fig.set_size_inches(14, 6) plot_state_city(qt_qst_rho_fit, title="Experiment"); plot_state_city(qi.DensityMatrix.from_instruction(qc_state_prep), title="Ideal");
https://github.com/mspronesti/qlearnkit
mspronesti
import numpy as np from qiskit import QuantumCircuit, QuantumRegister from .encoding_map import EncodingMap from ..circuits.circuit_utils import to_basis_gates """Encoding classical data to quantum state via amplitude encoding.""" class AmplitudeEncoding(EncodingMap): """ Amplitude Encoding map """ def __init__(self, n_features: int = 2): super().__init__(n_features) n_qubits = np.log2(n_features) if not n_qubits.is_integer(): # if number of qubits is not a positive # power of 2, an extra qubit is needed n_qubits = np.ceil(n_qubits) elif n_qubits == 0: # in this scenario, n_features = 1 # then we need 1 qubit n_qubits = 1 self._num_qubits = int(n_qubits) def construct_circuit(self, x) -> QuantumCircuit: """ Constructs circuit for amplitude encoding Args: x: 1D classical data vector to be encoded must satisfy len(x) == num_features """ self._check_feature_vector(x) if self.num_features % 2 != 0: # Number of features should be # a positive power of 2 for `initialize`, # then we add some padding x = np.pad(x, (0, (1 << self.num_qubits) - len(x))) state_vector = self.state_vector(x) q = QuantumRegister(self.num_qubits) qc = QuantumCircuit(q) qc.initialize(state_vector, [q[i] for i in range(self.num_qubits)]) # convert final circuit to basis gates # to unwrap the "initialize" block qc = to_basis_gates(qc) # remove the reset gates the unroller added qc.data = [d for d in qc.data if d[0].name != "reset"] return qc def state_vector(self, x): r""" The encoding of a state via amplitude encoding operates as follows: given a quantum state :math:`\psi`, it processes the data such that .. math::\langle\psi|\psi\rangle = 1, Args: x: the classical data Returns: (np.array) encoded quantum state """ if isinstance(x, list): x = np.asarray(x) norm = np.linalg.norm(x) # retrieves the normalized vector # if the norm is not zero return x / norm if not norm == 0 else x
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
from qiskit import QuantumCircuit def measure_y() -> QuantumCircuit: circuit = QuantumCircuit(1, 1) circuit.sdg(0) circuit.h(0) circuit.measure(0, 0) return circuit def measure_z() -> QuantumCircuit: circuit = QuantumCircuit(1, 1) circuit.measure(0, 0) return circuit def measure_x() -> QuantumCircuit: circuit = QuantumCircuit(1, 1) circuit.h(0) circuit.measure(0, 0) return circuit def ry_then_measure(theta) -> QuantumCircuit: circuit = QuantumCircuit(1, 1) circuit.ry(theta, 0) circuit.measure(0, 0) return circuit
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
import qiskit.quantum_info as qi from qiskit.circuit.library import FourierChecking from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt f = [0,0,0,0] g = [1,1,1,-1] circuit = FourierChecking(f=f, g=g) circuit.draw(output='mpl') zero = qi.Statevector.from_label('00') sv = zero.evolve(circuit) probs = sv.probabilities_dict() plot_histogram(probs) plt.show()
https://github.com/UST-QuAntiL/nisq-analyzer-content
UST-QuAntiL
from typing import List from qiskit import QuantumCircuit, transpile, QuantumRegister, ClassicalRegister from qiskit import BasicAer,Aer,execute, IBMQ from qiskit.providers.aer import QasmSimulator from qiskit.circuit.library.arithmetic import DraperQFTAdder, RGQFTMultiplier from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, AmplitudeEstimation from qiskit.algorithms import EstimationProblem from qiskit.utils import QuantumInstance from qiskit.providers.fake_provider import FakeMontreal def encode_input(x: List[int]) -> "Gate": num_qubits = len(x) qc = QuantumCircuit(num_qubits, name="encoding") for i in range(num_qubits): if x[i] == 1: qc.x(num_qubits - i - 1) return qc def encode_hadamard_copy(num_qubits: int) -> "Gate": qc = QuantumCircuit(num_qubits * 2, name="extension") for i in range(num_qubits): qc.cx(i, i + num_qubits) return qc def encode_hadamard(num_qubits: int) -> "Gate": qc = QuantumCircuit(num_qubits, name="encoding") for i in range(num_qubits): qc.h(i) return qc def classical(x: List[int], y: List[int]) -> int: num1 = 0 for i in range(len(x)): num1 += x[i] * 0.5 ** (i + 1) num2 = 0 for i in range(len(y)): num2 += x[i] * 0.5 ** (i + 1) result = num1 ** 2 + num2 ** 2 if result < 1: return 1 return 0 def operator(bits_per_input, x1, x2, useQAE): num_bits_after_mult = 2 * bits_per_input num_bits_comparer = num_bits_after_mult + 1 nQubits = 4 * bits_per_input + 2 * num_bits_after_mult + 1 + num_bits_comparer nClassical = 1 input_register_1 = QuantumRegister(size=bits_per_input) input_register_1_copy = QuantumRegister(size=bits_per_input) input_register_2 = QuantumRegister(size=bits_per_input) input_register_2_copy = QuantumRegister(size=bits_per_input) if len(x1) == 0 and len(x2) == 0: input_circuit_1 = encode_hadamard(bits_per_input) input_circuit_1_copy = encode_hadamard_copy(bits_per_input) input_circuit_2 = encode_hadamard(bits_per_input) input_circuit_2_copy = encode_hadamard_copy(bits_per_input) else: input_circuit_1 = encode_input(x1) input_circuit_1_copy = encode_input(x1) input_circuit_2 = encode_input(x2) input_circuit_2_copy = encode_input(x2) carry_qubits_mult_1 = QuantumRegister(size=num_bits_after_mult) carry_qubits_mult_2 = QuantumRegister(size=num_bits_after_mult) carry_qubits_comparer = QuantumRegister(size=num_bits_comparer) carry_qubit_addition = QuantumRegister(size=1) # 1 additional qubit for addition if useQAE == False: output_register = ClassicalRegister(size=nClassical) circuit = QuantumCircuit( input_register_1, input_register_1_copy, input_register_2, input_register_2_copy, carry_qubits_mult_1, carry_qubits_mult_2, carry_qubit_addition, carry_qubits_comparer, output_register ) else: circuit = QuantumCircuit( input_register_1, input_register_1_copy, input_register_2, input_register_2_copy, carry_qubits_mult_1, carry_qubits_mult_2, carry_qubit_addition, carry_qubits_comparer ) # encoding circuit.append(input_circuit_1, input_register_1[:]) if len(x1) == 0 and len(x2) == 0: circuit.append(input_circuit_1_copy, input_register_1[:] + input_register_1_copy[:]) else: circuit.append(input_circuit_1_copy, input_register_1_copy[:]) circuit.append(input_circuit_2, input_register_2[:]) if len(x1) == 0 and len(x2) == 0: circuit.append(input_circuit_2_copy, input_register_2[:] + input_register_2_copy[:]) else: circuit.append(input_circuit_2_copy, input_register_2_copy[:]) # multiplication multiplicator = RGQFTMultiplier(num_state_qubits=bits_per_input) circuit.append(multiplicator, input_register_1[:] + input_register_1_copy[:] + carry_qubits_mult_1[:]) circuit.append(multiplicator, input_register_2[:] + input_register_2_copy[:] + carry_qubits_mult_2[:]) # addition adder = DraperQFTAdder(num_bits_after_mult, kind="half") circuit.append(adder, carry_qubits_mult_1[:] + carry_qubits_mult_2[:] + carry_qubit_addition[:]) # inequality check if in circle s = 2 ** (bits_per_input) - 1 comparer = IntegerComparator(num_bits_after_mult + 1, s * s + 1, False) circuit.append(comparer, carry_qubits_mult_2[:] + carry_qubit_addition[:] + carry_qubits_comparer[:]) # readout if useQAE == False: circuit.measure(nQubits - num_bits_comparer, 0) return circuit def get_circuit(**kwargs): bits_per_input =1 # num qubits per number useQAE =True circuit =operator(bits_per_input,[],[],useQAE) #circuit.draw('mpl') #backend = FakeMontreal() #circuit_transpiled = transpile(circuit,backend) #circuit_transpiled.draw('mpl') #circuit_transpiled.depth() backend =Aer.get_backend('qasm_simulator') circuit_to_return = None if useQAE == True: quantum_instance = Aer.get_backend('qasm_simulator') num_bits_after_mult = 2 * bits_per_input num_bits_comparer =num_bits_after_mult+1 nQubits=4*bits_per_input + 2*num_bits_after_mult+1 +num_bits_comparer problem = EstimationProblem( state_preparation=circuit.decompose(), # A operator objective_qubits=[nQubits-num_bits_comparer], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) print(f"Depth: ", circuit.depth()) print(f"Width: ", circuit.num_qubits) ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy quantum_instance=quantum_instance, ) iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval quantum_instance=quantum_instance, ) circuit_to_return = iae.construct_circuit(problem, measurement=True).decompose() print(circuit_to_return) result =iae.estimate(problem) print(result) else: shots =1000 job= execute(circuit,backend=backend,shots=shots) counts =job.result().get_counts() print(counts) #print(4 * counts['1'] /shots ) return circuit_to_return
https://github.com/googlercolin/Qiskit-Course
googlercolin
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * provider = IBMQ.load_account() def lab1_ex1(): qc = QuantumCircuit(1) qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) def lab1_ex2(): qc = QuantumCircuit(1) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) def lab1_ex3(): qc = QuantumCircuit(1) qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) def lab1_ex4(): qc = QuantumCircuit(1) qc.x(0) qc.h(0) qc.s(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement qc.h(0) qc.x(1) qc.cx(0,1) return qc qc = lab1_ex5() qc.draw() # we draw the circuit qc.measure_all() # we measure all the qubits backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): qc = QuantumCircuit(3,3) qc.x(0) qc.h(0) qc.x(1) qc.x(2) qc.cx(0,1) qc.cx(1,2) return qc qc = lab1_ex6() qc.draw() # we draw the circuit oraclenr = 2 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1011' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 # put your answer here, then uncomment max_nr_inputs = (2**n)/2 + 1 # put your answer here, then uncomment return [min_nr_inputs, max_nr_inputs] n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) qc.x(4) qc.h(4) qc.barrier() return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = (|00000> - |10000>)/sqrt(2) state qc = psi_0(n) # create the superposition state |psi_1> for i in range(4): qc.h(i) return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate for i in range(n): qc.h(i) qc.barrier() # add the measurement by connecting qubits to classical bits for j in range(n): qc.measure(j, j) return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print('least busy backend: ', backend) %qiskit_job_watcher job = execute(dj_circuit, backend=backend, shots=1024, optimization_level=3) # Get results of computation results = job.result() answer = results.get_counts() plot_histogram(answer) # Jobs I ran before backend = provider.get_backend('ibmq_quito') old_job = backend.retrieve_job('61cbfe7be867009014a0362e') results = old_job.result() answer = results.get_counts() plot_histogram(answer)
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit(2) qc.x(1) qc.draw("mpl") state = Statevector.from_instruction(qc) state.draw('bloch')
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from virtual_swap.deprecated.cns_sa import VSwapPass from qiskit import QuantumCircuit from qiskit.quantum_info import Operator qc = QuantumCircuit(3) qc.cx(0, 1) qc.h(1) qc.iswap(1, 2) qc.y(2) original_op = Operator(qc) qc.draw("mpl") from qiskit.converters import circuit_to_dag dag = circuit_to_dag(qc) dag.draw() # manually select the first cx node from qiskit.circuit.library.standard_gates import CXGate, iSwapGate h_node = dag.op_nodes(iSwapGate)[0] import numpy as np # cx -> iswap cx_replace = QuantumCircuit(2, 0) cx_replace.h(1) cx_replace.rz(-np.pi / 2, 0) cx_replace.rz(-np.pi / 2, 1) cx_replace.iswap(0, 1) cx_replace.h(0) cx_replace.draw("mpl") # iswap -> cx iswap_replace = QuantumCircuit(2, 0) iswap_replace.rz(np.pi / 2, 0) iswap_replace.rz(np.pi / 2, 1) iswap_replace.h(1) iswap_replace.cx(0, 1) iswap_replace.h(1) from qiskit.dagcircuit import DAGOpNode, DAGInNode, DAGOutNode, DAGCircuit from qiskit.circuit.library import iSwapGate, SwapGate def cns_transform(dag: DAGCircuit, h_node): """Alternative implementation, adds nodes into blank copy of dag""" new_dag = dag.copy_empty_like() flip_flag = False swap_wires = { qarg1: qarg2 for qarg1, qarg2 in zip(h_node.qargs, h_node.qargs[::-1]) } for node in dag.topological_op_nodes(): if node == h_node: if node.name == "cx": new_dag.apply_operation_back(cx_replace.to_instruction(), node.qargs) elif node.name == "iswap": new_dag.apply_operation_back(iswap_replace.to_instruction(), node.qargs) else: raise ValueError("Unsupported operation") flip_flag = True else: if flip_flag: new_dag.apply_operation_back( node.op, [swap_wires.get(qarg, qarg) for qarg in node.qargs] ) else: new_dag.apply_operation_back(node.op, node.qargs) # fix with a swap new_dag.apply_operation_back(SwapGate(), h_node.qargs) return new_dag def cns_transform_old(dag, h_node): swap_wires = { qarg1: qarg2 for qarg1, qarg2 in zip(h_node.qargs, h_node.qargs[::-1]) } # NOTE, include the node itself, because we want to reference set of all outgoing edges node_list = list(dag.descendants(h_node)) node_list.insert(0, h_node) for source in node_list: # first, update edge arguments for target in dag.successors(source): edge = dag._multi_graph.get_edge_data(source._node_id, target._node_id) dag._multi_graph.update_edge( source._node_id, target._node_id, swap_wires.get(edge, edge) ) # second, update the node's qargs if source == h_node: # here replace the operation... if source.name == "cx": dag.substitute_node(source, cx_replace.to_instruction()) elif source.name == "iswap": dag.substitute_node(source, iswap_replace.to_instruction()) else: raise ValueError("Unsupported operation") # third, update output nodes elif isinstance(source, DAGOpNode): source.qargs = [swap_wires.get(qarg, qarg) for qarg in source.qargs] elif isinstance(source, DAGOutNode): source.wire = swap_wires.get(source.wire, source.wire) # add a swap a swap at end of circuit # NOTE, preserves unitary for equivalence checks # final SWAP gates can be removed by the optimizer dag.apply_operation_back(SwapGate(), h_node.qargs) dag = cns_transform(dag, h_node) # cns_transform_old(dag, h_node) dag.draw() from qiskit.converters import dag_to_circuit qc = dag_to_circuit(dag) # transpile into iswap, cx, u basis from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller pm = PassManager([Unroller(["swap", "iswap", "cx", "u"])]) qc = pm.run(qc) qc.draw("mpl") # verify circuits are equivalent from qiskit.quantum_info import Operator original_op.equiv(Operator(qc)) # get first cx node from qc dag = circuit_to_dag(qc) cx_node = dag.op_nodes(CXGate) from virtual_swap.cns_transform import cns_transform new_dag = cns_transform(dag, *cx_node, preserve_layout=True) new_qc = dag_to_circuit(new_dag) new_qc.draw("mpl")
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 job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution() plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5)) G labels = nx.get_edge_attributes(G,'weight') labels import json # Array of JSON Objects products = [{"name": "HDD", "brand": "Samsung", "price": "$100"}, {"name": "Monitor", "brand": "Dell", "price": "$120"}, {"name": "Mouse", "brand": "Logitech", "price": "$10"}] # Print the original data print("The original JSON data:\n{0}".format(products)) # Sort the JSON data based on the value of the brand key products.sort(key=lambda x: x["price"]) # Print the sorted JSON data print("The sorted JSON data based on the value of the brand:\n{0}".format(products)) _LAMBDA UNIFORM_CONVERGENCE_SAMPLE import json # Array of JSON Objects # Sort the JSON data based on the value of the brand key UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"]) # Print the sorted JSON data UNIFORM_CONVERGENCE_SAMPLE np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"]) # generamos las distancias entre para la convergencia uniforme index = -1 for sample in UNIFORM_CONVERGENCE_SAMPLE: mean = sample["mean"] index += 1 distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"])) UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state UNIFORM_CONVERGENCE_SAMPLE import csv header = ['iteration', 'state', 'probability', 'mean'] header_q = ['iteration', 'distance'] with open('qaoa_cu.csv', 'w', encoding='UTF8') as f: with open('qaoa_distance.csv', 'w', encoding='UTF8') as q: writer = csv.writer(f) writer_q = csv.writer(q) # write the header writer.writerow(header) writer_q.writerow(header_q) iteration = 0 for sample in UNIFORM_CONVERGENCE_SAMPLE: iteration += 1 mean = sample["mean"] distance = sample["distance_pgs"] state = 0 for probability in sample["probabilities"]: state += 1 # write the data data = [iteration, state, probability, mean] writer.writerow(data) writer_q.writerow([iteration, distance]) #plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png") #print(sample["mean"]) plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
https://github.com/hugoecarl/TSP-Problem-Study
hugoecarl
import math import matplotlib.pyplot as plt %matplotlib inline class TSP: def __init__(self): self.flat_mat = flat_mat self.n = 0 self.melhor_dist = 1e11 self.pontos = [] self.melhores_pontos = [] def busca_exaustiva(self, flat_mat, n, ite): if ite == n: dist = 0 for j in range(1, n): dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]] dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]] if dist < self.melhor_dist: self.melhor_dist = dist self.melhores_pontos = self.pontos[:] return for i in range(n): if self.pontos[i] == -1: self.pontos[i] = ite self.busca_exaustiva(flat_mat, n, ite + 1) self.pontos[i] = -1 def dist_mat(self): x = [] y = [] flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo. while True: try: temp = input("Digite a coordenada x y: ").split() x.append(float(temp[0])) y.append(float(temp[1])) except: break for i in range(len(x)): for j in range(len(y)): flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2)) return flat_mat, x, y def get_results(self): self.flat_mat, x, _ = self.dist_mat() self.n = len(x) self.pontos = [-1]*self.n self.pontos[0] = 0 self.busca_exaustiva(self.flat_mat, self.n, 1) return self.melhor_dist, self.melhores_pontos Tsp = TSP() distancia, pontos = Tsp.get_results() print("Melhor distancia encontrada: ", distancia) print("Melhor caminho encontrado: ", pontos) #plota gráfico def connectpoints(x,y,p1,p2): x1, x2 = x[p1], x[p2] y1, y2 = y[p1], y[p2] plt.plot([x1,x2],[y1,y2],'ro-') for i in range(1, len(pontos)): connectpoints(x,y,pontos[i-1],pontos[i]) connectpoints(x,y,pontos[len(x)-1],pontos[0]) plt.title("Percurso") plt.show() %%time %%cmd python TSP.py < in-1.txt type out-1.txt python TSP.py < in-2.txt type out-2.txt python TSP.py < in-3.txt type out-3.txt python TSP.py < in-4.txt type out-4.txt from qiskit import IBMQ import numpy as np #IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente') IBMQ.load_account() from qiskit import Aer from qiskit.tools.visualization import plot_histogram from qiskit.circuit.library import TwoLocal from qiskit.optimization.applications.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua import aqua_globals from qiskit.aqua import QuantumInstance from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.optimization.algorithms import MinimumEigenOptimizer from qiskit.optimization.problems import QuadraticProgram import logging from qiskit.aqua import set_qiskit_aqua_logging #Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits coord = [] flat_mat, x, y = TSP().dist_mat() dist_mat = np.array(flat_mat).reshape(len(x),len(x)) for i, j in zip(x, y): coord.append([i,j]) ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat) qubitOp, offset = tsp.get_operator(ins) print('Offset:', offset) print('Ising Hamiltonian:') print(qubitOp.print_details()) #Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica ee = NumPyMinimumEigensolver(qubitOp) result = ee.run() print('energy:', result.eigenvalue.real) print('tsp objective:', result.eigenvalue.real + offset) x_Q = sample_most_likely(result.eigenstate) print('feasible:', tsp.tsp_feasible(x_Q)) z = tsp.get_tsp_solution(x_Q) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w)) for i in range(1, len(z)): connectpoints(x,y,z[i-1],z[i]) connectpoints(x,y,z[len(x)-1],z[0]) plt.title("Percurso") plt.show() #instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica provider = IBMQ.get_provider(hub = 'ibm-q') device = provider.get_backend('ibmq_16_melbourne') aqua_globals.random_seed = np.random.default_rng(123) seed = 10598 backend = Aer.get_backend('qasm_simulator') #descomentar essa linha caso queira rodar na maquina real #backend = device quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) #rodando no simulador quantico spsa = SPSA(maxiter=10) ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance) result = vqe.run(quantum_instance) print('energy:', result.eigenvalue.real) print('time:', result.optimizer_time) x = sample_most_likely(result.eigenstate) print('feasible:', tsp.tsp_feasible(x_Q)) z = tsp.get_tsp_solution(x_Q) print('solution:', z) print('solution objective:', tsp.tsp_value(z, ins.w))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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/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. """BasicAer Backends Test.""" from qiskit import BasicAer from qiskit.providers.basicaer import BasicAerProvider from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.test import providers class TestBasicAerBackends(providers.ProviderTestCase): """Qiskit BasicAer Backends (Object) Tests.""" provider_cls = BasicAerProvider backend_name = "qasm_simulator" def test_deprecated(self): """Test that deprecated names map the same backends as the new names.""" def _get_first_available_backend(provider, backend_names): """Gets the first available backend.""" if isinstance(backend_names, str): backend_names = [backend_names] for backend_name in backend_names: try: return provider.get_backend(backend_name).name() except QiskitBackendNotFoundError: pass return None deprecated_names = BasicAer._deprecated_backend_names() for oldname, newname in deprecated_names.items(): expected = ( "WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. " "Use '%s'." % (oldname, newname) ) with self.subTest(oldname=oldname, newname=newname): with self.assertLogs("qiskit.providers.providerutils", level="WARNING") as context: resolved_newname = _get_first_available_backend(BasicAer, newname) real_backend = BasicAer.get_backend(resolved_newname) self.assertEqual(BasicAer.backends(oldname)[0], real_backend) self.assertEqual(context.output, [expected]) def test_aliases_fail(self): """Test a failing backend lookup.""" self.assertRaises(QiskitBackendNotFoundError, BasicAer.get_backend, "bad_name") def test_aliases_return_empty_list(self): """Test backends() return an empty list if name is unknown.""" self.assertEqual(BasicAer.backends("bad_name"), [])
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_st_qcs), ")") t3_st_qcs[-1].draw("mpl") # only view trotter gates # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") shots = 8192 reps = 8 jobs = [] for _ in range(reps): # execute job = execute(t3_st_qcs, backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout) print('Job ID', cal_job.job_id()) dt_now = datetime.datetime.now() print(dt_now) with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') # set the target state target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: # mit_results = meas_fitter.filter.apply(job.result()) # apply QREM rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/pranavdurai10/quantum-gates
pranavdurai10
''' /////////////////////////////////////////////////////////////////////////// Code written by Pranav Durai for Quantum Computer on 27.05.2023 @ 22:41:54 Component: Pauli-X-Gate (bit-flip-gate) Framework: Qiskit 0.43.0 /////////////////////////////////////////////////////////////////////////// ''' # Import necessary libraries from qiskit import QuantumCircuit, Aer, execute # Create a quantum circuit with one qubit circuit = QuantumCircuit(1) # Apply Pauli-X gate to the qubit circuit.x(0) # Measure the qubit circuit.measure_all() # Simulate the circuit using the local Aer simulator simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1) # Get the result result = job.result() counts = result.get_counts(circuit) # Print the measurement outcome print("Measurement outcome:", list(counts.keys())[0])
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
SaashaJoshi
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# consider the following list with 4 elements L = [1,-2,0,5] print(L) # 3 * v v = [1,-2,0,5] print("v is",v) # we use the same list for the result for i in range(len(v)): v[i] = 3 * v[i] print("3v is",v) # -0.6 * u # reinitialize the list v v = [1,-2,0,5] for i in range(len(v)): v[i] = -0.6 * v[i] print("0.6v is",v) u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] result=[] for i in range(len(u)): result.append(u[i]+v[i]) print("u+v is",result) # let's also print the result vector similarly to a column vector print() # print an empty line print("the elements of u+v are") for j in range(len(result)): print(result[j]) from random import randrange # # your solution is here # #r=randrange(-10,11) # randomly pick a number from the list {-10,-9,...,-1,0,1,...,9,10} # # your solution is here # v = [-1,-3,5,3,1,2] length_square=0 for i in range(len(v)): print(v[i],":square ->",v[i]**2) # let's print each entry and its square value length_square = length_square + v[i]**2 # let's sum up the square of each entry length = length_square ** 0.5 # let's take the square root of the summation of the squares of all entries print("the summation is",length_square) print("then the length is",length) # for square root, we can also use built-in function math.sqrt print() # print an empty line from math import sqrt print("the square root of",length_square,"is",sqrt(length_square)) # # your solution is here # # # your solution is here #
https://github.com/abbarreto/qiskit4
abbarreto
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver() problem = driver.run() print(problem) from qiskit_nature.second_q.problems import ElectronicBasis driver.run_pyscf() problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True) print(problem.basis) ao_problem = driver.to_problem(basis=ElectronicBasis.AO) print(ao_problem.basis) from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem qcschema = driver.to_qcschema() ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO) from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema basis_transformer = get_ao_to_mo_from_qcschema(qcschema) mo_problem = basis_transformer.transform(ao_problem) print(mo_problem.basis) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import qiskit_metal as metal from numpy import pi from scipy.constants import c, h, pi, hbar, e, mu_0, epsilon_0 from qiskit_metal import Dict from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) #project parameters: L_JJ = 10 # nH C_JJ = 2 # fF f_r = 8 # GHz Z_r = 50 # Ohm v_r = 0.404314 # relative velocity to c #parameter extraction: eps_eff = (1/v_r)**2 # effective eps_r eps_r = 2*eps_eff-1 # approximation I_JJ = varphi0/(L_JJ*1e-9)/1e-9 # nA E_JJ = (varphi0)**2/(L_JJ*1e-9)/h/1e9 # GHz #print print(eps_r, I_JJ, E_JJ) QuantumSystemRegistry.registry() capfile = ws_path+"/Transmon_Readout_CapMatrix.txt" t1_mat, _, _, _ = load_q3d_capacitance_matrix(capfile) t1_mat opt1 = dict( cap_mat = t1_mat, ind_dict = {('pad_top_Q1', 'pad_bot_Q1'): L_JJ}, # junction inductance in nH jj_dict = {('pad_top_Q1', 'pad_bot_Q1'): 'j1'}, cj_dict = {('pad_top_Q1', 'pad_bot_Q1'): C_JJ}, # junction capacitance in fF ) cell_1 = Cell(opt1) transmon1 = Subsystem(name='transmon1', sys_type='TRANSMON', nodes=['j1']) trans_read = Subsystem(name='readout1', sys_type='TL_RESONATOR', nodes=['readout_connector_pad_Q1'], q_opts=dict(f_res = f_r, Z0=Z_r, vp=v_r*c)) composite_sys = CompositeSystem( subsystems=[transmon1, trans_read], cells=[cell_1], grd_node='ground_main_plane', nodes_force_keep=['readout_connector_pad_Q1'] ) cg = composite_sys.circuitGraph() print(cg) hilbertspace = composite_sys.create_hilbertspace() print(hilbertspace) hilbertspace = composite_sys.add_interaction() hilbertspace.hamiltonian() hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30) composite_sys.compute_gs()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
import sys print(sys.executable) import qiskit qiskit.__qiskit_version__ from qiskit import IBMQ IBMQ.save_account('fb335ef56b1d6d43894ad997ae54daf329de8050cda1e2e7a795f9bcae2da2e84ad903bd320d6e1354214371bcf9af7a80c1ccc1e0a546947469913805528928') IBMQ.load_account() import qiskit as q %matplotlib inline circuit=q.QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1],[0,1]) circuit.draw() circuit.draw(output="mpl") from qiskit import IBMQ provider=IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count=len(backend.properties().qubits) except: qubit_count="simulated" print(f"{backend.name()}has{backend.status().pending_jobs}queued and␣{qubit_count}qubits") from qiskit.tools.monitor import job_monitor backend=provider.get_backend("ibmq_lima") job=q.execute(circuit,backend=backend,shots=1024) job_monitor(job) from qiskit.visualization import plot_histogram from matplotlib import style style.use("dark_background") result=job.result() count=result.get_counts(circuit) plot_histogram([count]) backend=provider.get_backend("ibmq_qasm_simulator") circuit=q.QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1],[0,1]) circuit.draw() job=q.execute(circuit,backend=backend,shots=1024) job_monitor(job) from qiskit.visualization import plot_histogram from matplotlib import style style.use("dark_background") result=job.result() count=result.get_counts(circuit) plot_histogram([count]) from qiskit import Aer sim_backend=Aer.get_backend("qasm_simulator") for backend in Aer.backends(): print(backend) job=q.execute(circuit,backend=sim_backend,shots=1024) job_monitor(job) from qiskit.visualization import plot_histogram from matplotlib import style style.use("dark_background") result=job.result() count=result.get_counts(circuit) plot_histogram([count]) from qiskit import * circuit=QuantumCircuit(3,3) %matplotlib inline from qiskit.tools.visualization import plot_histogram from qiskit.tools.visualization import plot_bloch_multivector from qiskit.tools.visualization import plot_state_qsphere # QFT # Initialize the 3-qubit quantum circuit # Set the state '110' s = '110' num_qubits = len(s) qc = QuantumCircuit(num_qubits) # Set reverse ordering s = s[::-1] # Construct the state 110 for idx in range(num_qubits): if s[idx] == '1': qc.x(idx) qc.barrier() qc.draw() circuit.draw(output='mpl') # Import the value pi for our rotations from numpy import pi # Always start from the most significant qubit, # in this case it's q2. # Step 1, add a Hadamard gate qc.h(2) # Step 2, add CROT gates from most significant qubit qc.cu1(pi/2,1,2) # Step 3, add another CROT from 2 to the next qubit down, # while doubling the phase denominator qc.cu1(pi/4, 0, 2) # Draw the circuit qc.draw() # Now that we finished from 2 down to 0 # We'll drop to the next least significant qubit and # start again, # Step 1, add a Hadamard gate qc.h(1) # Step 2, add Control Rotation (CROT) gates from most # significant towards # least significant starting a pi/2, and doubling the # denominator # as you go down each qubit. qc.cu1(pi/2, 0, 1) # Draw the circuit qc.draw() # Now that we finished from 1 down to 0 # We'll drop to the next least significant qubit and # Start again # Step 1, add a Hadamard gate qc.h(0) # Since we are at the least significant qubit, we are # done! # Draw the circuit qc.draw() # Define a function which will add the swap gates to the # outer # pair of qubits def add_swap_gates(qc_swaps,qubits): for qubit in range(qubits//2): qc-swaps.swap(qubit, qubit-qubit-1) return qc_swaps qft_circuit=add_swap_gates(qc, num, qubits) qft_circuit.draw() # Get the state vector simulator to view our final QFT # state backend = Aer.get_backend("statevector_simulator") # Execute the QFT circuit and visualize the results statevector = execute(qft_circuit,backend=backend).result().get_statevector() plot_bloch_multivector(statevector) plot_state_qsphere(statevector)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
#Import general libraries (needed for functions) import numpy as np import matplotlib.pyplot as plt from IPython import display #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 RB Functions import qiskit.ignis.verification.randomized_benchmarking as rb #Generate RB circuits (2Q RB) #number of qubits nQ=2 rb_opts = {} #Number of Cliffords in the sequence rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175] #Number of seeds (random sequences) rb_opts['nseeds'] = 5 #Default pattern rb_opts['rb_pattern'] = [[0,1]] rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts) print(rb_circs[0][0]) # Create a new circuit without the measurement qc = qiskit.QuantumCircuit(*rb_circs[0][-1].qregs,*rb_circs[0][-1].cregs) for i in rb_circs[0][-1][0:-nQ]: qc._attach(i) # The Unitary is an identity (with a global phase) backend = qiskit.Aer.get_backend('unitary_simulator') basis_gates = ['u1','u2','u3','cx'] # use U,CX for now basis_gates_str = ','.join(basis_gates) job = qiskit.execute(qc, backend=backend, basis_gates=basis_gates_str) print(np.around(job.result().get_unitary(),3)) # Run on a noisy simulator noise_model = NoiseModel() # Depolarizing_error dp = 0.002 noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 1), ['u1', 'u2', 'u3']) noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 2), 'cx') backend = qiskit.Aer.get_backend('qasm_simulator') qobj_list = [] # Create the RB fitter rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern']) for rb_seed,rb_circ_seed in enumerate(rb_circs): qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str) job = backend.run(qobj, noise_model=noise_model) qobj_list.append(qobj) # Add data to the fitter rb_fit.add_data(job.result()) print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc'])) plt.figure(figsize=(8, 6)) ax = plt.subplot(1, 1, 1) # Plot the essence by calling plot_rb_data rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False) # Add title and label ax.set_title('%d Qubit RB'%(nQ), fontsize=18) plt.show() #Count the number of single and 2Q gates in the 2Q Cliffords gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0]) for i in range(len(basis_gates)): print("Number of %s gates per Clifford: %f"%(basis_gates[i], np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]]))) # Prepare lists of the number of qubits and the errors ngates = np.zeros(7) ngates[0:3] = gates_per_cliff[0][0:3] ngates[3:6] = gates_per_cliff[1][0:3] ngates[6] = gates_per_cliff[0][3] gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int) gate_errs = np.zeros(len(gate_qubits)) gate_errs[[1,4]] = dp/2 #convert from depolarizing error to epg (1Q) gate_errs[[2,5]] = 2*dp/2 #convert from depolarizing error to epg (1Q) gate_errs[6] = dp*3/4 #convert from depolarizing error to epg (2Q) #Calculate the predicted epc pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs) print("Predicted 2Q Error per Clifford: %e"%pred_epc)
https://github.com/anpaschool/quantum-computing
anpaschool
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), ] ) from qiskit.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers 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}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shaimayshah/Quantum-Global-Public-Goods-Game
shaimayshah
from qiskit import * import numpy as np from functools import partial from qiskit.aqua.components.optimizers import COBYLA from scipy.optimize import minimize, fmin_slsqp import pandas as pd import matplotlib.pyplot as plt %matplotlib inline theta = np.array([0.5, np.pi*2, 1.4, 1/3, np.pi/2, 1.3, 1.4, 0.22, 1.2, 0.99, 1.0, 0.23, 0.14, 0.90, np.pi]) def run_quantum_circ(n, theta): ''' This creates a quantum circuit with n qubits. ''' qr = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qr, cr) #Applies Hadamard Gate to first circuit.h(0) #Entangles the qubits for i in range(n-1): circuit.cx(i, i+1) # For ease of understanding circuit.barrier() # Applying U3 gates -- later i = 0 for i in range(n): circuit.u3(theta[3*i], theta[(3*i)+1], theta[(3*i)+2], i) circuit.barrier() # Unentangling qubits for i in reversed(range(n)): if i-1==-1: break else: circuit.cx(i-1, i) circuit.h(0) circuit.barrier() # Measuring the values for i in range(n-1): circuit.measure(i, i) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=10000).result() return result.get_counts() theta_c = np.array([np.pi*2, np.pi/2, 0.22, 1.0, 0.90]) def run_classical_circ(n, theta): ''' This creates a quantum circuit with n qubits. ''' qr = QuantumRegister(n) cr = ClassicalRegister(n) circuit = QuantumCircuit(qr, cr) # For ease of understanding circuit.barrier() # Applying U3 gates -- later i = 0 for i in range(n): circuit.u2(theta[i], 0, i) circuit.barrier() # Measuring the values for i in range(n-1): circuit.measure(i, i) backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=10000).result() return result.get_counts() # Translate from dictionary to sorted values. def dic_to_vec(dic): ''' Converts to dictionary outputted by the quantum/classical circuit to a 2^n dimensional (dim = 32) vector. ''' scores = np.zeros(32) num_shots = 10000 for key in dic.keys(): i = int(key,2) scores[i] = dic[key]/num_shots return scores # The Payoff matrix -- made it here at random v1 = np.random.rand(5,1)*np.random.rand(1) v2 = np.random.rand(1,32) payoff_mat = np.matmul(v1,v2) def payoff_finder(result, payoff): ''' Input: results from quantum/classical calc (32x1), payoff matrix. Output: payoff matrix for that particular ''' return np.matmul(payoff, result) def quantum_cost_function(n, rand_payoff_mat, theta): ''' Input: number of qubits, initial values of theta, the payoff matrix you've generated Output: a singular number that represents how large the difference between the standard deviation and L1 norm. ''' # Runs the quantum circuit and returns a dictionary of values. dic = run_quantum_circ(n, theta) vec = dic_to_vec(dic) payoff_vec = payoff_finder(vec, rand_payoff_mat) val = np.linalg.norm(payoff_vec, ord = 1) - np.std(payoff_vec) return -val #quantum_cost_function(5,theta,payoff_mat) def classical_cost_function(n, rand_payoff_mat, theta): ''' Input: number of qubits, initial values of theta, the payoff matrix you've generated Output: a singular number that represents how large the difference between the standard deviation and L1 norm. ''' dic = run_classical_circ(n, theta) vec = dic_to_vec(dic) payoff_vec = payoff_finder(vec, rand_payoff_mat) val = np.linalg.norm(payoff_vec, ord = 1) - np.std(payoff_vec) return -val vals = [] def callback(res): params.append(res) def callback_classic(res): params_c.append(res) #backup_params = params params = [] qcost = partial(quantum_cost_function, 5, payoff_mat) results = minimize(qcost, theta, method='Nelder-Mead', callback = callback)#, tol=1e-9) results params_c = [] ccost = partial(classical_cost_function, 5, payoff_mat) results_c = minimize(ccost, theta_c, method='Nelder-Mead', callback = callback_classic) results_c vals = [] for param in params: vals.append(0-quantum_cost_function(5, payoff_mat, param)) vals_c = [] for param in params_c: vals_c.append(0-classical_cost_function(5, payoff_mat, param)) max_c = np.asarray(vals_c).max() max_q = np.asarray(vals).max() with plt.xkcd(): plt.plot(list(range(len(vals))), vals, label="quantum strategy") plt.plot(list(range(len(vals_c))), vals_c, color='r', label = "classical strategy") #plt.axhline(max_c, color='r', ls='--', label = 'Maximum quantum value reached') #plt.axhline(max_q, color='b', ls='--', label = 'Maximum classical value reached') plt.xlabel('Iterations') plt.ylabel('Maximization Function') plt.legend()
https://github.com/rmlarose/qcbq
rmlarose
#!pip install qiskit # Do the usual setup, but without classical registers or measurement import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute qr = QuantumRegister(1) circ = QuantumCircuit(qr) # Place an Ry gate with a −3π/4 rotation circ.ry(-3/4 * np.pi, qr[0]) # Draw the circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circ, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector quantum_state # Plot the state vector on a Bloch sphere from qiskit.tools.visualization import plot_bloch_multivector plot_bloch_multivector(quantum_state) # Do the usual setup, but without classical registers or measurement import numpy as np from qiskit import QuantumCircuit, QuantumRegister, execute qr = QuantumRegister(1) circ = QuantumCircuit(qr) # Place gates that will achieve the desired state # Draw the circuit circ.draw(output='mpl') # Use the BasicAer statevector_simulator backend from qiskit import BasicAer backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circ, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circ, decimals=3) # Output the quantum state vector quantum_state # Plot the state vector on a Bloch sphere from qiskit.tools.visualization import plot_bloch_multivector plot_bloch_multivector(quantum_state)
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. """DAGFixedPoint pass testing""" import unittest from qiskit.transpiler.passes import DAGLongestPath from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase class TestDAGLongestPathPass(QiskitTestCase): """Tests for PropertySet methods.""" def test_empty_dag_true(self): """Test the dag longest path of an empty dag.""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = DAGLongestPath() pass_.run(dag) self.assertListEqual(pass_.property_set["dag_longest_path"], []) def test_nonempty_dag_false(self): """Test the dag longest path non-empty dag. path length = 11 = 9 ops + 2 qubits at start and end of path """ # ┌───┐┌───┐┌───┐ # q0_0: ──■──┤ X ├┤ Y ├┤ H ├──■───────────────────■── # ┌─┴─┐└───┘└───┘└───┘┌─┴─┐┌───┐┌───┐┌───┐┌─┴─┐ # q0_1: ┤ X ├───────────────┤ X ├┤ X ├┤ Y ├┤ H ├┤ X ├ # └───┘ └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.x(qr[0]) circuit.y(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.x(qr[1]) circuit.y(qr[1]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = DAGLongestPath() pass_.run(dag) self.assertEqual(len(pass_.property_set["dag_longest_path"]), 11) if __name__ == "__main__": unittest.main()
https://github.com/SamperQuinto/QisKit
SamperQuinto
import numpy as np from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister from qiskit.quantum_info import * # Creamos los registros del circuito de corrección de errores qreg_state = QuantumRegister(1,'state') qreg_sup = QuantumRegister(2,'ancila_sup') qreg_inf = QuantumRegister(2,'ancila_inf') creg= ClassicalRegister(4,'sindrome') # Creamos el circuito cuántico para la codificación y decodificación circ = QuantumCircuit(qreg_sup,qreg_state,qreg_inf,creg) circ_state = QuantumCircuit(qreg_sup,qreg_state,qreg_inf,creg) state = [1/np.sqrt(3), np.sqrt(2/3)] #state = random_statevector(2) # Inicializamos el circuito circ_state.initialize(state, 2) circ_state.barrier() circ_state.draw() from qiskit.circuit.library.standard_gates.z import ZGate # Procedemos con la construcción del circuito cuántico asociado: circ.h(0) circ.h(1) circ.h(3) circ.cz(1,4) circ.cz(2,4) circ.cz(3,4) circ.cz(1,4, ctrl_state=0) circ.cz(2,4) circ.cz(3,4, ctrl_state=0) circ.cx(2,4) circ.cx(0,2) circ.cx(0,4) circ.cx(3,2) circ.cx(1,4) circ.cz(2,3) circ.cz(2,4) # Introducimos el error qreg_error = QuantumRegister(5) circ_error = QuantumCircuit(qreg_error) circ_error.barrier() #circ_error.x(2) circ_error.z(2) #Fin del error circ_error.barrier() circ_con_state = circ_state.compose(circ) circ_con_error = circ_con_state.compose(circ_error) circ_inverse = circ.inverse() circ = circ_con_error.compose(circ_inverse) circ.barrier() state_con_error = Statevector.from_instruction(circ) circ.measure([0,1,3,4],[0,1,2,3]) circ.barrier() circ.z(qreg_state[0]).c_if(creg,12) circ.z(qreg_state[0]).c_if(creg,10) circ.z(qreg_state[0]).c_if(creg,1) circ.z(qreg_state[0]).c_if(creg,5) circ.z(qreg_state[0]).c_if(creg,15) circ.z(qreg_state[0]).c_if(creg,6) circ.x(qreg_state[0]).c_if(creg,6) circ.z(qreg_state[0]).c_if(creg,14) circ.x(qreg_state[0]).c_if(creg,14) circ.z(qreg_state[0]).c_if(creg,9) circ.x(qreg_state[0]).c_if(creg,9) circ.z(qreg_state[0]).c_if(creg,13) circ.x(qreg_state[0]).c_if(creg,13) circ.z(qreg_state[0]).c_if(creg,11) circ.x(qreg_state[0]).c_if(creg,11) circ.z(qreg_state[0]).c_if(creg,7) circ.x(qreg_state[0]).c_if(creg,7) circ.draw() from qiskit import Aer, execute from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit_textbook.tools import array_to_latex from qiskit.visualization import * import warnings warnings.filterwarnings("ignore") backend = Aer.get_backend('statevector_simulator') job = execute(circ,backend ,shots = 1000) resultado = job.result() counts = resultado.get_counts(circ) plot_histogram(counts, title = 'sindrome') psi_error=list(filter(lambda x: x != 0, state_con_error)) resultado_sv = job.result().get_statevector() resultado_psi=list(filter(lambda x: x != 0, resultado_sv)) psi_error=list(filter(lambda x: x != 0, state_con_error)) display(array_to_latex(state, prefix= 'Estado \; original \; |\\Psi \\rangle=')) display(array_to_latex(psi_error, prefix= 'Estado \; con \; error \; |\\Psi \\rangle=')) display(array_to_latex(resultado_psi, prefix = 'Estado \; corregido \; |\\Psi \\rangle='))
https://github.com/QForestCommunity/launchpad
QForestCommunity
from pyqubo import Spin, solve_ising x1, x2, x3 = Spin("x1"), Spin("x2"), Spin("x3") Quad_form = 2*(x1) + x2 - 3*(x3) model = Quad_form.compile() deg1, deg2, off = model.to_ising() print('Degree1:',deg1,' Degree2:',deg2,' Offset:',off) res = solve_ising(deg1,deg2) print(res) shots = 10 #variable used to specify number of times you want to solve the model ans = [] for i in range(shots): res = solve_ising(deg1, deg2) ans.append(res) result = ans[0] maxim = 0 for i in ans: freq = ans.count(i) if freq>maxim: maxim = freq result = i print(str(result))
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 16 K = 4 NUM_SHOTS = 1024 NUM_ITERATIONS = 50 w = 0.5 approximated_energies = [] from qiskit import IBMQ provider = IBMQ.enable_account('4cd532424f249f20233857b3b211eb28dfc0e790386bd2ea14d3e0d03c867dfcfec4c2c968e4693f1c9caf7b3f6fad3f6a6393065fb45719692fd1a5177536cb') real_backend = provider.get_backend('ibmq_belem') from scipy.optimize import minimize from utiles import * input_states = get_first_k_eigenvectors_from_n_computational_basis(K, N) from ansatz_circuit_item2 import get_full_variational_quantum_circuit init_circuit_params = { "thetas": np.random.uniform(low=0, high=2*np.pi, size=8), "phis": np.random.uniform(low=0, high=2*np.pi, size=4), "D1": 2, "D2": 6 } def prepare_circuit_params(thetas) -> Dict: return { "thetas": thetas[4:], "phis": thetas[:4], "D1": 2, "D2": 6 } def get_ansatz_state(circuit_params, input_state): circuit_params_with_input_state = {**circuit_params, "input_state": input_state} return get_full_variational_quantum_circuit(**circuit_params_with_input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, real_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = real_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian): circuit_params = prepare_circuit_params(thetas) computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) k_ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[K-1]) approximated_energey = get_expectation_value(k_ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(approximated_energey) L_w = w*approximated_energey for j in range(K-1): ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[j]) L_w += get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) return L_w def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=12) optimizer_result = minimize(cost_function,x0=initial_thetas,args=(hamiltonian),method="BFGS",options={"maxiter":NUM_ITERATIONS}) optimal_thetas = prepare_circuit_params(optimizer_result.x) return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian) print(optimal_thetas) computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N) optimal_ansatz_state = get_ansatz_state(optimal_thetas, computational_eigenvectors[K-1]) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_k_exact_eigenvalue_of_hamiltonian(hamiltonian, k): eigen_values = LA.eig(hamiltonian.to_matrix())[0] print(sorted(eigen_values, reverse=True)) return sorted(eigen_values,reverse=True)[k-1] def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_k_exact_eigenvalue_of_hamiltonian(hamiltonian, K) print("Exact Eigenvalue:") print(exact_eigenvalue) print("Approximated K Eigenvalues:") print(approximated_eigenvalue) print("Approximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, Y, I, H, S LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits) compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] LiH_approximated_energies = [-7.086471480342895, -7.100658534270067, -7.099715987203259, -7.104706322802394, -7.0881767422400515, -7.094941901238781, -7.101189782415803, -7.091782649949064, -7.095129380762572, -7.089782186084561, -7.103641494347653, -7.08770304365008, -7.097466178879243, -6.927386893001271, -6.918605722866235, -6.929889900623873, -6.929547677497744, -6.9144751585444, -6.92705204011207, -6.928594209576469, -6.918356322098606, -6.922146575259048, -6.928167910638778, -6.920735015129623, -6.934524032800371, -6.9240609972824645, -7.054992091903585, -7.056718682779798, -7.047680065570422, -7.057958949601671, -7.049809365284406, -7.04886498241836, -7.061382947330433, -7.047727314056423, -7.05595544969352, -7.0549833626221155, -7.064687065647647, -7.04480704575676, -7.053986384203245, -7.079305098939433, -7.08780253307097, -7.079683274206787, -7.082864577262481, -7.074313240029014, -7.076075827379148, -7.094328957871822, -7.08496554875689, -7.08017425919163, -7.080091087607597, -7.091782059567345, -7.091247992689509, -7.070866930379006, -7.090286264563848, -7.104283776653907, -7.105507768659804, -7.082013868585181, -7.089272262553638, -7.093947194681023, -7.074106629342778, -7.098394252872861, -7.0959686725785405, -7.07952225336062, -7.095513342542343, -7.09416071736501, -7.096369979461571, -7.099848242069214, -7.084955688773306, -7.100455873892028, -7.093183696883554, -7.0975872306150345, -7.088097397700704, -7.106647897103562, -7.093977686069661, -7.087712543786841, -7.111504280126781, -7.1022363547755125, -7.087493749330183, -7.086287626873361, -7.093369560806178, -7.078161435586905, -7.09441449134148, -7.089607689893512, -7.0932238396900935, -7.111989359310854, -7.104929885548429, -7.091436536609016, -7.08666585935681, -7.082934757346767, -7.101100532138134, -7.088104163062988, -7.096424567809472, -7.099068194469176, -7.092174139685106, -7.093834778605302, -7.102211865551155, -7.093273952141729, -7.098925944110142, -7.094136827312879, -7.096515152172171, -7.106869073487611, -7.105025480517323, -7.08291256775595, -7.090057760157153, -7.101077914837238, -7.098981572929163, -7.103243624466709, -7.081271774215078, -7.113017035519717, -7.081225379146937, -7.116834711504442, -7.095492739824888, -7.092682578748099, -7.101013785481937, -7.1014895178629045, -7.089392729188864, -7.107015846039383, -7.098163688087048, -7.111610506727951, -7.107437432724649, -7.104541043920935, -7.104814557146702, -7.088507490097296, -7.091868681777208, -7.092327160052328, -7.110303366341896, -7.084971369187621, -7.106279269575924, -7.08748298127782, -7.1068551105826145, -7.091008955160712, -7.096443978916333, -7.084657042850862, -7.091138219995237, -7.0998677627359195, -7.0888015973421545, -7.077323969498798, -7.090075437365467, -7.103938600828348, -7.085513121721133, -7.093846377275633, -7.100739101641138, -7.092065649168193, -7.094889058778457, -7.092173541005391, -7.101259881230652, -7.093329510244533, -7.105936945903171, -7.087603313944616, -7.097873442997792, -7.101002397868193, -7.085514640470669, -7.104346225751653, -7.108225666766319, -7.111418621976149, -7.092840805395079, -7.0997679722989115, -7.103255616021782, -7.1174210275723695, -7.102934036335791, -7.094670120993602, -7.0951047953871305, -7.089065125835845, -7.09840645780722, -7.105211057511607, -7.089083299917603, -7.093536455196501, -7.089028853201778, -7.085106562924485, -7.094025566715013, -7.093679961728104, -7.097635614184673, -7.097876397476181, -7.094228767292644, -7.095176655148256, -7.098376263483634, -7.103892028959518, -7.086136465046034, -7.087496098005651, -7.116101776894849, -7.0836112045512705, -7.087318451256026, -7.089288193935741, -7.0990242642314785, -7.095138019651596, -7.098662991437872, -7.094562027567983, -7.099690770432304, -7.10097689047591, -7.103828491824173, -7.095403813862108, -7.092482494208955, -7.0961542900231755, -7.097735395547859, -7.101840243383003, -7.094728079435617, -7.089079166461775, -7.0918303529233695, -7.093445910102374, -7.0824677848419855, -7.088613823891637, -7.094448016211003, -7.102567463647013, -7.093674126629666, -7.107515891897475, -7.091175773435145, -7.099878612823926, -7.108888487835898, -7.0932901938871025, -7.100690499032453, -7.1027627009989205, -7.095985679639996, -7.103159134683138, -7.101594099093457, -7.09708690219646, -7.089839220984511, -7.110835783093937, -7.1106173669768005, -7.105706223928073, -7.101671068636789, -7.093043127308357, -7.107499275434534, -7.098620367705562, -7.101791302589503, -7.093974565602916, -7.100086270996543, -7.103967087697664, -7.096334501266853, -7.093197040678562, -7.090566503804324, -7.10777548347143, -7.0940663715743515, -7.079435919407288, -7.1045995778828575, -7.10782600555929, -7.095063062315657, -7.088283716422724, -7.083549548308807, -7.109182438307642, -7.0973139726115155, -7.091323880662006, -7.089267567957862, -7.093801064885492, -7.096478431968507, -7.096450570087517, -7.0834951672860145, -7.105536970385327, -7.091694022844323, -7.0987246829979735, -7.105823728075208, -7.091466927556181, -7.087866391118642, -7.086779542808011, -7.082284206870279, -7.102748671032144, -7.094013649749645, -7.076280227170458, -7.09268421659322, -7.098730097915838, -7.095792848436216, -7.090464809457003, -7.098254342554415, -7.098030162423567, -7.0935066669889375, -7.086557591264656, -7.102526761243724, -7.098181739651888, -7.10872784155506, -7.097459195380401, -7.095191100812662, -7.102890507504376, -7.0923183296893795, -7.102156393269663, -7.09845792437554, -7.096080365452766, -7.10013103533166, -7.1005268316155945, -7.092915662727403, -7.095654857173873, -7.10922258172602, -7.099831667590216, -7.108845117487635, -7.082825083394153, -7.09107742992335, -7.077237571417883, -7.096191060913464, -7.0969085540182455, -7.114145172610189, -7.108437033980985, -7.105356395396853, -7.102301352541805, -7.103938890772344, -7.101405935547222, -7.1113452563763815, -7.0947122361413415, -7.099371225641347, -7.102428612231857, -7.080811315146189, -7.091175823108694, -7.1006602596540445, -7.085633248686943, -7.101715269263441, -7.0835485945728305, -7.0994928231977195, -7.09758387589104, -7.0795693729863505, -7.093444335523969, -7.102404867274401, -7.09942952825781, -7.092772226440181, -7.104709368820088, -7.098167881166478, -7.090812612388616, -7.104342211111905, -7.095634875814595, -7.092173851473915, -7.096806777226616, -7.104061399180975, -7.103310800731109, -7.083274172204216, -7.097915562847112, -7.077818214117743, -7.083628375959302, -7.093476904190158, -7.089513462892567, -7.090304705450007, -7.093392779706353, -7.10554680082769, -7.088962810558666, -7.091859039419992, -7.095055353625999, -7.095717126988325, -7.083592132581408, -7.100324224161871, -7.0785000809768714, -7.105908001716903, -7.093818438314592, -7.098883881335108, -7.104431926558294, -7.099627499021038, -7.092250021905359, -7.0907944678741535, -7.09293707780021, -7.091586685769627, -7.089190047620321, -7.1018597532027385, -7.100262126701205, -7.09131145193086, -7.09482991668717, -7.088031963725242, -7.09771658959787, -7.089270186131905, -7.096846356920972, -7.09686896582669, -7.092845267851078, -7.11130293906202, -7.091518158249563, -7.094435352643231, -7.097573980280066, -7.097401803322267, -7.09679214923423, -7.096140093891424, -7.105779785807971, -7.101284059739653] plot_convergence_of_optimization_process(LiH_approximated_energies, exact_eigenvalue=-7.151525481896562,margin=1) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits) compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] H2_approximated_energies = [-0.6479084750255486, -0.6276579569919597, -0.6079422008169065, -0.616731159779808, -0.6325842283091055, -0.6393897280901208, -0.6171807581727554, -0.632653791572579, -0.6213172282987715, -0.6295655663398093, -0.6289772030449229, -0.6186181091776035, -0.624022941533276, -0.5082839240612291, -0.48226570208794234, -0.4821361107003052, -0.4954020352078101, -0.4793435904590445, -0.49199670120300654, -0.49416478838441447, -0.502190052373643, -0.49599755978221166, -0.5020643548684793, -0.4889205213711024, -0.5018939914800866, -0.5099878400191491, -0.5856552068715944, -0.54923382599589, -0.5582306982767166, -0.5444314531693122, -0.5567710700669415, -0.5659113697818672, -0.552668511160273, -0.5735134318844516, -0.549852476753314, -0.5503189869962759, -0.5601864836520486, -0.5659896127460298, -0.5446950460298908, -0.615920984439197, -0.5928640404070656, -0.5879106801498322, -0.5935911543775607, -0.6075920247035514, -0.6201194518598445, -0.60623970115924, -0.6162790804378995, -0.6070899791213487, -0.6105620077787796, -0.604279338203177, -0.5953765787888684, -0.6176510100281449, -0.6121876903025966, -0.6221925707825862, -0.6167720694769763, -0.6138135616671906, -0.6141332165079305, -0.6280212409220817, -0.6360069982326235, -0.6007258601159454, -0.6251861183198779, -0.6230618384361196, -0.6294049945914133, -0.6233533946933156, -0.608497712991425, -0.6496414061454564, -0.6486467922145787, -0.6248046230879923, -0.6382435950247505, -0.6396933212611499, -0.6313975747684536, -0.6205882624714589, -0.6408121049037772, -0.6358325058878442, -0.6483418584555031, -0.6371649113759628, -0.6291839190391355, -0.6347573834032361, -0.6407098912056699, -0.6159176260854965, -0.6384554645835627, -0.6164080207309359, -0.625543079338974, -0.6382937503891668, -0.6264097132175528, -0.6420718561520969, -0.6267262725213436, -0.6374963711667498, -0.6193193504433864, -0.6078143278866533, -0.634472486357409, -0.6223512323012782, -0.6351163020561015, -0.634661177023637, -0.6327899211075433, -0.6336448686497769, -0.6193351633432258, -0.6281755978797693, -0.6264777231208046, -0.6414830476329384, -0.6307683399864691, -0.6307085701314388, -0.6206080402310008, -0.6348255969934301, -0.6396136598903551, -0.6119662685652434, -0.6416707355866279, -0.6413693107560723, -0.6177947197203094, -0.6298765228276698, -0.6523529064199631, -0.6449003109571184, -0.653383311719062, -0.6114270075961685, -0.6288547938898695, -0.618693644838608, -0.6474406100562011, -0.6311230491106903, -0.6116401562656182, -0.636431790506111, -0.6291838050229098, -0.6323232015973214, -0.6084567336875317, -0.6260410898582017, -0.6558980736383361, -0.6088478495140429, -0.6362772541154403, -0.6229687283270671, -0.6337477882049586, -0.6146890139542273, -0.6109822191193143, -0.6410668717503976, -0.6050360295204666, -0.6127109227117324, -0.613969481075047, -0.6330316470359499, -0.6336428860578563, -0.6579205656897767, -0.6226609914498723, -0.6308197002529959, -0.6592780043421462, -0.6286105470576249, -0.6142144474532307, -0.6308763800946607, -0.6313362339145869, -0.6587453552909762, -0.6439616021766039, -0.6342588475726809, -0.6348805630323535, -0.612208176680939, -0.6384209891698392, -0.6377259399102154, -0.6288355030414153, -0.6254287723561084, -0.6267028568621377, -0.633225553954038, -0.6266439989301029, -0.6219787315736918, -0.6444478946498267, -0.6078647889145464, -0.6169625336670495, -0.6228416937169068, -0.6055808453138738, -0.6349070986052844, -0.6233134657244299, -0.638807727216456, -0.6439324406558855, -0.6290682438485403, -0.6347278678305891, -0.6370807223116214, -0.6331202879928073, -0.6259391405710086, -0.6205239729014943, -0.6271330693467981, -0.6384914098927226, -0.6540996612097635, -0.6297277932870161, -0.6230026756130547, -0.6337458840743901, -0.6269616938156711, -0.6071713916280417, -0.6182364077263139, -0.6295847748388186, -0.6340000050667973, -0.662525648783056, -0.6268357485227919, -0.6383142008116837, -0.6356494637389134, -0.6334179386720562, -0.6368477711503842, -0.6258766827515051, -0.6250225216677815, -0.6402120922677865, -0.6215866553687236, -0.6300458164726813, -0.6349074242618946, -0.6281512038322912, -0.6106861518433435, -0.6257220729152266, -0.6264637065414248, -0.6413022282257185, -0.6287300650968061, -0.6415216331142828, -0.6177784438217981, -0.6235031629550336, -0.6522908854196745, -0.6433100700195024, -0.6467856500499529, -0.6383906423809346, -0.6353007399215785, -0.628267887248418, -0.6530534039557805, -0.6489154837903043, -0.6251303963665552, -0.606115215627397, -0.640564227336403, -0.6426262151446616, -0.6375465819155562, -0.6241657686495026, -0.6365874044036779, -0.6368987773426885, -0.6254336505997881, -0.6195698003196071, -0.6312797723656407, -0.6493745786523953, -0.6255032951930553, -0.6076271422511403, -0.6369485503847903, -0.633978893260772, -0.6247995690801257, -0.6181592078851024, -0.6413113581396256, -0.6357432503116383, -0.6413681655967249, -0.6349930744741815, -0.6553915345015394, -0.6333982709804692, -0.6323784240845362, -0.597462603561814, -0.6354799343741077, -0.6435513818689228, -0.6288306285283861, -0.6252986455639116, -0.6338258059332423, -0.6354797897494069, -0.6118871374772903] plot_convergence_of_optimization_process(H2_approximated_energies, exact_eigenvalue=-0.353325104107155, margin=5) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigen_value = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits) compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) print(approximated_energies) approximated_energies = [] TI_approximated_energies = [1.8984375, 1.943359375, 1.9619140625, 1.978515625, 1.984375, 1.9873046875, 1.9931640625, 1.9248046875, 1.962890625, 1.9248046875, 1.9150390625, 1.9052734375, 1.9267578125, 1.802734375, 1.81640625, 1.86328125, 1.8623046875, 1.7939453125, 1.8623046875, 1.89453125, 1.880859375, 1.8388671875, 1.8720703125, 1.83984375, 1.8837890625, 1.8359375, 1.701171875, 1.7470703125, 1.69140625, 1.73828125, 1.833984375, 1.69921875, 1.7744140625, 1.7529296875, 1.7353515625, 1.7265625, 1.7666015625, 1.708984375, 1.7421875, 1.79296875, 1.8671875, 1.91015625, 1.8828125, 1.884765625, 1.875, 1.86328125, 1.85546875, 1.8134765625, 1.84375, 1.79296875, 1.865234375, 1.8916015625, 1.908203125, 1.900390625, 1.8837890625, 1.876953125, 1.896484375, 1.9921875, 1.9208984375, 1.94921875, 1.96875, 1.8466796875, 1.92578125, 1.8740234375, 1.9716796875, 1.9130859375, 1.939453125, 1.9599609375, 1.9716796875, 1.9150390625, 1.98828125, 1.865234375, 1.9248046875, 1.890625, 2.0146484375, 1.9560546875, 1.947265625, 1.9619140625, 1.955078125, 1.9208984375, 1.955078125, 1.9384765625, 1.96484375, 1.9150390625, 1.923828125, 1.9580078125, 1.958984375, 2.013671875, 1.935546875, 1.9443359375, 2.0546875, 2.001953125, 1.958984375, 1.98828125, 1.962890625, 2.0205078125, 2.0029296875, 1.93359375, 1.91015625, 1.9765625, 1.9365234375, 1.8984375, 1.9072265625, 1.939453125, 1.9033203125, 2.0556640625, 1.947265625, 1.9267578125, 1.9541015625, 1.962890625, 1.9287109375, 1.9072265625, 1.962890625, 1.966796875, 1.9560546875, 1.970703125, 1.9580078125, 1.9833984375, 2.013671875, 1.966796875, 1.9599609375, 1.943359375, 1.974609375, 1.9619140625, 1.9462890625, 1.974609375, 1.9482421875, 1.943359375, 1.9697265625, 1.9033203125, 1.9794921875, 1.98828125, 1.94140625, 1.9658203125, 2.0078125, 1.9912109375, 1.916015625, 1.916015625, 2.0068359375, 1.9130859375, 1.9267578125, 1.90234375, 1.921875, 1.943359375, 1.9755859375, 1.90234375, 1.95703125, 1.9482421875, 1.97265625, 1.9658203125, 1.990234375, 1.9384765625, 1.935546875, 1.916015625, 1.91796875, 1.99609375, 1.87109375, 1.9599609375, 1.919921875, 1.951171875, 1.9521484375, 1.9716796875, 1.9736328125, 1.9794921875, 1.99609375, 1.9765625, 1.9228515625, 1.9482421875, 1.9462890625, 1.986328125, 1.927734375, 1.9482421875, 2.0771484375, 2.0009765625, 1.9267578125, 1.9638671875, 1.904296875, 1.9365234375, 1.962890625, 1.958984375, 1.96875, 1.9521484375, 1.8935546875, 1.916015625, 1.939453125, 1.98046875, 1.9560546875, 1.9541015625, 1.955078125, 1.9228515625, 1.9951171875, 1.93359375, 1.9736328125, 1.9443359375, 1.96484375, 1.984375, 1.8681640625, 1.923828125, 1.947265625, 1.96484375, 1.94140625, 1.9375, 1.96875, 1.94921875, 1.943359375, 1.8935546875, 1.9638671875, 1.912109375, 2.0, 1.921875, 2.064453125, 1.95703125, 1.9287109375, 1.951171875, 1.982421875, 1.8955078125, 1.9482421875, 1.9970703125, 1.9423828125, 1.9697265625, 1.90625, 1.9306640625, 1.9716796875, 1.92578125, 1.98046875, 1.9521484375, 1.9072265625, 1.962890625, 1.9365234375, 1.9609375, 1.9560546875, 1.9462890625, 2.0166015625, 1.9609375, 1.9287109375, 1.962890625, 1.9677734375, 1.9169921875, 1.876953125, 1.9443359375, 1.984375, 1.9697265625, 1.978515625, 1.958984375, 1.9677734375, 2.0341796875, 1.9697265625, 1.93359375, 1.966796875, 1.9482421875, 1.9345703125, 1.9453125, 1.9912109375, 1.986328125, 1.955078125, 1.927734375, 2.03125, 1.921875, 1.951171875, 1.9990234375, 1.8955078125, 1.9794921875, 2.0078125, 1.9580078125, 1.986328125, 1.9287109375, 1.9853515625, 1.9990234375, 1.9365234375, 2.0048828125, 1.9462890625, 1.9580078125, 1.970703125, 1.951171875, 1.91015625, 1.8662109375, 1.9013671875, 1.9267578125, 1.943359375, 1.9814453125, 1.927734375, 1.99609375, 1.9580078125, 1.904296875, 1.912109375, 1.978515625, 1.9453125, 1.990234375, 1.97265625, 1.9580078125, 1.93359375, 1.9599609375, 1.986328125, 1.970703125, 1.966796875, 1.947265625, 1.875, 1.953125, 1.966796875, 1.931640625, 1.9140625, 1.98828125, 1.919921875, 1.970703125, 1.8916015625, 2.0615234375, 2.015625, 1.8466796875, 1.916015625, 1.96875, 1.9697265625, 2.0029296875, 1.9326171875, 1.939453125, 1.873046875, 1.9345703125, 1.9501953125, 1.927734375, 1.9453125, 2.005859375, 1.96484375, 1.9384765625, 1.9609375, 1.990234375, 1.951171875, 1.951171875, 1.994140625, 2.015625, 1.9462890625, 1.94140625, 2.0439453125, 1.9755859375, 1.9326171875, 2.0224609375, 1.9248046875, 1.990234375, 2.0, 1.9091796875, 1.9267578125, 1.951171875, 1.95703125, 1.9521484375] plot_convergence_of_optimization_process(TI_approximated_energies, exact_eigenvalue=1.6816520928402046, margin=3)
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
JessicaJohnBritto
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram from qiskit.quantum_info import Statevector import numpy as np import matplotlib backend = BasicAer.get_backend('qasm_simulator') shots = 1024 style = {'backgroundcolor': 'lightyellow'} # Style of the circuits qreg = QuantumRegister(2) creg = ClassicalRegister(1) qc = QuantumCircuit(qreg, creg) qc.x(1) # Applying X gate on qubit 2 to get |1> qc.barrier() qc.draw(output='mpl', style=style) # Applying Hadamard Gate for qubit in range(2): qc.h(qubit) qc.barrier() qc.draw(output='mpl', style=style) # Balanced Oracle qc.cx(0,1) qc.barrier() for qubit in range(1): qc.h(qubit) qc.measure(0,0) qc.draw(output='mpl', style=style) transpiled_dj_circuit = transpile(qc, backend) qobj = assemble(transpiled_dj_circuit) results = backend.run(qobj).result() answer = results.get_counts() plot_histogram(answer) ## Re-initialising qreg = QuantumRegister(2) creg = ClassicalRegister(1) qc = QuantumCircuit(qreg, creg) qc.x(1) # Applying X gate on qubit 2 to get |1> qc.barrier() # qc.draw(output='mpl', style=style) # Applying Hadamard Gate for qubit in range(2): qc.h(qubit) qc.barrier() # Constant Oracle if qc[1]==1: qc.x(1) for qubit in range(1): qc.h(qubit) qc.measure(0,0) qc.draw(output='mpl', style=style) transpiled_dj_circuit = transpile(qc, backend) qobj = assemble(transpiled_dj_circuit) results = backend.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
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-metriq
qiskit-community
import os import json import qiskit import requests from datetime import datetime def get_installed_version(): try: # Starting with qiskit v0.45, qiskit and qiskit-terra will have the same version return qiskit.__version__ except ImportError: return qiskit.__qiskit_version__["qiskit"] def get_qiskit_releases_data(package_name: str) -> dict: response = requests.get(f"https://pypi.org/pypi/{package_name}/json") if response.status_code == 200: data = response.json() return data["releases"].items() return None def get_qiskit_versions_info() -> []: data_items = get_qiskit_releases_data("qiskit") # Filter releases starting from 2023-11 # Starting with qiskit 0.45, qiskit and qiskit-terra will have the same version return filter_by_date(data_items, [2023,11], []) def get_qiskit_terra_versions_info() -> []: data_items = get_qiskit_releases_data("qiskit-terra") # Filter releases from 2020-03 (terra v0.13.x) to 2023-10 (terra v.0.25.x) return filter_by_date(data_items,[2020,3], [2023,10]) def get_qiskit_versions_list(package_name: str) -> []: qiskit_versions_info = get_qiskit_terra_versions_info() if "terra" in package_name else get_qiskit_versions_info() versions_only = [] for item in qiskit_versions_info: for key, value in item.items(): if key == "version": versions_only.append(value) return versions_only def find_latest_version(versions: []) -> str: if not versions: return "" # Split each version string into a tuple of integers version_tuples = [tuple(map(int, v.split("."))) for v in versions] # Sort sorted_versions = sorted(version_tuples, reverse=True) # Convert the latest version tuple back to string latest_version = ".".join(map(str, sorted_versions[0])) return latest_version # Compare versions in string format and return the highest def compare_versions(version_1:str, version_2: str) -> str: # Split version strings into lists of ints # Split version strings into lists of ints v1_parts = list(map(int, version_1.split("."))) v2_parts = list(map(int, version_2.split("."))) # Compare for v1, v2 in zip(v1_parts, v2_parts): if v1 > int(v2): return version_1 elif v1 < int(v2): return version_2 return version_1 # if they are the same def same_minor(version_1: str, version_2: str) -> bool: # Split version strings into lists of ints v1 = list(map(int, version_1.split("."))) v2 = list(map(int, version_2.split("."))) return v1[:2] == v2[:2] def filter_by_date(data_items: dict, min_date: [], max_date: []) -> []: # Temporary control dictionary for package release info for version, date and python version temp = {} for release, release_info in data_items: # Skip RCs and pre-releases if "rc" in release or "b" in release: print("Skipping version ", release) continue date_str = release_info[0]["upload_time"] dt = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S") year = dt.year month = dt.month if max_date: max_y, max_m = max_date # Ignore above max_date if (year == max_y and month > max_m) or year > max_y: continue min_y, min_m = min_date # Ignore below min_date if (year == min_y and month < min_m) or year < min_y: continue python_version = release_info[0]["requires_python"] # Parse the release string of format "x.y.z" into a list of "x","y","z" major_minor_patch_list = release.split(".") major_minor = ".".join(major_minor_patch_list[:2]) # Get latest patch patch_number = int(major_minor_patch_list[2]) temp_info = temp.get(major_minor) previous_patch_number = -1 if not temp_info else temp_info[0] if previous_patch_number < patch_number: # Replace to latest patch version found temp[major_minor] = (patch_number, {"version":release, "date": dt.strftime("%Y-%m-%d"), "python_version": python_version}) continue filtered_releases = [] for _, value in temp.items(): filtered_releases.append(value[1]) return filtered_releases def write_versions_to_file(versions: [], filename: str): file_path = os.path.abspath(os.path.join( os.path.dirname( __file__ ),"..", "benchmarking", filename)) with open(file_path,"w") as file: json.dump(versions, file, indent=4) def get_version_date(package_name: str, input_version:str) -> str: data_items = data_items = get_qiskit_releases_data(package_name) for release, release_info in data_items: if release == input_version: # Remove time from date format "%Y-%m-%dT%H:%M:%S" date_time= release_info[0]["upload_time"] return date_time.split('T', 1)[0] return "Invalid version" ### # qiskit_info = get_qiskit_versions_info() # print("qiskit versions:", sep='\n') # print(*qiskit_info, sep='\n') """ qiskit versions: {'version': '0.45.0', 'date': '2023-11-03', 'python_version': '>=3.8'} """ # qiskit_terra_info = get_qiskit_terra_versions_info() # print("qiskit-terra versions:", sep='\n') # print(*qiskit_terra_info, sep='\n') """ qiskit-terra versions: {'version': '0.13.0', 'date': '2020-04-09', 'python_version': '>=3.5'} {'version': '0.14.2', 'date': '2020-06-15', 'python_version': '>=3.5'} {'version': '0.15.2', 'date': '2020-09-08', 'python_version': '>=3.5'} {'version': '0.16.4', 'date': '2021-02-08', 'python_version': '>=3.6'} {'version': '0.17.4', 'date': '2021-05-18', 'python_version': '>=3.6'} {'version': '0.18.3', 'date': '2021-09-29', 'python_version': '>=3.6'} {'version': '0.19.2', 'date': '2022-02-02', 'python_version': '>=3.6'} {'version': '0.20.2', 'date': '2022-05-18', 'python_version': '>=3.7'} {'version': '0.21.2', 'date': '2022-08-23', 'python_version': '>=3.7'} {'version': '0.22.4', 'date': '2023-01-17', 'python_version': '>=3.7'} {'version': '0.23.3', 'date': '2023-03-21', 'python_version': '>=3.7'} {'version': '0.24.2', 'date': '2023-07-19', 'python_version': '>=3.7'} {'version': '0.25.3', 'date': '2023-10-25', 'python_version': '>=3.8'} """
https://github.com/tomtuamnuq/compare-qiskit-ocean
tomtuamnuq
import dimod import networkx as nx import dwave_networkx as dnx from dwave.embedding import pegasus import neal, dwave.system import numpy as np A_int = np.array([[0,1,2,3,4,1], [2,1,4,1,0,2], [1,5,2,3,1,1]]) m, n = A_int.shape vartype = dimod.Vartype.BINARY c_int = np.array([1,2,1,-3,1,-1]) b = np.array([7,8,5]) print(A_int.dot(np.array([1,0,0,0,1,3]))) def get_binary_form(c,bits): c_bin = [] for c_j in c: c_bin += [c_j * 2**i for i in range(0,bits)] return np.array(c_bin) # represent each x_i as 3 bits to the power of 2 bits = 3 # Set Penalty for Constraints aprox solution P = max(abs(c_int))*3 c = get_binary_form(c_int,bits) print(c) A = np.array([get_binary_form(A_int[i], bits) for i in range(0,m)]) print(A) # Set up linear and quadratic coefficients L = c.T - P * 2 * np.matmul(b.T,A) Q = P * np.matmul(A.T,A) offset = P * b.T.dot(b) bqm = dimod.as_bqm(L, Q, offset, vartype) def construct_x(sample, bits): x=[] for k in range(0,len(sample.keys()),bits): x += [sum(sample[k+j]* 2**j for j in range(0,bits))] return np.array(x) def testSamples(sampleset, bits): print("Minimum Energy Level found in:",sampleset.first) X = [] for sample, energy, in sampleset.data(fields=['sample', 'energy']): x = construct_x(sample,bits) if all(A_int.dot(x)[i] == b[i] for i in range(0,m)) : X += [(x,energy)] return X # Define target Pegasus Graph M = 16 # Defines number of qubits in Pegasus graph : 24M(M-1) P_M = dnx.pegasus_graph(M, data = True) # allow the use of pegasus indizes # Define source complete graph a = len(bqm.variables) K_a = nx.complete_graph(a) # Embedding K_a into P_M embedding = pegasus.find_clique_embedding(K_a, target_graph=P_M) sampler = dwave.system.FixedEmbeddingComposite(dwave.system.DWaveSampler(), embedding = embedding) sampler.child.properties['num_qubits'] sampleset = sampler.sample(bqm,num_reads = 2000) sampleset.to_pandas_dataframe() solutions_real = testSamples(sampleset, bits) solutions_unique = { str(x) : energy for x, energy in solutions_real} for x in solutions_unique.keys() : print("Found solution {} with Energy Level {}".format(x,solutions_unique[x])) a = len(bqm.variables) embedding = pegasus.find_clique_embedding(a,m = a) sampler = dwave.system.FixedEmbeddingComposite(dwave.system.DWaveSampler(), embedding = embedding)
https://github.com/NirdevPaul/GroversAlgorithm
NirdevPaul
my_list = [1, 3, 5, 2, 4, 9, 5, 8, 0, 7, 6] def the_oracle(my_input): winner = 7 return my_input == winner for index, trial_number in enumerate(my_list): if the_oracle(trial_number): print(f"Found the winner at index {index}!") print(f"{index+1} calls made") break from qiskit import * from qiskit.visualization import plot_histogram, array_to_latex from qiskit.providers.ibmq import least_busy import matplotlib.pyplot as plt import numpy as np grover_circuit = QuantumCircuit(2) def init_state(qc, qubits): for q in qubits: qc.h(q) return qc grover_circuit = init_state(grover_circuit, [0, 1]) grover_circuit.draw("mpl") #define the oracle circuit def oracle(qc, qubits): qc.cz(qubits[0], qubits[1]) qc = QuantumCircuit(2) oracle(qc, [0, 1]) qc.draw("mpl") usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{One can see that only the state }\ket{11}\\text{ has been flipped: }\n") def diffusion(qc, qubits): qc.h([0, 1]) qc.z([0, 1]) qc.cz(0, 1) qc.h([0, 1]) grover_circuit.barrier() oracle(grover_circuit, [0, 1]) grover_circuit.barrier() diffusion(grover_circuit, [0, 1]) grover_circuit.measure_all() grover_circuit.draw("mpl") # Let's see if the final statevector matches our expectations sv_sim = Aer.get_backend('statevector_simulator') result = sv_sim.run(grover_circuit).result() statevec = result.get_statevector() statevec aer_sim = Aer.get_backend('aer_simulator') result = execute(grover_circuit, aer_sim, shots=1024).result() result.get_counts() # Load IBM Q account and get the least busy backend device # Run the following line with your API token to use IBM's own quantum computers #IBMQ.save_account('') provider = IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") 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) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) grover_circuit = QuantumCircuit(3) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.draw("mpl") oracle_qc = QuantumCircuit(3) oracle_qc.cz(0, 1) oracle_qc.cz(0, 2) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "U$_\omega$" def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> -> |11..1> for qubit in range(nqubits): qc.h(qubit) qc.x(qubit) # When these are combined, they function as a multi-controlled Z gate # A negative phase is added to |11..1> to flip the state qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> -> |s> for qubit in range(nqubits): qc.x(qubit) qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s num_qubits = 3 grover_circuit = QuantumCircuit(num_qubits) grover_circuit = init_state(grover_circuit, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(oracle_gate, [0, 1, 2]) grover_circuit.barrier() grover_circuit.append(diffuser(num_qubits), [0, 1, 2]) grover_circuit.measure_all() grover_circuit.draw("mpl") qasm_sim = Aer.get_backend('qasm_simulator') transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) results = qasm_sim.run(transpiled_grover_circuit).result() counts = results.get_counts() plot_histogram(counts) backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3) job = device.run(transpiled_grover_circuit) job_monitor(job, interval=2) # Get the results from the computation results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer)
https://github.com/apcarrik/qiskit-dev
apcarrik
from qiskit import IBMQ, transpile from qiskit import QuantumCircuit from qiskit.providers.aer import AerSimulator from qiskit.tools.visualization import plot_histogram ## Terra Mock Backends from qiskit.test.mock import FakeVigo device_backend = FakeVigo() # Build test circuit circ = QuantumCircuit(3,3) circ.h(0) circ.cx(0,1) circ.cx(1,2) circ.measure([0,1,2], [0,1,2]) sim_ideal = AerSimulator() # Execute circuit and get counts result = sim_ideal.run(transpile(circ,sim_ideal)).result() counts = result.get_counts(0) plot_histogram(counts, title="Ideal counts for 3-qubit GHZ state").show() ## Generate Simulator that Mimics Real Device sim_vigo = AerSimulator.from_backend(device_backend) # Run noisy simulation tcirc = transpile(circ, sim_vigo) result_noise = sim_vigo.run(tcirc).result() counts_noise = result_noise.get_counts() plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with noisy model").show()
https://github.com/1chooo/Quantum-Oracle
1chooo
#Below are examples of using print function print('The name of the language is',"Python") print("The radius of the circle is", 3, '\nIts area is', 3.14159*3**2) #Below are examples of using print function print('The name of the language is',"Python",end=". ") print('Its version is',"3.x",sep="....") print("The radius of the circle is", 3) print("The area of the circle is", 3.14159*3**2) r=input('Please enter the radius of the circle:') print('The radius of the circle:', r) r=input('Please enter the radius of the circle:') ri=int(r) rf=float(r) print('The radius of the circle:', ri) print("The area of the circle:", 3.14159*rf**2) a=123;b=123.456;c=False;d=123+456j;e="123";f=[1,2,3];g=(1,2,3);h={1,2,3};i={1:'x',2:'y',3:'z'} print(type(a),type(b),type(c),type(d),type(e),type(f),type(g),type(h),type(i)) a=3;b=8 print(a+b) #11 print(a-b) #-5 print(a*b) #24 print(a/b) #0.375 print(a//b) #0 print(a%b) #3 print(a**b) #6561 print(a+b//a**b) #3 print((a+b)//a**b) #0 a=3.0;b=8.0;c=8 print(a+b) #11.0 print(a-b) #-5.0 print(a*b) #24.0 print(a/b) #0.375 print(a//b) #0.0 print(a%b) #3.0 print(a**b) #6561.0 print(a+c) #11.0 print(a+b//a**b) #3.0 print((a+b)//a**b) #0.0 a=3.0;b=8.0;c=8 print(a==b) #False print(a!=b) #True print(a>b) #False print(a<b) #True print(a>=b) #False print(a<=b) #True print(not (a==b)) #True print(a==b or a!=b and a>b) #False print(a==b and a>b or a!=b) #True print(a==b and a>b or not (a!=b)) #False a=2+4j;b=3-8j print(a+b) #(5-4j) print(a-b) #(-1+12j) print(a*b) #(38-4j) print(a/b) #(-0.3561643835616438+0.3835616438356164j) print(a+b/a) #(0.7+2.6j) print((a+b)/a) #(-0.3-1.4j) print(a.real) #2.0 print(a.imag) #4.0 print(a.conjugate()) #(2-4j) print(abs(a)) #4.47213595499958 a={1,2,3};b={2,4,6} print(a|b) #{1, 2, 3, 4, 6} print(a.union(b)) #{1, 2, 3, 4, 6} print(a&b) #{2} print(a.intersection(b)) #{2} print(a-b) #{1,3} print(a.difference(b)) #{1,3} print(a^b) #{1,3,4,6} print(a.symmetric_difference(b)) #{1,3,4,6} ex = {"a":1, "b":2, "c":3, 1: "integer", 2.3: "float", 4+5j: "complex", (6,7): "tuple"} print(ex["a"],ex["b"],ex["c"],ex[1],ex[2.3],ex[4+5j],ex[(6,7)]) ex["a"]=100 print(ex["a"]) print(len(ex)) ex["d"]=4 print(ex.get("d")) del ex["d"] print(ex.get("d")) print("e" in ex) print("e" not in ex) print(ex.keys()) print(ex.values()) a=5 a+=3 #a=a+3 (a=8) a-=3 #a=a-3 (a=5) a*=3 #a=a*3 (a=15) a%=8 #a=a%8 (a=7) a//=3 #a=a//3 (a=2) a/=3 #a=a/3 (a=0.6666666666666666) a**=3 #a=a**3 (a=0.2962962962962962) print(a) score=90 if score >=60: print("PASS") score=90 if score >=60: print("PASS") else: print("FAIL") score=90 if score >=90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F") i=0 while i<5: i+=1 print(i,end="") i=0 while i<5: i+=1 print(i,end="") else: print("#") for i in [1,2,3,4,5]: print(i,end="") for i in [1,2,3,4,5]: print(i,end="") else: print("#") print(list(range(5))) #range(5)會回傳0、1、2、3、4 print(list(range(2,5))) #range(2,5)會回傳2、3、4 print(list(range(0,5,2))) #range(0,2,5)會回傳0、2、4 print(list(range(5,0,-1))) #range(5,0,-1)會回傳5、4、3、2、1 print(list(range(5,0))) #range(5,0)是一個空序列 i=0 while i<5: i+=1 if i==3: break print(i,end="") for i in range(1,6): if i==3: break print(i,end="") i=0 while i<5: i+=1 if i==3: continue print(i,end="") for i in range(1,6): if i==3: continue print(i,end="") def odd_check(n): """Check if n is odd (return True) or not (return False).""" if n%2==0: return False else: return True print(odd_check(5)) print(odd_check(10)) def test(aa,bb,cc=123,dd='abc'): return aa,bb,cc,dd print(test(1,2,3,4)) print(test(1,2,3)) print(test(1,2,dd='edf')) print(test(1,2)) def adding(*num): sum=0 for n in num: sum+=n return sum print(adding(1,2,3,4,5)) adding = lambda x,y: x+y print(adding(3,8)) #顯示11 print((lambda x,y: x+y)(3,8)) #顯示11 lista=[1,3,5,7,9] #以下將lambda函數當作map函數的參數 listb=list(map(lambda x:x+8, lista)) print(listb) class Rectangle: length=0 width=0 def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*(self.length+self.width) rect1=Rectangle(3,8) rect2=Rectangle(2,4) print('rect1:',rect1.length,rect1.width,rect1.area(),rect1.perimeter()) print('rect2:',rect2.length,rect2.width,rect2.area(),rect2.perimeter()) class NamedRectangle(Rectangle): name='' def __init__(self,length,width,name): super().__init__(length,width) self.name=name def show_name(self): print(self.name) rect1=NamedRectangle(3,8,'rectangle1') rect2=NamedRectangle(2,4,'rectangle2') print('rect1:',rect1.length,rect1.width,rect1.area(),rect1.perimeter()) print('rect2:',rect2.length,rect2.width,rect2.area(),rect2.perimeter()) rect1.show_name() rect2.show_name()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl')
https://github.com/Cryoris/gradient-reverse-mode
Cryoris
# -*- 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 trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ import logging import sys import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.tools import parallel_map from qiskit.tools.events import TextProgressBar from qiskit.aqua import Operator, aqua_globals from qiskit.aqua.components.variational_forms import VariationalForm from qiskit.chemistry.fermionic_operator import FermionicOperator from qiskit.chemistry import MP2Info from qiskit.chemistry import QMolecule as qm logger = logging.getLogger(__name__) class UCCSD(VariationalForm): """ This trial wavefunction is a Unitary Coupled-Cluster Single and Double excitations variational form. For more information, see https://arxiv.org/abs/1805.04340 """ CONFIGURATION = { 'name': 'UCCSD', 'description': 'UCCSD Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'uccsd_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 1, 'minimum': 1 }, 'num_orbitals': { 'type': 'integer', 'default': 4, 'minimum': 1 }, 'num_particles': { 'type': 'integer', 'default': 2, 'minimum': 1 }, 'active_occupied': { 'type': ['array', 'null'], 'default': None }, 'active_unoccupied': { 'type': ['array', 'null'], 'default': None }, 'qubit_mapping': { 'type': 'string', 'default': 'parity', 'oneOf': [ {'enum': ['jordan_wigner', 'parity', 'bravyi_kitaev']} ] }, 'two_qubit_reduction': { 'type': 'boolean', 'default': False }, 'mp2_reduction': { 'type': 'boolean', 'default': False }, 'num_time_slices': { 'type': 'integer', 'default': 1, 'minimum': 1 }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'HartreeFock', } }, ], } def __init__(self, num_qubits, depth, num_orbitals, num_particles, active_occupied=None, active_unoccupied=None, initial_state=None, qubit_mapping='parity', two_qubit_reduction=False, mp2_reduction=False, num_time_slices=1, cliffords=None, sq_list=None, tapering_values=None, symmetries=None, shallow_circuit_concat=True): """Constructor. Args: num_orbitals (int): number of spin orbitals depth (int): number of replica of basic module num_particles (int): number of particles active_occupied (list): list of occupied orbitals to consider as active space active_unoccupied (list): list of unoccupied orbitals to consider as active space initial_state (InitialState): An initial state object. qubit_mapping (str): qubit mapping type. two_qubit_reduction (bool): two qubit reduction is applied or not. num_time_slices (int): parameters for dynamics. cliffords ([Operator]): list of unitary Clifford transformation sq_list ([int]): position of the single-qubit operators that anticommute with the cliffords tapering_values ([int]): array of +/- 1 used to select the subspace. Length has to be equal to the length of cliffords and sq_list symmetries ([Pauli]): represent the Z2 symmetries shallow_circuit_concat (bool): indicate whether to use shallow (cheap) mode for circuit concatenation """ self.validate(locals()) super().__init__() self._cliffords = cliffords self._sq_list = sq_list self._tapering_values = tapering_values self._symmetries = symmetries if self._cliffords is not None and self._sq_list is not None and \ self._tapering_values is not None and self._symmetries is not None: self._qubit_tapering = True else: self._qubit_tapering = False self._num_qubits = num_orbitals if not two_qubit_reduction else num_orbitals - 2 self._num_qubits = self._num_qubits if not self._qubit_tapering else self._num_qubits - len(sq_list) if self._num_qubits != num_qubits: raise ValueError('Computed num qubits {} does not match actual {}' .format(self._num_qubits, num_qubits)) self._depth = depth self._num_orbitals = num_orbitals self._num_particles = num_particles if self._num_particles > self._num_orbitals: raise ValueError('# of particles must be less than or equal to # of orbitals.') self._initial_state = initial_state self._qubit_mapping = qubit_mapping self._two_qubit_reduction = two_qubit_reduction self._num_time_slices = num_time_slices self._shallow_circuit_concat = shallow_circuit_concat self._single_excitations, self._double_excitations = \ UCCSD.compute_excitation_lists(num_particles, num_orbitals, active_occupied, active_unoccupied) self._single_excitations = [] print('{} are the old doubles'.format(self._double_excitations)) print(mp2_reduction) if mp2_reduction: print('Getting new doubles') self._double_excitations = get_mp2_doubles(self._single_excitations,self._double_excitations) print('{} are the new doubles'.format(self._double_excitations)) self._hopping_ops, self._num_parameters = self._build_hopping_operators() self._bounds = [(-np.pi, np.pi) for _ in range(self._num_parameters)] self._logging_construct_circuit = True def _build_hopping_operators(self): from .uccsd import UCCSD hopping_ops = [] if logger.isEnabledFor(logging.DEBUG): TextProgressBar(sys.stderr) results = parallel_map(UCCSD._build_hopping_operator, self._single_excitations + self._double_excitations, task_args=(self._num_orbitals, self._num_particles, self._qubit_mapping, self._two_qubit_reduction, self._qubit_tapering, self._symmetries, self._cliffords, self._sq_list, self._tapering_values), num_processes=aqua_globals.num_processes) hopping_ops = [qubit_op for qubit_op in results if qubit_op is not None] num_parameters = len(hopping_ops) * self._depth return hopping_ops, num_parameters @staticmethod def _build_hopping_operator(index, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, qubit_tapering, symmetries, cliffords, sq_list, tapering_values): def check_commutativity(op_1, op_2): com = op_1 * op_2 - op_2 * op_1 com.zeros_coeff_elimination() return True if com.is_empty() else False h1 = np.zeros((num_orbitals, num_orbitals)) h2 = np.zeros((num_orbitals, num_orbitals, num_orbitals, num_orbitals)) if len(index) == 2: i, j = index h1[i, j] = 1.0 h1[j, i] = -1.0 elif len(index) == 4: i, j, k, m = index h2[i, j, k, m] = 1.0 h2[m, k, j, i] = -1.0 dummpy_fer_op = FermionicOperator(h1=h1, h2=h2) qubit_op = dummpy_fer_op.mapping(qubit_mapping) qubit_op = qubit_op.two_qubit_reduced_operator(num_particles) \ if two_qubit_reduction else qubit_op if qubit_tapering: for symmetry in symmetries: symmetry_op = Operator(paulis=[[1.0, symmetry]]) symm_commuting = check_commutativity(symmetry_op, qubit_op) if not symm_commuting: break if qubit_tapering: if symm_commuting: qubit_op = Operator.qubit_tapering(qubit_op, cliffords, sq_list, tapering_values) else: qubit_op = None if qubit_op is None: logger.debug('Excitation ({}) is skipped since it is not commuted ' 'with symmetries'.format(','.join([str(x) for x in index]))) return qubit_op def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ from .uccsd import UCCSD if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) if logger.isEnabledFor(logging.DEBUG) and self._logging_construct_circuit: logger.debug("Evolving hopping operators:") TextProgressBar(sys.stderr) self._logging_construct_circuit = False num_excitations = len(self._hopping_ops) results = parallel_map(UCCSD._construct_circuit_for_one_excited_operator, [(self._hopping_ops[index % num_excitations], parameters[index]) for index in range(self._depth * num_excitations)], task_args=(q, self._num_time_slices), num_processes=aqua_globals.num_processes) for qc in results: if self._shallow_circuit_concat: circuit.data += qc.data else: circuit += qc return circuit @staticmethod def _construct_circuit_for_one_excited_operator(qubit_op_and_param, qr, num_time_slices): qubit_op, param = qubit_op_and_param qc = qubit_op.evolve(None, param * -1j, 'circuit', num_time_slices, qr) return qc @property def preferred_init_points(self): """Getter of preferred initial points based on the given initial state.""" if self._initial_state is None: return None else: bitstr = self._initial_state.bitstr if bitstr is not None: return np.zeros(self._num_parameters, dtype=np.float) else: return None @staticmethod def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None, active_unocc_list=None, same_spin_doubles=True): """ Computes single and double excitation lists Args: num_particles: Total number of particles num_orbitals: Total number of spin orbitals active_occ_list: List of occupied orbitals to include, indices are 0 to n where n is num particles // 2 active_unocc_list: List of unoccupied orbitals to include, indices are 0 to m where m is (num_orbitals - num particles) // 2 same_spin_doubles: True to include alpha,alpha and beta,beta double excitations as well as alpha,beta pairings. False includes only alpha,beta Returns: Single and double excitation lists """ if num_particles < 2 or num_particles % 2 != 0: raise ValueError('Invalid number of particles {}'.format(num_particles)) if num_orbitals < 4 or num_orbitals % 2 != 0: raise ValueError('Invalid number of orbitals {}'.format(num_orbitals)) if num_orbitals <= num_particles: raise ValueError('No unoccupied orbitals') if active_occ_list is not None: active_occ_list = [i if i >= 0 else i + num_particles // 2 for i in active_occ_list] for i in active_occ_list: if i >= num_particles // 2: raise ValueError('Invalid index {} in active active_occ_list {}' .format(i, active_occ_list)) if active_unocc_list is not None: active_unocc_list = [i + num_particles // 2 if i >= 0 else i + num_orbitals // 2 for i in active_unocc_list] for i in active_unocc_list: if i < 0 or i >= num_orbitals // 2: raise ValueError('Invalid index {} in active active_unocc_list {}' .format(i, active_unocc_list)) if active_occ_list is None or len(active_occ_list) <= 0: active_occ_list = [i for i in range(0, num_particles // 2)] if active_unocc_list is None or len(active_unocc_list) <= 0: active_unocc_list = [i for i in range(num_particles // 2, num_orbitals // 2)] single_excitations = [] double_excitations = [] logger.debug('active_occ_list {}'.format(active_occ_list)) logger.debug('active_unocc_list {}'.format(active_unocc_list)) beta_idx = num_orbitals // 2 for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: single_excitations.append([occ_alpha, unocc_alpha]) for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: single_excitations.append([occ_beta, unocc_beta]) for occ_alpha in active_occ_list: for unocc_alpha in active_unocc_list: for occ_beta in [i + beta_idx for i in active_occ_list]: for unocc_beta in [i + beta_idx for i in active_unocc_list]: double_excitations.append([occ_alpha, unocc_alpha, occ_beta, unocc_beta]) if same_spin_doubles and len(active_occ_list) > 1 and len(active_unocc_list) > 1: for i, occ_alpha in enumerate(active_occ_list[:-1]): for j, unocc_alpha in enumerate(active_unocc_list[:-1]): for occ_alpha_1 in active_occ_list[i + 1:]: for unocc_alpha_1 in active_unocc_list[j + 1:]: double_excitations.append([occ_alpha, unocc_alpha, occ_alpha_1, unocc_alpha_1]) up_active_occ_list = [i + beta_idx for i in active_occ_list] up_active_unocc_list = [i + beta_idx for i in active_unocc_list] for i, occ_beta in enumerate(up_active_occ_list[:-1]): for j, unocc_beta in enumerate(up_active_unocc_list[:-1]): for occ_beta_1 in up_active_occ_list[i + 1:]: for unocc_beta_1 in up_active_unocc_list[j + 1:]: double_excitations.append([occ_beta, unocc_beta, occ_beta_1, unocc_beta_1]) logger.debug('single_excitations ({}) {}'.format(len(single_excitations), single_excitations)) logger.debug('double_excitations ({}) {}'.format(len(double_excitations), double_excitations)) return single_excitations, double_excitations def get_mp2_doubles(single_excitations, double_excitations): print('Is the class still populated with the correct info: ', qm.nuclear_repulsion_energy) mp2 = MP2Info(qm, single_excitations, double_excitations, threshold=1e-3) mp2_doubles = mp2._mp2_doubles return mp2_doubles
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
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), ] ) from qiskit.primitives import Estimator estimator = Estimator() import numpy as np from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals # we will iterate over these different optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_counts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) for i, optimizer in enumerate(optimizers): print("\rOptimizer: {} ".format(type(optimizer).__name__), end="") algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_counts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print("\rOptimization complete "); import pylab pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for various optimizers") pylab.legend(loc="upper right"); from qiskit.algorithms.minimum_eigensolvers 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}") pylab.rcParams["figure.figsize"] = (12, 8) for i, optimizer in enumerate(optimizers): pylab.plot( converge_counts[i], abs(ref_value - converge_vals[i]), label=type(optimizer).__name__, ) pylab.xlabel("Eval count") pylab.ylabel("Energy difference from solution reference value") pylab.title("Energy convergence for various optimizers") pylab.yscale("log") pylab.legend(loc="upper right"); from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient estimator = Estimator() gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer = SLSQP(maxiter=100) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE( estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient ) result = vqe.compute_minimum_eigenvalue(operator=H2_op) print(f"Value using Gradient: {result.eigenvalue.real:.5f}") pylab.rcParams["figure.figsize"] = (12, 8) pylab.plot(counts, values, label=type(optimizer).__name__) pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence using Gradient") pylab.legend(loc="upper right"); print(result) cost_function_evals = result.cost_function_evals initial_pt = result.optimal_point estimator1 = Estimator() gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01) ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") optimizer1 = SLSQP(maxiter=1000) vqe1 = VQE( estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt ) result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op) print(result1) cost_function_evals1 = result1.cost_function_evals print() print( f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it." ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
rodneyosodo
import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('display.max_colwidth', -1) df = pd.read_csv("../../Data/Processed/iriscost.csv") df.columns = ['Spec', "CostValues"] df.head(1) df['Spec'] def check_lowest_cost(df): """ Checks the configs which attained the lowest sost """ cost = [] lowest_cost = [] for i in range(df.shape[0]): data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')] lowest_cost.append(data[len(data) - 1]) lowest_cost = sorted(lowest_cost)[:10] for m in lowest_cost: for i in range(df.shape[0]): data = df['CostValues'][i].split(',') data = [float(x.replace("[", "").replace("]", "")) for x in data] if float(m) == float(data[len(data) - 1]): print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1])) cost.append(data[len(data) - 1]) #df['CostValues'] = [] #df.to_excel("n.xlsx") # print(df.head(80)) check_lowest_cost(df) # Plotting all for i in range(df.shape[0]): fig = plt.figure() data = df['CostValues'][i].split(',') data = [float(x.replace("[", "").replace("]", "")) for x in data] plt.plot(range(0, len(data), 1), data) plt.xlabel('Steps') plt.ylabel('Cost value') plt.title(str(df['Spec'][i])) plt.show() path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")) # fig.savefig(path) def plot_individual_optimizers(Optimizers): for opt in Optimizers: max_iter = 0 fig = plt.figure(figsize=(20,20)) for i in range(df.shape[0]): if df['Spec'][i].__contains__(opt): data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')] if len(data) >= max_iter: max_iter = len(data) for i in range(df.shape[0]): if df['Spec'][i].__contains__(opt): data = df['CostValues'][i].split(',') data = [float(x.replace("[", "").replace("]", "")) for x in data] if max_iter >= len(data): temp = np.full((max_iter, ), data[len(data) -1]) temp[:len(data)] = data data = temp plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))) plt.xlabel('Steps') plt.ylabel('Cost value') plt.title(opt) plt.legend() plt.show() plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"]) def plot_increase_vdepth(optimizer, featuremap, reps, checking): points = [] for i in range(df.shape[0]): title = str(df['Spec'][i]) if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)): points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", ""))) fig = plt.figure() plt.plot(range(0, len(points), 1), points) plt.xlabel(checking) plt.ylabel('Cost value') plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps)) plt.show() def plot_increase_fdepth(optimizer, featuremap, fdepth, checking): points = [] for i in range(df.shape[0]): title = str(df['Spec'][i]) if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)): points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", ""))) fig = plt.figure() plt.plot(range(0, len(points), 1), points) plt.xlabel(checking) plt.ylabel('Cost value') plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth)) plt.show() plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth") plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth") for opt in ['SPSA', "COBYLA", "ADAM"]: for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]: for fdepth in [1, 2, 4]: plot_increase_vdepth(opt, fmap, fdepth, "vdepth") for opt in ['SPSA', "COBYLA", "ADAM"]: for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]: for fdepth in [1, 3, 5]: plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
https://github.com/ColibrITD-SAS/mpqp
ColibrITD-SAS
"""Mathematical tools for linear algebra, functions generalized to more data types, etc…""" from __future__ import annotations import math from functools import reduce from numbers import Complex, Real from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from sympy import Expr import sympy as sp import numpy as np import numpy.typing as npt from scipy.linalg import inv, sqrtm from typeguard import typechecked from mpqp.tools.generics import Matrix rtol = 1e-05 """The relative tolerance parameter.""" atol = 1e-08 """The absolute tolerance parameter.""" @typechecked def normalize(v: npt.NDArray[np.complex64]) -> npt.NDArray[np.complex64]: """Normalizes an array representing the amplitudes of the state. Args: v: The vector to be normalized. Returns: The normalized vector. Examples: >>> vector = np.array([1,0,0,1]) >>> normalize(vector) array([0.70710678, 0. , 0. , 0.70710678]) >>> vector = np.array([0,0,0,0]) >>> normalize(vector) array([0, 0, 0, 0]) """ norm = np.linalg.norm(v, ord=2) return v if norm == 0 else v / norm @typechecked def matrix_eq(lhs: Matrix, rhs: Matrix, atol: float = atol, rtol: float = rtol) -> bool: r"""Checks whether two matrix (including vectors) are element-wise equal, within a tolerance. For respectively each elements `a` and `b` of both inputs, we check this specific condition: `|a - b| \leq (atol + rtol * |b|)`. Args: lhs: Left-hand side matrix of the equality. rhs: Right-hand side matrix of the equality. Returns: ``True`` if the two matrix are equal (according to the definition above). """ from sympy import Expr for elt in zip(np.ndarray.flatten(lhs), np.ndarray.flatten(rhs)): if isinstance(elt[0], Expr) or isinstance(elt[1], Expr): if elt[0] != elt[1]: return False else: if abs(elt[0] - elt[1]) > (atol + rtol * abs(elt[1])): return False return True @typechecked def is_hermitian(matrix: Matrix) -> bool: """Checks whether the matrix in parameter is hermitian. Args: matrix: matrix for which we want to know if it is hermitian. Returns: ``True`` if the matrix in parameter is Hermitian. Examples: >>> m1 = np.array([[1,2j,3j],[-2j,4,5j],[-3j,-5j,6]]) >>> is_hermitian(m1) True >>> m2 = np.diag([1,2,3,4]) >>> is_hermitian(m2) True >>> m3 = np.array([[1,2,3],[2,4,5],[3,5,6]]) >>> is_hermitian(m3) True >>> m4 = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> is_hermitian(m4) False >>> x = symbols("x", real=True) >>> m5 = np.diag([1,x]) >>> is_hermitian(m5) True >>> m6 = np.array([[1,x],[-x,2]]) >>> is_hermitian(m6) False """ return matrix_eq(np.array(matrix).transpose().conjugate(), matrix) # type: ignore @typechecked def is_unitary(matrix: Matrix) -> bool: """Checks whether the matrix in parameter is unitary. Args: matrix: Matrix for which we want to know if it is unitary. Returns: ``True`` if the matrix in parameter is Unitary. Example: >>> a = np.array([[1,1],[1,-1]]) >>> is_unitary(a) False >>> is_unitary(a/np.sqrt(2)) True """ return matrix_eq( np.eye(len(matrix), dtype=np.complex64), matrix.transpose().conjugate().dot(matrix), ) @typechecked def cos(angle: Expr | Real) -> sp.Expr | float: """Generalization of the cosine function, to take as input either ``sympy``'s expressions or floating numbers. Args: angle: The angle considered. Returns: Cosine of the given ``angle``. """ if isinstance(angle, Real): if TYPE_CHECKING: assert isinstance(angle, float) return np.cos(angle) else: import sympy as sp from sympy import Expr res = sp.cos(angle) assert isinstance(res, Expr) return res @typechecked def sin(angle: Expr | Real) -> sp.Expr | float: """Generalization of the sine function, to take as input either ``sympy``'s expressions or floating numbers. Args: angle: The angle considered. Returns: Sine of the given ``angle``. """ if isinstance(angle, Real): if TYPE_CHECKING: assert isinstance(angle, float) return np.sin(angle) else: import sympy as sp from sympy import Expr res = sp.sin(angle) assert isinstance(res, Expr) return res @typechecked def exp(angle: Expr | Complex) -> sp.Expr | complex: """Generalization of the exponential function, to take as input either ``sympy``'s expressions or floating numbers. Args: angle: The angle considered. Returns: Exponential of the given ``angle``. """ if isinstance(angle, Complex): if TYPE_CHECKING: assert isinstance(angle, complex) return np.exp(angle) else: import sympy as sp from sympy import Expr res = sp.exp(angle) assert isinstance(res, Expr) return res def rand_orthogonal_matrix( size: int, seed: Optional[int] = None ) -> npt.NDArray[np.complex64]: """Generate a random orthogonal matrix optionally with a given seed. Args: size: Size (number of columns) of the square matrix to generate. seed: Seed used to control the random generation of the matrix. Returns: A random orthogonal matrix. Examples: >>> rand_orthogonal_matrix(3) # doctest: +SKIP array([[ 0.94569439, 0.2903415 , 0.14616405], [-0.32503798, 0.83976928, 0.43489984], [ 0.0035254 , -0.45879121, 0.88853711]]) >>> rand_orthogonal_matrix(3, seed=42) array([[ 0.21667149, 0.1867762 , 0.95821089], [ 0.9608116 , 0.13303749, -0.24319148], [-0.17290035, 0.9733528 , -0.15063131]]) """ np.random.seed(seed) m = np.random.rand(size, size) return m.dot(inv(sqrtm(m.T.dot(m)))) def rand_clifford_matrix(nb_qubits: int) -> npt.NDArray[np.complex64]: """Generate a random Clifford matrix. Args: size: Size (number of columns) of the square matrix to generate. Returns: A random Clifford matrix. Examples: >>> rand_clifford_matrix(2) # doctest: +SKIP array([[ 0.5+0.j, -0.5+0.j, 0.5+0.j, -0.5+0.j], [-0.5+0.j, 0.5+0.j, 0.5+0.j, -0.5+0.j], [ 0.5+0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j], [-0.5+0.j, -0.5+0.j, 0.5+0.j, 0.5+0.j]]) """ from qiskit import quantum_info return quantum_info.random_clifford( nb_qubits ).to_matrix() # pyright: ignore[reportReturnType] def rand_unitary_2x2_matrix() -> npt.NDArray[np.complex64]: """Generate a random one-qubit unitary matrix. Args: size: Size (number of columns) of the square matrix to generate. Returns: A random Clifford matrix. Examples: >>> rand_unitary_2x2_matrix() # doctest: +SKIP array([[ 0.86889957+0.j , 0.44138577+0.22403602j], [-0.44138577-0.22403602j, -0.72981565-0.47154594j]]) """ theta, phi, gamma = np.random.rand(3) * 2 * math.pi c, s, eg, ep = ( np.cos(theta / 2), np.sin(theta / 2), np.exp(gamma * 1j), np.exp(phi * 1j), ) return np.array([[c, -eg * s], [eg * s, eg * ep * c]]) def rand_product_local_unitaries(nb_qubits: int) -> npt.NDArray[np.complex64]: """Generate a pseudo random matrix, resulting from a tensor product of random unitary matrices. Args: nb_qubits: Number of qubits on which the product of unitaries will act. Returns: A tensor product of random unitary matrices. Example: >>> rand_product_local_unitaries(2) # doctest: +SKIP array([[-0.39648015+0.j , 0.49842218-0.16609181j, 0.39826454-0.21692223j, -0.40979321+0.43953607j], [-0.49842218+0.16609181j, 0.14052896-0.37073997j, 0.40979321-0.43953607j, 0.06167784+0.44929471j], [-0.39826454+0.21692223j, 0.40979321-0.43953607j, 0.16112375-0.36226461j, -0.05079312+0.52290651j], [-0.40979321+0.43953607j, -0.06167784-0.44929471j, 0.05079312-0.52290651j, 0.28163685+0.27906487j]]) """ return reduce(np.kron, [rand_unitary_2x2_matrix() for _ in range(nb_qubits - 1)]) def rand_hermitian_matrix(size: int) -> npt.NDArray[np.complex64]: """Generate a random Hermitian matrix. Args: size: Size (number of columns) of the square matrix to generate. Returns: A random Hermitian Matrix. Example: >>> rand_hermitian_matrix(2) # doctest: +SKIP array([[1.4488624 +0.j, 0.20804943+0.j], [0.20804943+0.j, 0.7826408 +0.j]], dtype=complex64) """ m = np.random.rand(size, size).astype(np.complex64) return m + m.conjugate().transpose()
https://github.com/xin-0/QC-jupyter
xin-0
import numpy as np from qiskit.tools.jupyter import * from qiskit import IBMQ # ibm account manager # - communicate with online account # - store/delete # - enable/disenable # - communicate with ibmq online devices, quantum computers # - get actual quantum computers as backend IBMQ.load_account() provider = IBMQ.ibmq.get_provider(hub='ibm-q', group='open', project='main') provider.backends() backend = provider.get_backend('ibmq_bogota') back_config = backend.configuration() print("number of qubit: ", back_config.n_qubits) print("support open pulse?: ", back_config.open_pulse) print("basic gate set: ", back_config.basis_gates) dt = back_config.dt print(f"Sampling time: {dt*1e9} ns") back_defualt = backend.defaults() # frequncies for all the 5 qubits back_defualt.qubit_freq_est GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microsecond ns = 1.0e-9 # Nanosecond # the index of the qubit in backend that we want to find frequency with qubitIdx = 4 mem_slot = 0 # define the search range and get a list of frequencies center_f_Hz = back_defualt.qubit_freq_est[qubitIdx] f_span = 50 * MHz f_step = 1 * MHz f_min = center_f_Hz - f_span/2 f_max = center_f_Hz + f_span/2 frequencies_GHz = np.arange(f_min/GHz, f_max/GHz, f_step/GHz) print(f"We'll measure the {qubitIdx}th qubit in {back_config.backend_name} \n") print(f"sweep from {frequencies_GHz[0]} GHz to {frequencies_GHz[-1]} GHz with approximated frequncy {center_f_Hz/GHz} GHz") # samples need to be multiples of 16 def get_closest_multiple_of_16(num): return int(num + 8 ) - (int(num + 8 ) % 16) from qiskit import pulse from qiskit.circuit import Parameter drive_sigma_sec = 0.075 * us drive_duration_sec = 8 * drive_sigma_sec drive_amp =0.05 freq = Parameter('freq') with pulse.build(backend=backend, default_alignment='sequential', name='freq_sweep') as sweep_plan: drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec)) drive_sigma = pulse.seconds_to_samples(drive_sigma_sec) drive_chan = pulse.drive_channel(qubitIdx) pulse.set_frequency(freq, drive_chan) pulse.play(pulse.Gaussian( duration=drive_duration, sigma=drive_sigma, amp=drive_amp, name='freq_sweep_excitation_pulse' ),channel=drive_chan) pulse.measure(qubits=[qubitIdx], registers=[pulse.MemorySlot(mem_slot)]) frequencies_Hz = frequencies_GHz * GHz schedules = [sweep_plan.assign_parameters({freq: f}, inplace=False) for f in frequencies_Hz] schedules[0].draw(backend=backend)
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
from Grover.grover_num_list_cirq import find_num, find_num_list from qiskit.visualization import plot_histogram, plot_coupling_map from backend_operation import run_simulator, get_transpiled_circuits_of_circuit, get_fake_backend_list,get_unitary, get_fake_backend, get_fake_backend_list from qiskit import transpile import qiskit.providers.fake_provider from qiskit_ibm_provider import IBMProvider from qiskit.transpiler.passes import RemoveBarriers from qiskit_aer import AerSimulator, Aer Aer.get_backend('aer_simulator') x=AerSimulator() AerSimulator.available_methods(x) 5 import qiskit_ibm_runtime.fake_provider from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister from bit_functions import full_bitfield, get_qubit_list dir(qiskit_ibm_runtime.fake_provider) backend = qiskit_ibm_runtime.fake_provider.FakeAuckland() # GenericBackendV2 = Aer () backend = qiskit.providers.fake_provider.GenericBackendV2(num_qubits=5) circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0,1) circuit.cx(0,2) circuit.measure_all() circuit.draw('mpl') backend.coupling_map.draw() circuit.data # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(circuit, backend, optimization_level=0) transpiled_circuit.draw('mpl') transpiled_circuit.data # Run the transpiled circuit using the simulated backend job = backend.run(transpiled_circuit) counts = job.result().get_counts() plot_histogram(counts) dir(qiskit.providers.fake_provider) import random import timeit import matplotlib.colors as mcolors from itertools import combinations, permutations block_diagram = False qc_size = 4 fake_backed_name = 'FakeAuckland' #random.sample(get_fake_backend_list(min_qubit=len(experiments[0].qubits), max_qubit=len(experiments[0].qubits) + 10),1)[0][0] num_qubits = 3 num_list = list(range(2**num_qubits)) final_expermient = [] for winner in num_list: grover_num = find_num() grover_num.build_iteration([winner],circuit_nqubits=num_qubits, block_diagram=block_diagram) grover_num.create_grover(solutions = 1, block_diagram=block_diagram) final_expermient.append(grover_num.measure_qc[0]) transpiled_circuit = [ get_transpiled_circuits_of_circuit(qc, ['Aer', fake_backed_name], [None] + list(permutations(range(num_qubits))), optimization_level_list=[0,3]) for qc in final_expermient ] result_for_circuiut = [ [ run_simulator(qc,shots = 1024 * 4) for qc in qc_value ] for qc_value in transpiled_circuit ] output = [] for value, circuits in enumerate(result_for_circuiut): for index, run_circuit in enumerate(circuits): result_dict= run_circuit.to_dict() cirq_result = result_dict['results'][0] cirq_counts = cirq_result['data']['counts'] cirq_time = cirq_result['time_taken'] cirq_name = cirq_result['header']['name'] cirq_depth = transpiled_circuit[value][index].depth() output.append({'value' : value, 'name' : cirq_name, 'time_taken' :cirq_time, 'depth':cirq_depth, 'count':cirq_counts}) data = { 'Value' : [], 'Backend' : [], 'Qubit_Position' : [], 'Optimization_level' : [], 'Depth' : [], 'Time_Taken' : [], 'Counts' : [] } for cur_data in output: data['Value'].append(cur_data['value']) data['Backend'].append(cur_data['name'].split('|')[0].replace(" ","")) data['Qubit_Position'].append(cur_data['name'].split('|')[1].replace(" ","")) data['Optimization_level'].append(cur_data['name'].split('|')[2].replace(" ","")) data['Depth'].append(cur_data['depth']) data['Time_Taken'].append(cur_data['time_taken']) data['Counts'].append([cur_data['count'][f'0x{index}'] for index in range(len(cur_data['count']))]) for cur_data in output: data['Value'].append(cur_data['value']) # Assuming value is stored at index 0 in each sublist backend, qubit_position, optimization_level = cur_data['name'].split('|') data['Backend'].append(backend.strip()) data['Qubit_Position'].append(qubit_position.strip()) data['Optimization_level'].append(optimization_level.strip()) data['Depth'].append(cur_data['depth']) # Assuming depth is stored at index 2 in each sublist data['Time_Taken'].append(cur_data['time_taken']) # Assuming time_taken is stored at index 3 in each sublist counts = [cur_data['count'][f'0x{index}'] for index in range(len(cur_data['count']))] # Assuming counts is stored at index 4 in each sublist data['Counts'].append(counts) import pandas as pd data = pd.DataFrame(data) data output min_value = 5 max_value = 15 win = random.sample(range(min_value, max_value),1) print(win) grover_find_value_win_size = find_num() grover_find_value_win_size.build_iteration(win, block_diagram=block_diagram) grover_find_value_win_size.create_grover(block_diagram=block_diagram, solutions=len(list(win))) experiments = grover_find_value_win_size.measure_qc experiments[0].draw('mpl') fake_backed_name = 'FakeAuckland' #random.sample(get_fake_backend_list(min_qubit=len(experiments[0].qubits), max_qubit=len(experiments[0].qubits) + 10),1)[0][0] get_fake_backend_list() backend = get_fake_backend('FakeGuadalupeV2') print(backend.coupling_map) backend.coupling_map.draw() transpiled_qc_list = get_transpiled_circuits_of_circuit(experiments[0], ['Aer', fake_backed_name], [None, 'Full_Range'], optimization_level_list=[0,3]) plot_histogram({ qc.name : qc.depth() for qc in transpiled_qc_list }) transpiled_qc_list[0].draw('mpl') transpiled_qc_list[1].draw('mpl') transpiled_qc_list[4].draw('mpl') transpiled_qc_list[5].draw('mpl') plot_histogram([run_simulator(qc,shots = 1024 * 4).get_counts() for qc in transpiled_qc_list], legend=[qc.name for qc in transpiled_qc_list], color=list(random.choices(list(mcolors.get_named_colors_mapping().values()), k = len(transpiled_qc_list))), title="Result transpilers") num_list_num = 4 data_arr = list(range(num_list_num)) random.shuffle(data_arr) win = random.sample(data_arr, 1) print(f"Data array: {data_arr} , the winner: {win}") st = timeit.default_timer() sol = [] for i, val in enumerate(data_arr): if val in win: sol.append(i) end = timeit.default_timer() print(f"Time: {end - st} , solution : {sol}") grover_find_value_list = find_num_list() grover_find_value_list.build_iteration(win, block_diagram=block_diagram, num_array = data_arr) grover_find_value_list.create_grover(block_diagram=block_diagram, num_solutions=len(list(win))) experiments = grover_find_value_list.measure_qc print(experiments) experiments[0].draw('mpl') x = find_num_list() x.build_iteration(winner_list=[5],num_array = [0,5,3], block_diagram=False) x.create_grover(num_solutions=1,block_diagram=False) x.measure_qc[0].draw('mpl') from Grover.transpiler import * qc = remove_barriar_gate(x.measure_qc[0]) qc.draw('mpl') qc, did_remove = remove_similiar_adjacent(qc) qc.draw('mpl') transpiled_qc_list = get_transpiled_circuits_of_circuit(experiments[0], ['Aer', fake_backed_name], [None, 'Full_Range'], optimization_level_list=[0,3]) plot_histogram({ qc.name : qc.depth() for qc in transpiled_qc_list }) qc_result = [run_simulator(qc, shots = 1024 * 4) for qc in transpiled_qc_list] plot_histogram([qc.get_counts() for qc in qc_result], legend=[qc.name for qc in transpiled_qc_list], color=list(random.choices(list(mcolors.get_named_colors_mapping().values()), k = len(transpiled_qc_list))), title="Result transpilers") [{qc.name : result.time_taken} for result, qc in zip(qc_result, transpiled_qc_list)] for qc in transpiled_qc_list: print(qc.qubits) transpiled_qc_list[1].draw('mpl') transpiled_qc_list[6].draw('mpl') transpiled_qc_list[1].draw('mpl') for gate in transpiled_qc_list[1].data: print(gate) transpiled_qc_list[5].draw('mpl')
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import BasicSwap from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num couplingList = list() for i in range(3): for j in range(3): if i is not j: couplingList.append([i, j]) squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates squareCouplingMap = CouplingMap(squareCouplingList) couplingMap = CouplingMap(couplingList) qcHERR = QuantumCircuit(4) qcHERR.x(0) qcHERR.x(1) qcHERR.ccx(0, 1, 2) qcHERR.measure_all() qcHERR = qcHERR.decompose() nonHERR = QuantumCircuit(4) nonHERR.x(0) nonHERR.x(1) nonHERR.ccx(0, 1, 2) nonHERR.measure_all() circDag = circuit_to_dag(qcHERR) transpiledBasic = transpile(qcHERR, Aer.get_backend('qasm_simulator'), coupling_map=squareCouplingMap, basis_gates=basis_gates, routing_method='basic', layout_method='trivial') transpiledSabre = transpile(qcHERR, Aer.get_backend('qasm_simulator'), coupling_map=squareCouplingMap, basis_gates=basis_gates, routing_method='sabre', layout_method='trivial') transpiledStochastic = transpile(qcHERR, Aer.get_backend('qasm_simulator'), coupling_map=squareCouplingMap, basis_gates=basis_gates, routing_method='stochastic', layout_method='trivial') transpiledLookahead = transpile(qcHERR, Aer.get_backend('qasm_simulator'), coupling_map=squareCouplingMap, basis_gates=basis_gates, routing_method='lookahead', layout_method='trivial') s = '0111' for i in range(100): # Create a noise model for the simulations noise_model = noise.NoiseModel() err1Rate, err2Rate, err3Rate, err4Rate = random.randrange(1, 20, 1)/100.0, random.randrange(1, 20, 1)/100.0, random.randrange(1, 20, 1)/100.0,\ random.randrange(1, 10, 1)/100.0 error_1 = noise.depolarizing_error(err1Rate, 2) error_2 = noise.depolarizing_error(err2Rate, 2) error_3 = noise.depolarizing_error(err3Rate, 2) error_4 = noise.depolarizing_error(err4Rate, 2) noise_model.add_quantum_error(error_1, ['cx'], [0, 1]) noise_model.add_quantum_error(error_2, ['cx'], [1, 2]) noise_model.add_quantum_error(error_3, ['cx'], [2, 3]) noise_model.add_quantum_error(error_4, ['cx'], [0, 3]) # Generate a noise graph to pass into HERR noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 2]) noiseGraph.add_edge(0, 1, weight=1.0-err1Rate) noiseGraph.add_edge(1, 2, weight=1.0-err2Rate) noiseGraph.add_edge(2, 3, weight=1.0-err3Rate) noiseGraph.add_edge(0, 3, weight=1.0-err4Rate) herr = HERR.HERR(squareCouplingMap, noiseGraph) basSwap = BasicSwap(squareCouplingMap) #print(squareCouplingMap) # Run HERR HERRRes = herr.run(circDag) updatedCirc = dag_to_circuit(HERRRes) bSwapRes = basSwap.run(circDag) bSwapCirc = dag_to_circuit(bSwapRes) # Transpile HERR transpiledHERR = transpile(updatedCirc, Aer.get_backend('qasm_simulator'), coupling_map=squareCouplingMap, basis_gates=basis_gates, routing_method='basic', layout_method='trivial') # HERRCnotGateNum = countTwoQubitGates(transpiledHERR) # normalCnotGateNum = countTwoQubitGates(transpiledNormal) # print(str(HERRCnotGateNum) + " " + str(normalCnotGateNum)) sim = Aer.get_backend('qasm_simulator') simResultHERR = sim.run(transpiledHERR, noise_model=noise_model).result() simResultBasic = sim.run(transpiledBasic, noise_model=noise_model).result() simResultSabre = sim.run(transpiledSabre, noise_model=noise_model).result() simResultLookahead = sim.run(transpiledLookahead, noise_model=noise_model).result() simResultStochastic = sim.run(transpiledStochastic, noise_model=noise_model).result() # Output file and print results fName = "HERRQFTCouplingOutputs/HERRCirc" + str(i) + ".png" fName2 = "HERRQFTCouplingOutputs/NonCirc" + str(i) + ".png" #updatedCirc.draw(output='mpl', filename=fName) #bSwapCirc.draw(output='mpl', filename=fName2) #if transpiledNormal != transpiledHERR: #print("CIRCUIT CHANGED") #updatedCirc.draw(output='mpl', filename=fName) #bSwapCirc.draw(output='mpl', filename=fName2) #print("Iter: " + str(i) + " ErrorRate of edges (0,1) (1, 2), (0, 2), (1, 3), (2, 3), (0, 3) counts for HERR/nonHERR:") #print(str(err1Rate) + " " + str(err2Rate) + " " + str(err3Rate) + " " + str(err4Rate) + " " + str(err5Rate) + " " + str(err6Rate)) print(str(simResultHERR.get_counts()[s]/1024.0) + " " + str(simResultBasic.get_counts()[s]/1024.0) + " " + str(simResultSabre.get_counts()[s]/1024.0) + " " + str(simResultLookahead.get_counts()[s]/1024.0) + " " + str(simResultStochastic.get_counts()[s]/1024.0))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram from qiskit.providers.aer import QasmSimulator # use Aer's qasm_simulator simulator = QasmSimulator() # create quantum circute acting on the q register circuit = QuantumCircuit(2,2) # add a H gate on qubit 0 circuit.h(0) # add a cx (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0,1) # map the quantum measurement to the classical bits circuit.measure([0,1],[0,1]) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1024) # grad results from the job result = job.result() # return counts counts = result.get_counts(compiled_circuit) print('total count for 00 and 11 are: ',counts) # draw circuit circuit.draw(output='mpl') # plot histogram plot_histogram(counts) from qiskit.circuit import QuantumCircuit, Parameter from qiskit.providers.aer import AerSimulator backend = AerSimulator() circuit = QuantumCircuit(2) theta = Parameter('theta') circuit.rx(234, 0) circuit.draw(output='mpl') backend = AerSimulator() circuit = QuantumCircuit(2) # theta = Parameter('theta') circuit.rx(20, 0) circuit.x(0) circuit.h(1) result = execute(circuit, backend=backend, shots=1024).result() # counts=result.get_counts() # print(counts) circuit.draw(output='mpl')
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit from qiskit.circuit.library import CPhaseGate, HGate, TGate, XGate, YGate, ZGate from qiskit.converters import circuit_to_dag, dag_to_circuit import random, itertools class RandomCircuit(object): def __init__(self, width, depth, connection_degree, num_hadamards, seed) -> None: """ Generate a random benchmark circuit width: number of qubits depth: depth of the random circuit connection_degree: max number of direct contacts num_hadamards: number of H gates in the encoding layer. Overall number of solutions = 2^num_H """ super().__init__() random.seed(seed) self.width = width self.depth = depth self.num_hadamards = num_hadamards self.num_targets_ubs = [] for qubit in range(width): max_num_targets = self.width - 1 - qubit num_targets_ub = int(connection_degree * max_num_targets) if qubit < width - 1: num_targets_ub = max(num_targets_ub, 1) self.num_targets_ubs.append(num_targets_ub) # print('num_targets_ubs = {}'.format(self.num_targets_ubs)) def generate(self): entangled_circuit, num_targets = self.generate_entangled() """ Encode random solution states """ encoding_qubits = random.sample(range(self.width), self.num_hadamards) quantum_states = [["0"] for qubit in range(self.width)] for qubit in encoding_qubits: entangled_circuit.append(instruction=HGate(), qargs=[qubit]) quantum_states[qubit] = ["0", "1"] solution_states_strings = itertools.product(*quantum_states) solution_states = [] for binary_state in solution_states_strings: binary_state = "".join(binary_state[::-1]) state = int(binary_state, 2) solution_states.append(state) # print('%d 2q gates. %d tensor factors. %d depth.'%( # entangled_circuit.num_nonlocal_gates(), # entangled_circuit.num_unitary_factors(), # entangled_circuit.depth() # )) # print('num_targets = {}'.format(num_targets)) return entangled_circuit, solution_states def generate_entangled(self): left_circuit = QuantumCircuit(self.width, name="q") left_dag = circuit_to_dag(left_circuit) right_circuit = QuantumCircuit(self.width, name="q") right_dag = circuit_to_dag(right_circuit) qubit_targets = {qubit: set() for qubit in range(self.width)} while True: """ Apply a random two-qubit gate to either left_dag or right_dag """ random_control_qubit_idx = self.get_random_control(qubit_targets) random_target_qubit_idx = self.get_random_target( random_control_qubit_idx, qubit_targets ) dag_to_apply = random.choice([left_dag, right_dag]) random_control_qubit = dag_to_apply.qubits[random_control_qubit_idx] random_target_qubit = dag_to_apply.qubits[random_target_qubit_idx] dag_to_apply.apply_operation_back( op=CPhaseGate(theta=0.0), qargs=[random_control_qubit, random_target_qubit], cargs=[], ) qubit_targets[random_control_qubit_idx].add(random_target_qubit_idx) """ Apply a random 1-q gate to left_dag Apply its inverse to right_dag """ single_qubit_gate = random.choice( [HGate(), TGate(), XGate(), YGate(), ZGate()] ) random_qubit = left_dag.qubits[random.choice(range(self.width))] left_dag.apply_operation_back( op=single_qubit_gate, qargs=[random_qubit], cargs=[] ) right_dag.apply_operation_front( op=single_qubit_gate.inverse(), qargs=[random_qubit], cargs=[] ) """ Terminate when there is enough depth """ if left_dag.depth() + right_dag.depth() >= self.depth: break entangled_dag = left_dag.compose(right_dag, inplace=False) entangled_circuit = dag_to_circuit(entangled_dag) num_targets = [len(qubit_targets[qubit]) for qubit in range(self.width)] for qubit in range(self.width): assert num_targets[qubit] <= self.num_targets_ubs[qubit] return entangled_circuit, num_targets def get_random_control(self, qubit_targets): """ Get a random control qubit Prioritize the ones with spare targets Else choose from qubits with #targets>0 """ candidates = [] for qubit in qubit_targets: if len(qubit_targets[qubit]) < self.num_targets_ubs[qubit]: candidates.append(qubit) if len(candidates) > 0: return random.choice(candidates) else: candidates = [] for qubit, num_targets in enumerate(self.num_targets_ubs): if num_targets > 0: candidates.append(qubit) return random.choice(candidates) def get_random_target(self, control_qubit, qubit_targets): """ Get a random target qubit If the control qubit has exhausted its #targets, choose from existing targets Else prioritize the ones that have not been used """ if len(qubit_targets[control_qubit]) < self.num_targets_ubs[control_qubit]: candidates = [] for qubit in range(control_qubit + 1, self.width): if qubit not in qubit_targets[control_qubit]: candidates.append(qubit) return random.choice(candidates) else: return random.choice(list(qubit_targets[control_qubit]))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_circuit_layout from qiskit.tools.monitor import job_monitor from qiskit.providers.fake_provider import FakeVigoV2 import matplotlib.pyplot as plt ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = FakeVigoV2() new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend)
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. # # 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 qiskit/tools/parallel""" import os import time from unittest.mock import patch from qiskit.tools.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase def _parfunc(x): """Function for testing parallel_map""" time.sleep(1) return x def _build_simple_circuit(_): qreg = QuantumRegister(2) creg = ClassicalRegister(2) qc = QuantumCircuit(qreg, creg) return qc def _build_simple_schedule(_): return Schedule() class TestGetPlatformParallelDefault(QiskitTestCase): """Tests get_parallel_default_for_platform.""" def test_windows_parallel_default(self): """Verifies the parallel default for Windows.""" with patch("sys.platform", "win32"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_mac_os_unsupported_version_parallel_default(self): """Verifies the parallel default for macOS.""" with patch("sys.platform", "darwin"): with patch("sys.version_info", (3, 8, 0, "final", 0)): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, False) def test_other_os_parallel_default(self): """Verifies the parallel default for Linux and other OSes.""" with patch("sys.platform", "linux"): parallel_default = get_platform_parallel_default() self.assertEqual(parallel_default, True) class TestParallel(QiskitTestCase): """A class for testing parallel_map functionality.""" def test_parallel_env_flag(self): """Verify parallel env flag is set""" self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE") def test_parallel(self): """Test parallel_map""" ans = parallel_map(_parfunc, list(range(10))) self.assertEqual(ans, list(range(10))) def test_parallel_circuit_names(self): """Verify unique circuit names in parallel""" out_circs = parallel_map(_build_simple_circuit, list(range(10))) names = [circ.name for circ in out_circs] self.assertEqual(len(names), len(set(names))) def test_parallel_schedule_names(self): """Verify unique schedule names in parallel""" out_schedules = parallel_map(_build_simple_schedule, list(range(10))) names = [schedule.name for schedule in out_schedules] self.assertEqual(len(names), len(set(names)))
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
import qiskit import numpy as np X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]]) y_train = [0, 1, 0, 1] X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]]) y_test = [0, 1] from dc_qiskit_qml.encoding_maps import EncodingMap import scipy.sparse as sparse class MyEncodingMap(EncodingMap): def map(self, input_vector: list) -> sparse.dok_matrix: result = sparse.dok_matrix((4,1)) index = 0 if input_vector[0] > 0 and input_vector[1] > 0: index = 0 if input_vector[0] < 0 < input_vector[1]: index = 1 if input_vector[0] < 0 and input_vector[1] < 0: index = 2 if input_vector[0] > 0 > input_vector[1]: index = 3 result[index, 0] = 1.0 return result encoding_map = MyEncodingMap() import matplotlib.pyplot as plt plt.scatter( X_train[:,0], X_train[:,1], color=['red' if yy == 0 else 'blue' for yy in y_train], marker='x', s=200) plt.scatter( X_test[:,0], X_test[:,1], color=['red' if yy == 0 else 'blue' for yy in y_test], marker='o', s=200) plt.hlines(0.0, -1.0, 1.0) plt.vlines(0.0, -1.0, 1.0) plt.show() from qiskit_aer.backends.aerbackend import AerBackend from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=False) execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator') qml = QmlHadamardNeighborClassifier(backend=execution_backend, shots=8192, encoding_map=encoding_map, classifier_circuit_factory=initial_state_builder) qml.fit(X_train, y_train) qml.predict(X_test), y_test qml._last_predict_circuits[0].draw(output='mpl', fold=-1) initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=True) execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator') qml = QmlHadamardNeighborClassifier(backend=execution_backend, shots=8192, encoding_map=encoding_map, classifier_circuit_factory=initial_state_builder) qml.fit(X_train, y_train) qml.predict(X_test), y_test qml._last_predict_circuits[0].draw(output='mpl', fold=-1) from qiskit_ibm_provider import IBMProvider, IBMBackend provider : IBMProvider = IBMProvider() ibm_brisbane: IBMBackend = provider.get_backend('ibm_brisbane') transpiled_qc = qiskit.transpile(qml._last_predict_circuits[0], backend=ibm_brisbane) qobj = qiskit.assemble(transpiled_qc, backend=ibm_brisbane) print("Number of gates: {}.\n".format(len(transpiled_qc.data)))
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ CNOTDihedral operator class. """ from __future__ import annotations import itertools import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic.pauli import Pauli from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.mixins import generate_apidocs, AdjointMixin from qiskit.circuit import QuantumCircuit, Instruction from .dihedral_circuits import _append_circuit from .polynomial import SpecialPolynomial class CNOTDihedral(BaseOperator, AdjointMixin): """An N-qubit operator from the CNOT-Dihedral group. The CNOT-Dihedral group is generated by the quantum gates, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.TGate`, and :class:`~qiskit.circuit.library.XGate`. **Representation** An :math:`N`-qubit CNOT-Dihedral operator is stored as an affine function and a phase polynomial, based on the convention in references [1, 2]. The affine function consists of an :math:`N \\times N` invertible binary matrix, and an :math:`N` binary vector. The phase polynomial is a polynomial of degree at most 3, in :math:`N` variables, whose coefficients are in the ring Z_8 with 8 elements. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral circ = QuantumCircuit(3) circ.cx(0, 1) circ.x(2) circ.t(1) circ.t(1) circ.t(1) elem = CNOTDihedral(circ) # Print the CNOTDihedral element print(elem) .. parsed-literal:: phase polynomial = 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 affine function = (x_0,x_0 + x_1,x_2 + 1) **Circuit Conversion** CNOTDihedral operators can be initialized from circuits containing *only* the following gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.TGate`, :class:`~qiskit.circuit.library.TdgGate` :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CSGate`, :class:`~qiskit.circuit.library.CSdgGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.CCZGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~CNOTDihedral.to_circuit` or :meth:`~CNOTDihderal.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates if the number of qubits is more than two. CNOTDihedral operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ def __init__( self, data: CNOTDihedral | QuantumCircuit | Instruction | None = None, num_qubits: int | None = None, validate: bool = True, ): """Initialize a CNOTDihedral operator object. Args: data (CNOTDihedral or QuantumCircuit or ~qiskit.circuit.Instruction): Optional, operator to initialize. num_qubits (int): Optional, initialize an empty CNOTDihedral operator. validate (bool): if True, validates the CNOTDihedral element. Raises: QiskitError: if the type is invalid. QiskitError: if validate=True and the CNOTDihedral element is invalid. """ if num_qubits: # initialize n-qubit identity self._num_qubits = num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from another CNOTDihedral by sharing the underlying # poly, linear and shift elif isinstance(data, CNOTDihedral): self.linear = data.linear self.shift = data.shift self.poly = data.poly # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.is_unitary() or set(data._input_dims) != {2} or data.num_qubits is None: raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") self._num_qubits = data.num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): self._num_qubits = data.num_qubits elem = self._from_circuit(data) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift elif isinstance(data, Pauli): self._num_qubits = data.num_qubits elem = self._from_circuit(data.to_instruction()) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift else: raise QiskitError("Invalid input type for CNOTDihedral class.") # Initialize BaseOperator super().__init__(num_qubits=self._num_qubits) # Validate the CNOTDihedral element if validate and not self._is_valid(): raise QiskitError("Invalid CNOTDihedral element.") @property def name(self): """Unique string identifier for operation type.""" return "cnotdihedral" @property def num_clbits(self): """Number of classical bits.""" return 0 def _z2matmul(self, left, right): """Compute product of two n x n z2 matrices.""" prod = np.mod(np.dot(left, right), 2) return prod def _z2matvecmul(self, mat, vec): """Compute mat*vec of n x n z2 matrix and vector.""" prod = np.mod(np.dot(mat, vec), 2) return prod def _dot(self, other): """Left multiplication self * other.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(self.linear, other.shift), self.shift) ] result.linear = self._z2matmul(self.linear, other.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(self.num_qubits)[np.nonzero(other.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if other.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = other.poly + self.poly.evaluate(new_vars) return result def _compose(self, other): """Right multiplication other * self.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(other.linear, self.shift), other.shift) ] result.linear = self._z2matmul(other.linear, self.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(other.num_qubits)[np.nonzero(self.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if self.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = self.poly + other.poly.evaluate(new_vars) return result def __eq__(self, other): """Test equality.""" return ( isinstance(other, CNOTDihedral) and self.poly == other.poly and (self.linear == other.linear).all() and (self.shift == other.shift).all() ) def _append_cx(self, i, j): """Apply a CX gate to this element. Left multiply the element by CX(i, j). """ if not 0 <= i < self.num_qubits or not 0 <= j < self.num_qubits: raise QiskitError("CX qubits are out of bounds.") self.linear[j] = (self.linear[i] + self.linear[j]) % 2 self.shift[j] = (self.shift[i] + self.shift[j]) % 2 def _append_phase(self, k, i): """Apply an k-th power of T to this element. Left multiply the element by T_i^k. """ if not 0 <= i < self.num_qubits: raise QiskitError("phase qubit out of bounds.") # If the kth bit is flipped, conjugate this gate if self.shift[i] == 1: k = (7 * k) % 8 # Take all subsets \alpha of the support of row i # of weight up to 3 and add k*(-2)**(|\alpha| - 1) mod 8 # to the corresponding term. support = np.arange(self.num_qubits)[np.nonzero(self.linear[i])] subsets_2 = itertools.combinations(support, 2) subsets_3 = itertools.combinations(support, 3) for j in support: value = self.poly.get_term([j]) self.poly.set_term([j], (value + k) % 8) for j in subsets_2: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + -2 * k) % 8) for j in subsets_3: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + 4 * k) % 8) def _append_x(self, i): """Apply X to this element. Left multiply the element by X(i). """ if not 0 <= i < self.num_qubits: raise QiskitError("X qubit out of bounds.") self.shift[i] = (self.shift[i] + 1) % 2 def __str__(self): """Return formatted string representation.""" out = "phase polynomial = \n" out += str(self.poly) out += "\naffine function = \n" out += " (" for row in range(self.num_qubits): wrote = False for col in range(self.num_qubits): if self.linear[row][col] != 0: if wrote: out += " + x_" + str(col) else: out += "x_" + str(col) wrote = True if self.shift[row] != 0: out += " + 1" if row != self.num_qubits - 1: out += "," out += ")\n" return out def to_circuit(self): """Return a QuantumCircuit implementing the CNOT-Dihedral element. Return: QuantumCircuit: a circuit implementation of the CNOTDihedral object. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ from qiskit.synthesis.cnotdihedral import synth_cnotdihedral_full return synth_cnotdihedral_full(self) def to_instruction(self): """Return a Gate instruction implementing the CNOTDihedral object.""" return self.to_circuit().to_gate() def _from_circuit(self, circuit): """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: CNOTDihedral: the CNOTDihedral object for the circuit. Raises: QiskitError: if the input instruction is not CNOTDihedral or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity CNOTDihedral object elem = CNOTDihedral(num_qubits=self._num_qubits) _append_circuit(elem, circuit) return elem def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) def compose( self, other: CNOTDihedral, qargs: list | None = None, front: bool = False ) -> CNOTDihedral: if qargs is not None: raise NotImplementedError("compose method does not support qargs.") if self.num_qubits != other.num_qubits: raise QiskitError("Incompatible dimension for composition") if front: other = self._dot(other) else: other = self._compose(other) other.poly.weight_0 = 0 # set global phase return other def _tensor(self, other, reverse=False): """Returns the tensor product operator.""" if not isinstance(other, CNOTDihedral): raise QiskitError("Tensored element is not a CNOTDihderal object.") if reverse: elem0 = self elem1 = other else: elem0 = other elem1 = self result = CNOTDihedral(num_qubits=elem0.num_qubits + elem1.num_qubits) linear = np.block( [ [elem0.linear, np.zeros((elem0.num_qubits, elem1.num_qubits), dtype=np.int8)], [np.zeros((elem1.num_qubits, elem0.num_qubits), dtype=np.int8), elem1.linear], ] ) result.linear = linear shift = np.block([elem0.shift, elem1.shift]) result.shift = shift for i in range(elem0.num_qubits): value = elem0.poly.get_term([i]) result.poly.set_term([i], value) for j in range(i): value = elem0.poly.get_term([j, i]) result.poly.set_term([j, i], value) for k in range(j): value = elem0.poly.get_term([k, j, i]) result.poly.set_term([k, j, i], value) for i in range(elem1.num_qubits): value = elem1.poly.get_term([i]) result.poly.set_term([i + elem0.num_qubits], value) for j in range(i): value = elem1.poly.get_term([j, i]) result.poly.set_term([j + elem0.num_qubits, i + elem0.num_qubits], value) for k in range(j): value = elem1.poly.get_term([k, j, i]) result.poly.set_term( [k + elem0.num_qubits, j + elem0.num_qubits, i + elem0.num_qubits], value ) return result def tensor(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=True) def expand(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=False) def adjoint(self): circ = self.to_instruction() result = self._from_circuit(circ.inverse()) return result def conjugate(self): circ = self.to_instruction() new_circ = QuantumCircuit(self.num_qubits) bit_indices = {bit: index for index, bit in enumerate(circ.definition.qubits)} for instruction in circ.definition: new_qubits = [bit_indices[tup] for tup in instruction.qubits] if instruction.operation.name == "p": params = 2 * np.pi - instruction.operation.params[0] instruction.operation.params[0] = params new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "t": instruction.operation.name = "tdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "tdg": instruction.operation.name = "t" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "s": instruction.operation.name = "sdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "sdg": instruction.operation.name = "s" new_circ.append(instruction.operation, new_qubits) else: new_circ.append(instruction.operation, new_qubits) result = self._from_circuit(new_circ) return result def transpose(self): circ = self.to_instruction() result = self._from_circuit(circ.reverse_ops()) return result def _is_valid(self): """Return True if input is a CNOTDihedral element.""" if ( self.poly.weight_0 != 0 or len(self.poly.weight_1) != self.num_qubits or len(self.poly.weight_2) != int(self.num_qubits * (self.num_qubits - 1) / 2) or len(self.poly.weight_3) != int(self.num_qubits * (self.num_qubits - 1) * (self.num_qubits - 2) / 6) ): return False if ( (self.linear).shape != (self.num_qubits, self.num_qubits) or len(self.shift) != self.num_qubits or not np.allclose((np.linalg.det(self.linear) % 2), 1) ): return False if ( not (set(self.poly.weight_1.flatten())).issubset({0, 1, 2, 3, 4, 5, 6, 7}) or not (set(self.poly.weight_2.flatten())).issubset({0, 2, 4, 6}) or not (set(self.poly.weight_3.flatten())).issubset({0, 4}) ): return False if not (set(self.shift.flatten())).issubset({0, 1}) or not ( set(self.linear.flatten()) ).issubset({0, 1}): return False return True # Update docstrings for API docs generate_apidocs(CNOTDihedral)
https://github.com/sam-pf/pf-qiskit
sam-pf
# -*- 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 quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/Marduk-42/Quantum-Algorithm-Tutorials
Marduk-42
from qiskit import * import matplotlib.pyplot as plt qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg,creg) circuit.reset(qreg[0]) circuit.reset(qreg[1]) circuit.h(qreg[0]) circuit.cx(qreg[0],qreg[1]) circuit.measure(qreg[0],creg[0]) circuit.measure(qreg[1],creg[1]) backend = Aer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=2048) result = job.result() circuit.draw("mpl") visualization.plot_histogram(result.get_counts()) from qiskit.providers.ibmq import least_busy provider = IBMQ.load_account() #If this throws an error, run IBMQ.save_account(YOUR_API_KEY). You will find your api key on https://quantum-computing.ibm.com/account device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) job = execute(circuit, backend=device, shots=2048) #May take some time results = job.result() answer = results.get_counts(circuit) visualization.plot_histogram(answer)
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
""" Teague Tomesh - 3/25/2019 Implementation of the UCCSD ansatz for use in the VQE algorithm. Based on the description given in Whitfield et al. (https://arxiv.org/abs/1001.3855?context=physics.chem-ph) Adapted from a Scaffold implementation by Pranav Gokhale] (https://github.com/epiqc/ScaffCC) NOTE: Qiskit orders their circuits increasing from top -> bottom 0 --- 1 --- 2 --- Both Whitfield et al. and Barkoutsos et al. order increasing from bottom -> top p 3 --- q 2 --- r 1 --- s 0 --- Not a problem. Qubit index is what matters. Set reverse_bits = True when drawing Qiskit circuit. """ from qiskit import QuantumCircuit, QuantumRegister import sys import math import numpy as np class UCCSD: """ Class to implement the UCCSD ansatz as described in Whitfield et al. (https://arxiv.org/abs/1001.3855?context=physics.chem-ph) A UCCSD circuit can be generated for a given instance of the UCCSD class by calling the gen_circuit() method. Attributes ---------- width : int number of qubits parameters : str choice of parameters [random, seeded] seed : int a number to seed the number generator with barriers : bool should barriers be included in the generated circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__( self, width, parameters="random", seed=None, barriers=False, regname=None ): # number of qubits self.nq = width # set flags for circuit generation self.parameters = parameters self.seed = seed self.barriers = barriers # create a QuantumCircuit object # We do not include a ClassicalRegister in this circuit because # many different gates may need to be appended to this ansatz # to measure all of the terms in the Hamiltonian for an instance # VQE, but it is also easier for the circuit cutter to handle # circuits without measurement/classical registers. if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) def M_d(self, i, p, q, r, s, dagger=False): """ See Double Excitation Operator circuit in Table A1 of Whitfield et al 2010 Y in Table A1 of Whitfield et al 2010 really means Rx(-pi/2) """ if dagger: angle = math.pi / 2 else: angle = -math.pi / 2 qr = self.circ.qregs[0] if i == 1: self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.h(qr[r]) self.circ.h(qr[s]) elif i == 2: self.circ.rx(angle, qr[p]) self.circ.rx(angle, qr[q]) self.circ.rx(angle, qr[r]) self.circ.rx(angle, qr[s]) elif i == 3: self.circ.h(qr[p]) self.circ.rx(angle, qr[q]) self.circ.h(qr[r]) self.circ.rx(angle, qr[s]) elif i == 4: self.circ.rx(angle, qr[p]) self.circ.h(qr[q]) self.circ.rx(angle, qr[r]) self.circ.h(qr[s]) elif i == 5: self.circ.rx(angle, qr[p]) self.circ.rx(angle, qr[q]) self.circ.h(qr[r]) self.circ.h(qr[s]) elif i == 6: self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.rx(angle, qr[r]) self.circ.rx(angle, qr[s]) elif i == 7: self.circ.rx(angle, qr[p]) self.circ.h(qr[q]) self.circ.h(qr[r]) self.circ.rx(angle, qr[s]) elif i == 8: self.circ.h(qr[p]) self.circ.rx(angle, qr[q]) self.circ.rx(angle, qr[r]) self.circ.h(qr[s]) def CNOTLadder(self, controlStartIndex, controlStopIndex): """ Applies a ladder of CNOTs, as in the dashed-CNOT notation at bottom of Table A1 of Whitfield et al 2010 Qubit indices increase from bottom to top """ qr = self.circ.qregs[0] if controlStopIndex > controlStartIndex: delta = 1 index = controlStartIndex + 1 controlStopIndex += 1 else: delta = -1 index = controlStartIndex while index is not controlStopIndex: self.circ.cx(qr[index], qr[index - 1]) index += delta def DoubleExcitationOperator(self, theta, p, q, r, s): """ Prerequisite: p > q > r > s """ qr = self.circ.qregs[0] for i in range(1, 9): if self.barriers: self.circ.barrier(qr) self.M_d(i, p, q, r, s, dagger=False) if self.barriers: self.circ.barrier(qr) self.CNOTLadder(p, q) self.circ.cx(qr[q], qr[r]) self.CNOTLadder(r, s) self.circ.rz(theta, qr[s]) # Rz(reg[s], Theta_p_q_r_s[p][q][r][s]); self.CNOTLadder(s, r) self.circ.cx(qr[q], qr[r]) self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.M_d(i, p, q, r, s, dagger=True) def SingleExcitationOperator(self, theta, p, q): """ Prerequisite: p > q See Single Excitation Operator circuit in Table A1 of Whitfield et al 2010 """ qr = self.circ.qregs[0] if self.barriers: self.circ.barrier(qr) self.circ.h(qr[p]) self.circ.h(qr[q]) self.CNOTLadder(p, q) self.circ.rz(theta, qr[q]) # Rz(reg[q], Theta_p_q[p][q]); self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.rx(-math.pi / 2, qr[p]) self.circ.rx(-math.pi / 2, qr[q]) self.CNOTLadder(p, q) self.circ.rz(theta, qr[q]) # Rz(reg[q], Theta_p_q[p][q]); self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.circ.rx(-math.pi / 2, qr[p]) self.circ.rx(-math.pi / 2, qr[q]) def gen_circuit(self): """ Create a circuit implementing the UCCSD ansatz Given the number of qubits and parameters, construct the ansatz as given in Whitfield et al. Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ # Ensure the # of parameters matches what is neede by the current value of # Nq, then set a counter, p_i=0, when the circuit is first initialized, and # every call to the single or double operator will take param[p_i] as its # parameter and then increment the value of p_i num_dbl = (self.nq**4 - 6 * self.nq**3 + 11 * self.nq**2 - 6 * self.nq) / 24 num_sgl = (self.nq**2 - self.nq) / 2 numparam = int(num_dbl + num_sgl) if self.parameters == "random": param = np.random.uniform(-np.pi, np.pi, numparam) elif self.parameters == "seeded": if self.seed is None: raise Exception("A valid seed must be provided") else: np.random.seed(self.seed) param = np.random.uniform(-np.pi, np.pi, numparam) else: raise Exception("Unknown parameter option") p_i = 0 # enumerate all Nq > p > q > r > s >= 0 and apply Double Excitation Operator for p in range(self.nq): for q in range(p): for r in range(q): for s in range(r): # print(p,q,r,s) # For the 4 qubit case this function is called a single time self.DoubleExcitationOperator(param[p_i], p, q, r, s) p_i += 1 # enumerate all Nq > p > q >= 0 and apply Single Excitation Operator for p in range(self.nq): for q in range(p): # print(p,q) self.SingleExcitationOperator(param[p_i], p, q) p_i += 1 return self.circ
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Necessary imports import numpy as np import matplotlib.pyplot as plt from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS from qiskit import QuantumCircuit from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector # Set seed for random generators algorithm_globals.random_seed = 42 # Generate random dataset # Select dataset dimension (num_inputs) and size (num_samples) num_inputs = 2 num_samples = 20 # Generate random input coordinates (X) and binary labels (y) X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example # Convert to torch Tensors X_ = Tensor(X) y01_ = Tensor(y01).reshape(len(y)).long() y_ = Tensor(y).reshape(len(y), 1) # Plot dataset for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Set up a circuit feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs) qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw("mpl") # Setup QNN qnn1 = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # Set up PyTorch module # Note: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1) model1 = TorchConnector(qnn1, initial_weights=initial_weights) print("Initial weights: ", initial_weights) # Test with a single input model1(X_[0, :]) # Define optimizer and loss optimizer = LBFGS(model1.parameters()) f_loss = MSELoss(reduction="sum") # Start training model1.train() # set model to training mode # Note from (https://pytorch.org/docs/stable/optim.html): # Some optimization algorithms such as LBFGS need to # reevaluate the function multiple times, so you have to # pass in a closure that allows them to recompute your model. # The closure should clear the gradients, compute the loss, # and return it. def closure(): optimizer.zero_grad() # Initialize/clear gradients loss = f_loss(model1(X_), y_) # Evaluate loss function loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer step4 optimizer.step(closure) # Evaluate model and compute accuracy y_predict = [] for x, y_target in zip(X, y): output = model1(Tensor(x)) y_predict += [np.sign(output.detach().numpy())[0]] print("Accuracy:", sum(y_predict == y) / len(y)) # Plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Define feature map and ansatz feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1) # Define quantum circuit of num_qubits = input dim # Append feature map and ansatz qc = QuantumCircuit(num_inputs) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Define SamplerQNN and initial setup parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function output_shape = 2 # parity = 0, 1 qnn2 = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1) print("Initial weights: ", initial_weights) model2 = TorchConnector(qnn2, initial_weights) # Define model, optimizer, and loss optimizer = LBFGS(model2.parameters()) f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range # Start training model2.train() # Define LBFGS closure method (explained in previous section) def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model2(X_), y01_) # Calculate loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer (LBFGS requires closure) optimizer.step(closure); # Evaluate model and compute accuracy y_predict = [] for x in X: output = model2(Tensor(x)) y_predict += [np.argmax(output.detach().numpy())] print("Accuracy:", sum(y_predict == y01) / len(y01)) # plot results # red == wrongly classified for x, y_target, y_ in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # Generate random dataset num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1) plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") plt.plot(X, y, "bo") plt.show() # Construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # Construct simple feature map param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Construct QNN qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y]) # Set up PyTorch module # Reminder: If we don't explicitly declare the initial weights # they are chosen uniformly at random from [-1, 1]. initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1) model3 = TorchConnector(qnn3, initial_weights) # Define optimizer and loss function optimizer = LBFGS(model3.parameters()) f_loss = MSELoss(reduction="sum") # Start training model3.train() # set model to training mode # Define objective function def closure(): optimizer.zero_grad(set_to_none=True) # Initialize gradient loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss loss.backward() # Backward pass print(loss.item()) # Print loss return loss # Run optimizer optimizer.step(closure) # Plot target function plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--") # Plot data plt.plot(X, y, "bo") # Plot fitted line y_ = [] for x in np.linspace(lb, ub): output = model3(Tensor([x])) y_ += [output.detach().numpy()[0]] plt.plot(np.linspace(lb, ub), y_, "g-") plt.show() # Additional torch-related imports import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import datasets, transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss, MaxPool2d, Flatten, Sequential, ReLU, ) import torch.nn.functional as F # Train Dataset # ------------- # Set train shuffle seed (for reproducibility) manual_seed(42) batch_size = 1 n_samples = 100 # We will concentrate on the first 100 samples # Use pre-defined torchvision function to load MNIST train data X_train = datasets.MNIST( root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples] ) X_train.data = X_train.data[idx] X_train.targets = X_train.targets[idx] # Define torch dataloader with filtered data train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True) n_samples_show = 6 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) while n_samples_show > 0: images, targets = data_iter.__next__() axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), 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[0].item())) n_samples_show -= 1 # Test Dataset # ------------- # Set test shuffle seed (for reproducibility) # manual_seed(5) n_samples = 50 # Use pre-defined torchvision function to load MNIST test data X_test = datasets.MNIST( root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()]) ) # Filter out labels (originally 0-9), leaving only labels 0 and 1 idx = np.append( np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples] ) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] # Define torch dataloader with filtered data test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True) # Define and create QNN def create_qnn(): feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2, reps=1) qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn4 = create_qnn() # Define torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(1, 2, kernel_size=5) self.conv2 = Conv2d(2, 16, kernel_size=5) self.dropout = Dropout2d() self.fc1 = Linear(256, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen # uniformly at random from interval [-1,1]. self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) # apply QNN x = self.fc3(x) return cat((x, 1 - x), -1) model4 = Net(qnn4) # Define model, optimizer, and loss function optimizer = optim.Adam(model4.parameters(), lr=0.001) loss_func = NLLLoss() # Start training epochs = 10 # Set number of epochs loss_list = [] # Store loss history model4.train() # Set model to training mode for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad(set_to_none=True) # Initialize gradient output = model4(data) # Forward pass loss = loss_func(output, target) # Calculate loss loss.backward() # Backward pass optimizer.step() # Optimize weights total_loss.append(loss.item()) # Store loss loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plot loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() torch.save(model4.state_dict(), "model4.pt") qnn5 = create_qnn() model5 = Net(qnn5) model5.load_state_dict(torch.load("model4.pt")) model5.eval() # set model to evaluation mode with no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model5(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) 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) / batch_size * 100 ) ) # Plot predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model5.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model5(data[0:1]) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(data[0].numpy().squeeze(), cmap="gray") axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {}".format(pred.item())) count += 1 import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * # import matplotlib.pyplot as plt %matplotlib inline print(qiskit.__version__) circuit = QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) circuit.measure([0,1],[0,1]) # circuit.measure_all() circuit.barrier() # circuit.draw(output='mpl') circuit.draw(output='mpl') simulator = Aer.get_backend('aer_simulator') result = execute(circuit, backend=simulator, shots=1024).result() count = result.get_counts() print(count) from qiskit.tools.visualization import plot_histogram plot_histogram(count) from qiskit import IBMQ IBMQ.save_account("b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8ef******", overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() from qiskit.providers.ibmq import least_busy backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) job = execute(circuit, backend=backend, shots=1024) from qiskit.tools.monitor import job_monitor job_monitor(job) result = job.result() count = result.get_counts() print(count) from qiskit.tools.visualization import plot_histogram plot_histogram(count)
https://github.com/abbarreto/qiskit3
abbarreto
list_bin = [] for j in range(0,2**4): b = "{:04b}".format(j) list_bin.append(b) print(list_bin) list_int = [] for j in range(0,2**4): list_int.append(int(list_bin[j],2)) print(list_int)
https://github.com/zhangx1923/QISKit_Deve_Challenge
zhangx1923
# Import your solution function from challenge_submission import compiler_function # Import submission evaluation and scoring functions from challenge_evaluation import evaluate, score # Possibly useful other helper function from challenge_evaluation import qasm_to_dag_circuit, load_coupling, get_layout # Select the simulation backend to calculate the quantum states resulting from the circuits # On Windows platform the C++ Simulator is not yet available with pip install backend = 'local_qiskit_simulator' #backend = 'local_qasm_simulator' # uncomment this line if you are a Windows user # Load example circuits and coupling maps ex_nr = 1 # examples to add per qubit number. maximum is 10 with the provided circuits test_circuit_filenames = {} for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n5_d5.qasm' % i] = get_layout(5) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n16_d16.qasm' % i] = get_layout(16) for i in range(ex_nr): test_circuit_filenames['circuits/random%d_n20_d20.qasm' % i] = get_layout(20) # store circuit, coupling map pairs in test_circuits. Circuits are in qasm form. test_circuits = {} for filename, cmap in test_circuit_filenames.items(): with open(filename, 'r') as infile: qasm = infile.read() test_circuits[filename] = {"qasm": qasm, "coupling_map": cmap} result = evaluate(compiler_function, test_circuits, verbose=True, backend = backend) result test_circuits['circuits/random0_n5_d5.qasm'].keys() myres = score(compiler_function, backend = backend) print("Your compiler scored %6.5f x better \ and was %6.5f x faster than the QISKit reference compiler." % myres) # import some coupling map generation functions from gencoupling import * # generate a square coupling map with 18 qubits and nearest neighbour connectivity # then remove 4 random links # also try linear, circle, rect, torus, ibmqx etc. lr = rect(6,3,order = 0.5, defects = -4) plot_layout(lr) # save the coupling map in the layouts folder lr["name"] = "random_rectangular_lattice_4_defects_q18" save_coupling(lr) # load the saved coupling by name rr = load_coupling("random_rectangular_lattice_4_defects_q18") rr["coupling_map"] plot_layout(lr) # if your working directory is the folder with this notebook you can also use import os mydir = os.curdir os.chdir('circuits') !python generator.py -n 17 -d 17 os.chdir(mydir) with open('random0_n17_d17.qasm', 'r') as infile: qasm = infile.read() print(qasm)
https://github.com/xtophe388/QISKIT
xtophe388
# You may need to trust this notebook before the button below works from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''') def cplayer_output(strategy, inp): if(strategy == 1): return inp elif(strategy == 2): return abs(inp-1) elif(strategy == 3): return 1 elif(strategy == 4): return 0 else: print("INVALID choice") return 100 # Pick Alice's classical strategy A_st = int(input('select the classical strategy for Alice, input 1,2,3 or 4 to pick one of the strategies listed above ')) # Pick Bob's classical strategy B_st = int(input('select the classical strategy for Bob, input 1,2,3 or 4 to pick one of the strategies listed above ')) # useful packages import numpy as np import random as rand # fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played # play the game N times for i in range(N): # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # generates Alice's and Bob's output a = cplayer_output(A_st, x) # Alice's output b = cplayer_output(B_st, y) # Bob's output # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter Prob_win = cont_win/cont_tot # winning probability print('Alice and Bob won the game with probability: ', Prob_win*100, '%') def qAlice_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return 0 elif(inp == 1): return np.pi/2 else: print("INVALID choice") return 100 def qBob_output(strategy, inp): if(strategy == 1): return 0 elif(strategy == 2): return rand.uniform(0,2*np.pi) elif(strategy == 3): if(inp == 0): return np.pi/4 elif(inp == 1): return -np.pi/4 else: print("INVALID choice") return 100 # Alice's strategy qA_st = int(input('select the quantum strategy for Alice, input 1,2 or 3 to pick one of the strategies listed above: ')) # Bob's strategy qB_st = int(input('select the quantum strategy for Bob, input 1,2 or 3 to pick one of the strategies listed above: ')) # import packages from qiskit import * import numpy as np import random as rand # set parameters of the quantum run of the game shots = 1 # set how many times the circuit is run, accumulating statistics about the measurement outcomes backend = 'local_qasm_simulator' # set the machine where the quantum circuit is to be run #fixes the numbers of games to be played N=100 # initializes counters used to keep track of the numbers of games won and played by Alice an Bob cont_win = 0 # counts games won cont_tot = 0 # counts games played #play N games for i in range(N): #creates quantum program, which allows to specify the details of the circuit like the register and the gates used Q_program = QuantumProgram() # creates registers for qubits and bits q = Q_program.create_quantum_register('q', 2) # creates a quantum register, it specifies the qubits which are going to be used for the program c = Q_program.create_classical_register('c', 2) # creates a classical register, the results of the measurement of the qubits are stored here # creates quantum circuit, to write a quantum algorithm we will add gates to the circuit game = Q_program.create_circuit('game', [q], [c]) # These gates prepare the entangled Bell pair to be shared by Alice and Bob as part of their quantum strategy # Alice will have qubit 0 and Bob will have qubit 1 game.h(q[0]) # Hadamard gate on qubit 0 game.cx(q[0],q[1]) # CNOT gate on qubit 1 controlled by qubit 0 # generates two random input from the refree, x and y, to be given to Alice and Bob random_num1 = rand.random() # first random number random_num2 = rand.random() # second random number if(random_num1 >= 1/2): # converts the first random number to 0 or 1 x = 0 else: x = 1 if(random_num2 >= 1/2): # converts the second random number to 0 or 1 y = 0 else: y = 1 # The main part of Alice and Bob quantum strategy is to fix different rotation angles for their qubit according to the input x,y theta = qAlice_output(qA_st, x) # fixes Alice's rotation for her qubit phi = qBob_output(qB_st, y) # fixes Bob's rotation for his qubit # The following gates rotate Alice's qubit and Bob's qubit game.ry(theta,q[0]) #rotates Alice's qubit of an angle theta game.ry(phi,q[1]) ##rotates Bob's qubit of an angle phi # These gates are used to measure the value of the qubits game.measure(q[0], c[0]) # measure Alice's qubit and stores the result in a classical bit game.measure(q[1], c[1]) # measure Bob's qubit and stores the result in a classical bit # Assemble the gates in the circuit circuits = ['game'] # assemble circuit # executes circuit and store the output of the measurements result = Q_program.execute(circuits, backend=backend, shots=shots, wait=10, timeout=240) data = result.get_counts('game') # extract the outcomes and their statistics from the result of the execution # reads the result of the measurements of the quantum system for outcomes in data.keys(): out = outcomes # converts the result of the measurements contained in the classical register as string '00', '01', '10', '11', # which are the answers of Alice(a) and Bob (b), from a 'string' type to 'integer' type if(out == '00'): a = 0 b = 0 if(out == '01'): a = 1 b = 0 if(out == '10'): a = 0 b = 1 if(out == '11'): a = 1 b = 1 # check if the condition for winning the game is met if(x*y == a^b): cont_win += 1 # increase thes won games' counter if the condition to win the game is met cont_tot += 1 # increases the played games' counter qProb_win = cont_win/cont_tot print('Alice and Bob won the game with probability: ', qProb_win*100, '%') if Prob_win > qProb_win : print("The classical strategy gave Alice and Bob higher chances of winning") else: print("The quantum strategy gave Alice and Bob higher chances of winning")
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. """Tests for qiskit.quantum_info.analysis""" import unittest import qiskit from qiskit import BasicAer from qiskit.quantum_info.analysis.average import average_data from qiskit.quantum_info.analysis.make_observable import make_dict_observable from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.test import QiskitTestCase class TestAnalyzation(QiskitTestCase): """Test qiskit.Result API""" def test_average_data_dict_observable(self): """Test average_data for dictionary observable input""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = {"00": 1, "11": 1, "01": -1, "10": -1} mean_zz = average_data(counts=counts, observable=observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} mean_zi = average_data(counts, observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_average_data_list_observable(self): """Test average_data for list observable input.""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [1, -1, -1, 1, -1, 1, 1, -1] mean_zzz = average_data(counts=counts, observable=observable) observable = [1, 1, 1, 1, -1, -1, -1, -1] mean_zii = average_data(counts, observable) observable = [1, 1, -1, -1, 1, 1, -1, -1] mean_izi = average_data(counts, observable) observable = [1, 1, -1, -1, -1, -1, 1, 1] mean_zzi = average_data(counts, observable) self.assertAlmostEqual(mean_zzz, 0, places=1) self.assertAlmostEqual(mean_zii, 0, places=1) self.assertAlmostEqual(mean_izi, 0, places=1) self.assertAlmostEqual(mean_zzi, 1, places=1) def test_average_data_matrix_observable(self): """Test average_data for matrix observable input.""" qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(2) qc = qiskit.QuantumCircuit(qr, cr, name="qc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 10000 backend = BasicAer.get_backend("qasm_simulator") result = qiskit.execute(qc, backend, shots=shots).result() counts = result.get_counts(qc) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]] mean_zz = average_data(counts=counts, observable=observable) observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]] mean_zi = average_data(counts, observable) observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]] mean_iz = average_data(counts, observable) self.assertAlmostEqual(mean_zz, 1, places=1) self.assertAlmostEqual(mean_zi, 0, places=1) self.assertAlmostEqual(mean_iz, 0, places=1) def test_make_dict_observable(self): """Test make_dict_observable.""" list_in = [1, 1, -1, -1] list_out = make_dict_observable(list_in) list_expected = {"00": 1, "01": 1, "10": -1, "11": -1} matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]] matrix_out = make_dict_observable(matrix_in) matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1} long_list_in = [1, 1, -1, -1, -1, -1, 1, 1] long_list_out = make_dict_observable(long_list_in) long_list_expected = { "000": 1, "001": 1, "010": -1, "011": -1, "100": -1, "101": -1, "110": 1, "111": 1, } self.assertEqual(list_out, list_expected) self.assertEqual(matrix_out, matrix_expected) self.assertEqual(long_list_out, long_list_expected) def test_hellinger_fidelity_same(self): """Test hellinger fidelity is one for same dist.""" qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res = qiskit.execute(qc, sim).result() ans = hellinger_fidelity(res.get_counts(), res.get_counts()) self.assertEqual(ans, 1.0) def test_hellinger_fidelity_no_overlap(self): """Test hellinger fidelity is zero for no overlap.""" # ┌───┐ ┌─┐ # q_0: ──────────┤ X ├─────┤M├──────────── # ┌───┐└─┬─┘ └╥┘┌─┐ # q_1: ─────┤ X ├──■────────╫─┤M├───────── # ┌───┐└─┬─┘ ║ └╥┘┌─┐ # q_2: ┤ H ├──■────■────────╫──╫─┤M├────── # └───┘ ┌─┴─┐ ║ ║ └╥┘┌─┐ # q_3: ──────────┤ X ├──■───╫──╫──╫─┤M├─── # └───┘┌─┴─┐ ║ ║ ║ └╥┘┌─┐ # q_4: ───────────────┤ X ├─╫──╫──╫──╫─┤M├ # └───┘ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 qc = qiskit.QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) # ┌───┐ ┌─┐ # q_0: ──────────┤ X ├─────┤M├───────── # ┌───┐└─┬─┘ └╥┘┌─┐ # q_1: ─────┤ X ├──■────────╫─┤M├────── # ┌───┐└─┬─┘┌───┐ ║ └╥┘┌─┐ # q_2: ┤ H ├──■──┤ Y ├──■───╫──╫─┤M├─── # └───┘ └───┘┌─┴─┐ ║ ║ └╥┘┌─┐ # q_3: ───────────────┤ X ├─╫──╫──╫─┤M├ # ┌─┐ └───┘ ║ ║ ║ └╥┘ # q_4: ─┤M├─────────────────╫──╫──╫──╫─ # └╥┘ ║ ║ ║ ║ # c: 5/══╩══════════════════╩══╩══╩══╩═ # 4 0 1 2 3 qc2 = qiskit.QuantumCircuit(5, 5) qc2.h(2) qc2.cx(2, 1) qc2.y(2) qc2.cx(2, 3) qc2.cx(1, 0) qc2.measure(range(5), range(5)) sim = BasicAer.get_backend("qasm_simulator") res1 = qiskit.execute(qc, sim).result() res2 = qiskit.execute(qc2, sim).result() ans = hellinger_fidelity(res1.get_counts(), res2.get_counts()) self.assertEqual(ans, 0.0) if __name__ == "__main__": unittest.main(verbosity=2)
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/nahumsa/Introduction-to-IBM_Qiskit
nahumsa
%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() from qiskit.aqua.operators import OperatorBase, ListOp, PrimitiveOp, PauliOp from qiskit.quantum_info import Pauli from qiskit.aqua.algorithms import VQE, NumPyEigensolver from qiskit.circuit.library import TwoLocal from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP import numpy as np ansatz = TwoLocal(num_qubits=2, rotation_blocks=['rx','rz'], entanglement_blocks='cx', entanglement='full', reps=1) ansatz.draw() optimizer = SLSQP(maxiter=100) Op = PauliOp(Pauli(label='II'), 0.5) - PauliOp(Pauli(label='XX'), 0.5) - 0.5*PauliOp(Pauli(label='YY')) + 0.5*PauliOp(Pauli(label='ZZ')) # Op = PrimitiveOp(primitive=[[1,0],[0,1]], coeff=2.) # xx = Pauli(label='XX') # yy = Pauli(label='YY') # zz = Pauli(label='ZZ') # ii = Pauli(label='II') # Op = ListOp([zz,yy,xx, ii], coeff=[0.5,-0.5,-0.5,0.5]) vqe = VQE(Op, ansatz, optimizer) backend = Aer.get_backend("statevector_simulator") vqe_result = np.real(vqe.run(backend)['eigenvalue'] ) vqe_result np.min(np.linalg.eig(Op.to_matrix())[0]) Op.to_matrix()
https://github.com/renatawong/quantum-protein-structure-prediction
renatawong
''' (C) Copyright Renata Wong 2023. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license 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 is the accompanying Qiskit code for the paper 'Fast Quantum Algorithm for Protein Structure Prediction in Hydrophobic-Hydrophilic Model' (DOI: 10.1016/j.jpdc.2022.03.011) The code works for amino acid sequences of length > 4. NOTE: This code assumes the sequence 01001 for testing pursposes. Other sequences may require adjustments of variables num_solutions and j. ''' from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import numpy as np import math ''' Taking in user input of the amino acid sequence. Bit 0 stands for a hydrophilic amino acid, while bit 1 stands for a hydrophobic amino acid ''' sequence_input = list(input('Enter a sequence of length at least 5 encoded as a string of 0s and 1s:' )) length = len(sequence_input) ''' Quantum register holding the sequence encoding ''' sequence = QuantumRegister(length,'s') ''' Quantum registers for each of the three coordinates x, y, and z. Coordinate order within each register: x0, x1, x2, etc., where x0 is the x-coordinate of the 1st amino acid, x1 is the x-coordinate of the 2nd amino acid, etc. Each register holds 2(length - 1) + 1 values. Each value can therefore be repserented with a minimum of ceil(log2(2*length - 1)) bits. There are a 'length' number of amino acids in a sequence. ''' register_length = int(math.ceil(np.log2(2*length-1))) coord_reg_length = length * register_length x_coord = QuantumRegister(coord_reg_length, 'x') y_coord = QuantumRegister(coord_reg_length, 'y') ''' Quantum register holding the controls w0, w1, etc. Each w is of length 2. Amino acid at position (0, 0, 0) is fixed. Hence, length - 1 amino acids in a sequence require directional information encoded in w. ''' w = QuantumRegister(2*(length-1), 'w') ''' Quantum register holding the binary 1, and the two's complement of 1 (= -1). The two's complement of 1 can be obtained by negating all the qubits in binary one but the last. NOTE: Encoding coordinates in two's complement notation allows one to treat subtraction as addition with the same ripple carry circuit. ''' one_reg_length = int(math.ceil(np.log2(2*length-1))) binary_one = QuantumRegister(one_reg_length,'one') ''' Quantum register holding the carry bit for ripple-carry adder ''' carry = QuantumRegister(1, 'c') ''' Register holding the Grover auxialliary qubit ''' g = QuantumRegister(1, 'g') ''' Classical register holding the output of the quantum computation ''' output = ClassicalRegister(length+2*(length-1), 'out')#(length + 2*(length-1) + 2*coord_reg_length,'out') ''' The ancilla register of 3 qubits in needed for the multiplexer (controlled Toffoli gates) in the ripple-carry quantum adder. ''' ancilla = QuantumRegister(3, 'anc') ''' Registers for the section FINDING ENERGY VALUES ''' k_range = length-3 j_range = int((k_range * (k_range+1))/2) x_star = QuantumRegister(4*j_range*register_length, 'x_st') y_star = QuantumRegister(4*j_range*register_length, 'y_st') r_reg = QuantumRegister(4*j_range*(2*register_length + 1), 'r') delta = QuantumRegister(4*2*j_range, 'delta') psi = QuantumRegister(4*j_range, 'psi') ''' Registers for section SUMMING UP ENERGY VALUES. We create 4 index matrices that hold registers for each of 0 <= p <= 3 in the z_reg to obtain the value for kj in register z. ''' p0_matrix = [ [ 0 for m in range(4 * (length-4) + 2) ] for n in range(length-2) ] kj = 0 for k in range(1, length-2): for j in range(4 * (k-1) + 2): p0_matrix[k][j] = kj kj += 1 p1_matrix = [ [ 0 for m in range(4 * (length-4) + 3) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 3): p1_matrix[k][j] = kj kj += 1 p2_matrix = [ [ 0 for m in range(4 * (length-4) + 4) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 4): p2_matrix[k][j] = kj kj += 1 p3_matrix = [ [ 0 for m in range(4 * (length-4) + 5) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 5): p3_matrix[k][j] = kj kj += 1 z = QuantumRegister(kj, 'z') #((4 * length - 12) * (4 * length - 11) / 2, 'z') this value is too low z_or = QuantumRegister(1, 'z_or') # ancilla qubit for the multiplexer in Fig. 4 z_and = QuantumRegister(1, 'z_and') # ancilla to hold the results of the AND operation ''' Defining a quantum circuit consisting of the above quantum and classical registers ''' qc = QuantumCircuit(g, sequence, x_coord, y_coord, w, binary_one, carry, ancilla, x_star, y_star, r_reg, delta, psi, z, z_or, z_and, output) ''' SECTION: PREPARING A UNIFORM SUPERPOSITION STATE Initialisation of sequence values based on user input ''' for index, bit in enumerate(sequence_input): if bit == '1': qc.x(sequence[index]) ''' Initialising binary one and the two's complement of one ''' qc.x(binary_one[one_reg_length-1]) ''' Setting the quantum state in a uniform superposition wrt. w ''' qc.h(w[0:2*(length-1)]) ''' Initialization of r_reg ''' multiplier = int(len(r_reg)/(4*j_range)) for i in range(4*j_range): qc.x(r_reg[i*multiplier]) ''' Initialize z_or to |1> for cascading OR gates implemented with mcx gate. ''' qc.x(z_or) ''' Setting the Grover qubit into the |-> state ''' qc.x(g) qc.h(g) ''' SECTION: CALCULATING COORDINATES Requires a doubly-controlled ripple-carry adder as a subroutine sc The adder below is for amino acid sequences of length > 4. ''' summand_register_length = int(math.ceil(np.log2(2*length-1))) sw = QuantumRegister(2,'sw') # control qubits (w) sa = QuantumRegister(3,'sa') # ancilla qubits ss = QuantumRegister(1,'ss') # carry sx = QuantumRegister(summand_register_length,'sx') # summand x sy = QuantumRegister(summand_register_length,'sy') # summand y sc = QuantumCircuit(sw, sa, ss, sx, sy, name='ccrca') sc.ccx(sw[0],sw[1],sa[0]) for i in range(1, summand_register_length): sc.ccx(sa[0],sx[i],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i],sa[1]) sc.ccx(sa[0],sx[1],sa[1]) sc.cx(sa[1],ss[0]) sc.ccx(sa[0],sx[1],sa[1]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[1],sy[0],sa[2]) sc.cx(sa[2],ss[0]) sc.ccx(sa[1],sy[0],sa[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[1],sx[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.cx(sa[2],sx[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[1],sx[2]) sc.ccx(sa[0],sx[3],sa[1]) for i in range(2, summand_register_length-2): sc.ccx(sa[0],sy[i],sa[1]) sc.ccx(sa[1],sx[i-1],sa[2]) sc.cx(sa[2],sx[i]) sc.ccx(sa[1],sx[i-1],sa[2]) sc.ccx(sa[0],sy[i],sa[1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[1],sx[i+1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.ccx(sa[0],sy[summand_register_length-2],sa[1]) sc.ccx(sa[1],sx[summand_register_length-3],sa[2]) sc.cx(sa[2],sx[summand_register_length-2]) sc.ccx(sa[1],sx[summand_register_length-3],sa[2]) sc.ccx(sa[0],sy[summand_register_length-2],sa[1]) for i in range(1, summand_register_length-1): sc.cx(sa[0],sy[i]) sc.ccx(sa[0],ss[0],sa[1]) sc.cx(sa[1],sy[1]) sc.ccx(sa[0],ss[0],sa[1]) for i in range(2, summand_register_length): sc.ccx(sa[0],sx[i-1],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[0],sx[summand_register_length-3],sa[1]) sc.ccx(sa[1],sy[summand_register_length-2],sa[2]) sc.cx(sa[2],sx[summand_register_length-2]) sc.ccx(sa[1],sy[summand_register_length-2],sa[2]) sc.ccx(sa[0],sx[summand_register_length-3],sa[1]) for i in range(summand_register_length-3, 1, -1): sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[1],sy[i],sa[2]) sc.cx(sa[2],sx[i]) sc.ccx(sa[1],sy[i],sa[2]) sc.ccx(sa[0],sx[i-1],sa[1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[1],sx[i+1]) sc.ccx(sa[0],sx[i+2],sa[1]) sc.cx(sa[0],sy[i+1]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.cx(sa[2],sx[1]) sc.ccx(sa[1],sy[1],sa[2]) sc.ccx(sa[0],ss[0],sa[1]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[1],sx[2]) sc.ccx(sa[0],sx[3],sa[1]) sc.cx(sa[0],sy[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[1],sy[0],sa[2]) sc.cx(sa[2],ss[0]) sc.ccx(sa[1],sy[0],sa[2]) sc.ccx(sa[0],sx[0],sa[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[1],sx[1]) sc.ccx(sa[0],sx[2],sa[1]) sc.cx(sa[0],sy[1]) sc.ccx(sa[0],sx[1],sa[1]) sc.cx(sa[1],ss[0]) sc.ccx(sa[0],sx[1],sa[1]) for i in range(summand_register_length): sc.ccx(sa[0],sx[i],sa[1]) sc.cx(sa[1],sy[i]) sc.ccx(sa[0],sx[i],sa[1]) sc.ccx(sw[0],sw[1],sa[0]) subinst = sc.to_instruction() ''' Ripple-carry adder without control qubits |w> ''' ssr = QuantumRegister(1,'ssr') # carry sxr = QuantumRegister(summand_register_length,'sxr') # summand x syr = QuantumRegister(summand_register_length,'syr') # summand y rca = QuantumCircuit(ssr, sxr, syr, name='rca') for i in range(1, summand_register_length): rca.cx(sxr[1],syr[i]) rca.cx(sxr[1],ssr[0]) rca.ccx(sxr[0],syr[0],ssr[0]) rca.cx(sxr[2],sxr[1]) rca.ccx(ssr[0],syr[1],sxr[1]) rca.cx(sxr[3],sxr[2]) for i in range(2, summand_register_length-2): rca.ccx(syr[i],sxr[i-1],sxr[i]) rca.cx(sxr[i+2],sxr[i+1]) rca.ccx(syr[summand_register_length-2],sxr[summand_register_length-3],sxr[summand_register_length-2]) for i in range(1, summand_register_length-1): rca.x(syr[i]) rca.cx(ssr[0],syr[1]) for i in range(2, summand_register_length): rca.cx(sxr[i-1],syr[i]) rca.ccx(sxr[summand_register_length-3],syr[summand_register_length-2],sxr[summand_register_length-2]) for i in range(summand_register_length-3, 1, -1): rca.ccx(sxr[i-1],syr[i],sxr[i]) rca.cx(sxr[i+2],sxr[i+1]) rca.cx(sxr[i+2],syr[i+1]) rca.ccx(ssr[0],syr[1],sxr[1]) rca.cx(sxr[3],sxr[2]) rca.x(syr[2]) rca.ccx(sxr[0],syr[0],ssr[0]) rca.cx(sxr[2],sxr[1]) rca.x(syr[1]) rca.cx(sxr[1],ssr[0]) for i in range(summand_register_length): rca.cx(sxr[i],syr[i]) subinst_rca = rca.to_instruction() ''' AMPLITUDE AMPLIFICATION PROCEDURE: Calculation of coordinates using the ripple-carry adder b is a global variable used to navigate among the values of vector w. d stands for the position of an amino acid in a sequence. MODIFY NUMBER OF SOLUTIONS num_solutions FOR DIFFERENT SEQUENCES. ''' num_solutions = 8 num_iter = int(math.ceil(np.pi*(np.sqrt(2**(2*(length-1)/num_solutions)))/4)) # Number of iterations def calculate_neighbour(register, b, d): arglist = [] arglist.append(w[b]) arglist.append(w[b+1]) for i in range(len(ancilla)): arglist.append(ancilla[i]) arglist.append(carry[0]) for i in range(summand_register_length-1, -1, -1): # digit order reversed for adder arglist.append(binary_one[i]) for i in range(d*summand_register_length-1, (d-1)*summand_register_length-1, -1): # digit order reversed for adder arglist.append(register[i]) return arglist def update_coordinates(register_1, register_2): arglist = [] arglist.append(carry[0]) for i in range(summand_register_length-1, -1, -1): # digit order reversed for adder arglist.append(register_1[i]) reg = len(register_2) for i in reversed(range(reg)): # digit order reversed for adder arglist.append(register_2[i]) return arglist ''' THIS IS THE MAIN PART OF THE CODE. ''' for grover_iteration in range(num_iter): b = 0 # Subroutine 1: Generating conformational space by calculating coordinates # This part has been tested and performs correctly for d in range(2, length+1): for q in range(summand_register_length): qc.cx(x_coord[(d-2)*summand_register_length+q],x_coord[(d-1)*summand_register_length+q]) qc.cx(y_coord[(d-2)*summand_register_length+q],y_coord[(d-1)*summand_register_length+q]) ''' Calculating the western neighbour of site d-1 (this is the case when |w> = |11>) ''' for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) ''' Calculating the eastern neighbour of site d-1 (this is the case when |w> = |01>) ''' qc.x(w[b]) neighbour_east = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_east) qc.x(w[b]) ''' Calculating the northern neighbour of site d-1 (this is the case when |w> = |00>) ''' qc.x(w[b]) qc.x(w[b+1]) neighbour_north = calculate_neighbour(y_coord, b, d) qc.append(subinst, neighbour_north) qc.x(w[b]) qc.x(w[b+1]) ''' Calculating the southern neighbour of site d-1 (this is the case when |w> = |10>) ''' qc.x(w[b+1]) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = calculate_neighbour(x_coord, b, d) qc.append(subinst, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) qc.x(w[b+1]) b = b+2 ''' SECTION: FINDING ENERGY VALUES For the conformation that corresponds to the ground energy of the protein, the energy value will be e = 1, while e = 0 for all other confornations. The energy is calculated based on the number of hydrophobic-hydrophobic contacts in the lattice. For each such contact, a 1 is added to the energy value for the given conformation. New registers for calculating energy values based on the coordinates x and y: |x_star> and |y_star>. Register r_reg stores the result of coordinate comparison between sites k and j. Register delta stores the information as to whether the k-th and j-th lattice sites are both hydrophobic and form a loose contact (i.e., are adjacent in the lattice but not in the sequence). At the end of the computation, vector psi contains all the information about hydrophobic-hydrophobic contacts: psi(k, j, p) = |1> iff amino acid k and amino acid j, where j is p-neighbour of k, are both hydrophobic and have a contact in the lattice but not in the sequence. ''' # star_matrix: 3D array to hold the |x_star> and y_star indices # r_matrix: 3D array to hold the indices for r_reg # delta_matrix: 3D array to hold pairs of delta indices # psi_matrix: 3D array to hold psi indices. # All indexed in the coding convention, i.e. from 0 to n-1 instead of from 1 to n. star_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] r_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] delta_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] psi_matrix = [[[0 for k in range(length)] for j in range(length)] for p in range(4)] star_index, r_index, delta_index, psi_index = 0, 0, 0, 0 for k in range(length-3): for j in range(k+3, length): for p in range(4): star_matrix[k][j][p] = [m for m in range(star_index, star_index + register_length)] star_index += register_length r_matrix[k][j][p] = [m for m in range(r_index, r_index + 2*register_length + 1)] r_index += 2 * register_length + 1 delta_matrix[k][j][p] = (delta_index, delta_index+1) delta_index += 2 psi_matrix[k][j][p] = psi_index psi_index += 1 #The code below has not been tested within the algorithm but the indices are assigned correctly and so it should work for k in range(length-3): for j in range(k+3, length): for p in range(4): for r in range(register_length): qc.cx(x_coord[k+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[k+r], y_star[star_matrix[k][j][p][r]]) if p == 0: neighbour_north = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_north) if p == 1: neighbour_east = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_east) if p == 2: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) if p == 3: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) for r in range(register_length): qc.cx(x_coord[j+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[j+r], y_star[star_matrix[k][j][p][r]]) # rows 13 to 19 for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) qc.ccx(y_star[star_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][1]]) for r in reversed(range(1, register_length)): qc.ccx(y_star[star_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in reversed(range(register_length, 2*register_length)): qc.ccx(x_star[star_matrix[k][j][p][r-register_length]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) # row 20 onwards qc.ccx(sequence[k], r_reg[r_matrix[k][j][p][2*register_length]], delta[delta_matrix[k][j][p][0]]) qc.ccx(sequence[j], delta[delta_matrix[k][j][p][0]], delta[delta_matrix[k][j][p][1]]) qc.cx(delta[delta_matrix[k][j][p][1]], psi[psi_matrix[k][j][p]]) ''' Uncomputing calculation of H-H contacts (stored in vector psi) to free up qubits ''' #This part has not been tested due to running out of memory. But should be correct. for k in reversed(range(length-3)): for j in reversed(range(k+3, length)): for p in reversed(range(3)): qc.ccx(sequence[j], delta[delta_matrix[k][j][p][0]], delta[delta_matrix[k][j][p][1]]) qc.ccx(sequence[k], r_reg[r_matrix[k][j][p][2*register_length]], delta[delta_matrix[k][j][p][0]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) for r in range(register_length, 2*register_length): qc.ccx(x_star[star_matrix[k][j][p][r-register_length]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) for r in range(1, register_length): qc.ccx(y_star[star_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r]], r_reg[r_matrix[k][j][p][r+1]]) qc.ccx(y_star[star_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][0]], r_reg[r_matrix[k][j][p][1]]) for r in range(register_length): qc.x(y_star[star_matrix[k][j][p][r]]) qc.x(x_star[star_matrix[k][j][p][r]]) for r in reversed(range(register_length)): qc.cx(x_coord[j+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[j+r], y_star[star_matrix[k][j][p][r]]) if p == 0: neighbour_north = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_north) if p == 1: neighbour_east = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_east) if p == 2: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = update_coordinates(binary_one, [y_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) if p == 3: for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = update_coordinates(binary_one, [x_star[star_matrix[k][j][p][r]] for r in range(register_length)]) qc.append(subinst_rca, neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) for r in reversed(range(register_length)): qc.cx(x_coord[k+r], x_star[star_matrix[k][j][p][r]]) qc.cx(y_coord[k+r], y_star[star_matrix[k][j][p][r]]) # This part has been tested and performs correctly ''' # Reversing coordinate calculation ''' b = b-2 for d in range (length, 1, -1): # Uncomputing the western neighbour of site d-1 (|w> = |11>) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_west = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_west) for i in range(summand_register_length-1): qc.x(binary_one[i]) # Uncomputing the eastern neighbour of site d-1 (|w> = |01>) qc.x(w[b]) neighbour_east = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_east) qc.x(w[b]) # Uncomputing the northern neighbour of site d-1 (|w> = |00>) qc.x(w[b]) qc.x(w[b+1]) neighbour_north = calculate_neighbour(y_coord, b, d) qc.append(subinst.inverse(), neighbour_north) qc.x(w[b]) qc.x(w[b+1]) # Uncomputing the southern neighbour of site d-1 (|w> = |10>) qc.x(w[b+1]) for i in range(summand_register_length-1): qc.x(binary_one[i]) neighbour_south = calculate_neighbour(x_coord, b, d) qc.append(subinst.inverse(), neighbour_south) for i in range(summand_register_length-1): qc.x(binary_one[i]) qc.x(w[b+1]) b = b-2 for q in range(summand_register_length-1, -1, -1): qc.cx(x_coord[(d-2)*summand_register_length+q],x_coord[(d-1)*summand_register_length+q]) qc.cx(y_coord[(d-2)*summand_register_length+q],y_coord[(d-1)*summand_register_length+q]) ''' SUMMING UP ENERGY VALUES IN PSI = THIS IS THE CRUCIAL ORACLE PART STORING THE SUM OF ENERGIES IN VECTOR Z_{length-3, 3, j} FLIPPING THE BIT ON GROVER QUBIT g FOR THE LARGEST ENERGY VALUE p0_matrix = [ [ 0 for m in range(4 * (length-4) + 2) ] for n in range(length-2) ] kj = 0 for k in range(1, length-2): for j in range(4 * (k-1) + 2): p0_matrix[k][j] = kj kj += 1 p1_matrix = [ [ 0 for m in range(4 * (length-4) + 3) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 3): p1_matrix[k][j] = kj kj += 1 p2_matrix = [ [ 0 for m in range(4 * (length-4) + 4) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 4): p2_matrix[k][j] = kj kj += 1 p3_matrix = [ [ 0 for m in range(4 * (length-4) + 5) ] for n in range(length-2) ] for k in range(1, length-2): for j in range(4 * (k-1) + 5): p3_matrix[k][j] = kj kj += 1 ''' # Adding up the energies. # The energies for each conformation are stored in qubits z_{length-3, 3, j}. # If j = 0, there are no HH contacts and the energy is 0. # If j = 1, there is 1 HH contact and, hence, the energy is 1. And so on. for k in range(length-3): for p in range(4): multiplexer = [psi[psi_matrix[k][i][p]] for i in range(k+3, length)] for j in reversed(range(4*k + p + 1)): if p == 0: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j+1]]) # uncomputing to reuse the z_or and z_and ancillas qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j]]) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 1: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j+1]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 2: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j+1]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 3: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j+1]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) # This is the crucial part of the oracle # WE ASSUME j = 1 SINCE WE ASSUME THAT OUR SEQUENCE IS 01001, # i.e. second and fifth amino acids are hydrophobic, first, third and fourth are hydrophilic. # PARAMETER j IS ADJUSTABLE. j = 1 qc.cx(z[p3_matrix[length-3][j]], g) # Uncomputing the summation of energy for k in reversed(range(length-3)): for p in reversed(range(4)): multiplexer = [psi[psi_matrix[k][i][p]] for i in range(k+3, length)] for j in range(4*k + p + 1): if p == 0: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j+1]]) # uncomputing to reuse the z_or and z_and ancillas qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.cx(z_and, z[p0_matrix[k+1][j]]) qc.ccx(z_or, z[p3_matrix[k][3]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 1: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j+1]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.cx(z_and, z[p1_matrix[k+1][j]]) qc.ccx(z_or, z[p0_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 2: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j+1]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.cx(z_and, z[p2_matrix[k+1][j]]) qc.ccx(z_or, z[p1_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) elif p == 3: for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j+1]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) qc.mcx(multiplexer, z_or) qc.x(z_or) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.cx(z_and, z[p3_matrix[k+1][j]]) qc.ccx(z_or, z[p2_matrix[k+1][j]], z_and) qc.x(z_or) qc.mcx(multiplexer, z_or) for index, qubit in enumerate(multiplexer): qc.x(multiplexer[index]) ''' SECTION: IDENTIFYING THE CONFORMATION WITH THE MINIMAL ENERGY Using Grover's diffusion operation on register w ''' for i in range(len(w)): qc.h(w[i]) qc.x(w[i]) multiplexer = [w[i] for i in range(len(w) - 1)] qc.h(w[len(w) - 1]) qc.mcx(multiplexer, w[len(w) - 1]) qc.h(w[len(w) - 1]) for i in range(len(w)): qc.x(w[i]) qc.h(w[i]) ''' MEASUREMENT. WE ASSUME THAT THE AMINO ACID SEQUENCE IS PHPPH = 01001. HENCE, WE ARE EXPECTING TO SEE THE FOLLOWING VALUES IN THE CHART: 01011011 01101111 00000110 00001110 11111001 11110001 10100100 10101100 ''' conformations = [] for i in range(length): conformations.append(sequence[i]) for i in range(2*(length-1)): conformations.append(w[i]) # Reverse the order in which the output is shown so that it can be read from left to right. conformations.reverse() qc.measure(conformations, output) from qiskit import Aer, execute #from qiskit.providers.aer import QasmSimulator, StatevectorSimulator simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend = simulator, shots = 10).result() counts = result.get_counts() #statevector = result.get_statevector(qc) #print(statevector) #from qiskit.tools.visualization import plot_histogram #plot_histogram(counts) print(counts, sep='\n') qc.draw('mpl')
https://github.com/mvicenzi/grover-qiskit
mvicenzi
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit # Create a circuit with a register of three qubits circ = QuantumCircuit(3) # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. circ.h(0) # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. circ.cx(0, 1) # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. circ.cx(0, 2) # Draw the circuit circ.draw('mpl')
https://github.com/liyaochong/quantum-algorithm-learning-and-implementation
liyaochong
# 导入相应的运算库 import numpy as np from math import pi from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer # 定义相应的量子寄存器,并添加至电路当中去 # q0寄存器表示地址寄存器 q0 = QuantumRegister(2,'q0') c0 = ClassicalRegister(2,'c0') # q1寄存器表示数据寄存器,寄存器的位数表示计算的精度,这里设置为3,最后误差在0.125以内 q1 = QuantumRegister(4,'q1') c1 = ClassicalRegister(4,'c1') # q2寄存器表示执行量子算数的的目标寄存器,位数一般与q1寄存器相同 q2 = QuantumRegister(4,'q2') c2 = ClassicalRegister(4,'c2') # q3寄存器用来做辅助量子比特,执行系列的受控旋转操作 q3 = QuantumRegister(1,'q3') c3 = ClassicalRegister(1,'c3') # 定义一个量子电路对象 Circuit = QuantumCircuit() # 往寄存器中添加4个量子寄存器 Circuit.add_register(q0,c0) Circuit.add_register(q1,c1) Circuit.add_register(q2,c2) Circuit.add_register(q3,c3) # 添加量子门操作,注意这里的命名方式为最低有效位 # 执行H门操作,将地址寄存器q0张开,分叉存储,由于两个数据只需要用1个量子比特进行表示 Circuit.h(q0[0]) Circuit.h(q0[1]) # 写入数据至q1寄存器,更为通用的采用的是QRAM算法,或者其他数据制备算法,注意这里的数据用基态表示,本质上以经典的形式出现 Circuit.barrier() Circuit.cx(q0[0],q1[0]) Circuit.x(q1[1]) Circuit.x(q0[0]) Circuit.ccx(q0[0],q0[1],q1[2]) Circuit.x(q0[0]) Circuit.cx(q0[1],q1[3]) # 这里执行的量子算数运算,进行的是类似一个函数的运算过程 Circuit.barrier() Circuit.x(q1[0]) Circuit.cx(q1[0],q2[0]) Circuit.x(q1[0]) Circuit.x(q1[2]) Circuit.ccx(q1[1],q1[2],q2[1]) Circuit.x(q1[2]) Circuit.x(q2[2]) Circuit.x(q1[0]) Circuit.x(q1[2]) Circuit.ccx(q1[0],q1[2],q2[2]) Circuit.x(q1[0]) Circuit.x(q1[2]) Circuit.x(q2[3]) Circuit.x(q1[2]) Circuit.ccx(q1[2],q1[3],q2[3]) Circuit.x(q1[2]) # 执行受控旋转操作,将数据从函数运算的输出,加载到概率幅度上 Circuit.barrier() Circuit.cu3(pi/2, 0, 0, q2[0], q3) Circuit.cu3(pi/4, 0, 0, q2[1], q3) Circuit.cu3(pi/8, 0, 0, q2[2], q3) Circuit.cu3(pi/16, 0, 0, q2[3], q3) # 执行量子算数运算的解运算过程 Circuit.barrier() Circuit.x(q1[2]) Circuit.ccx(q1[2],q1[3],q2[3]) Circuit.x(q1[2]) Circuit.x(q2[3]) Circuit.x(q1[2]) Circuit.x(q1[0]) Circuit.ccx(q1[0],q1[2],q2[2]) Circuit.x(q1[2]) Circuit.x(q1[0]) Circuit.x(q2[2]) Circuit.x(q1[2]) Circuit.ccx(q1[1],q1[2],q2[1]) Circuit.x(q1[2]) Circuit.x(q1[0]) Circuit.cx(q1[0],q2[0]) Circuit.x(q1[0]) # 执行数据的量子制备过程的逆变换(IQRAM),完成解运算 Circuit.barrier() Circuit.cx(q0[1],q1[3]) Circuit.x(q0[0]) Circuit.ccx(q0[0],q0[1],q1[2]) Circuit.x(q0[0]) Circuit.x(q1[1]) Circuit.cx(q0[0],q1[0]) #Circuit.h(q0[0]) #Circuit.h(q0[1]) # 添加测量操作,量子寄存器关联相应的经典寄存器 Circuit.barrier() Circuit.measure(q0,c0) Circuit.measure(q1,c1) Circuit.measure(q2,c2) Circuit.measure(q3,c3) # 绘制整个量子电路图 Circuit.draw(output='mpl') # 使用 Aer's qasm_simulator backend_sim = BasicAer.get_backend('qasm_simulator') # 执行量子仿真器 job_sim = execute(Circuit, backend_sim, shots=8096) # 获得结果 result_sim = job_sim.result() counts = result_sim.get_counts(Circuit) # 打印结果输出 print(counts)
https://github.com/CodeJP97/QHT-2022-WoQ
CodeJP97
import numpy as np # Importing standard Qiskit libraries from qiskit.quantum_info import Statevector from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## X-gate # FILL IN YOUR CODE HERE # Keep theta<=np.pi theta = np.pi phi = 0 lam = np.pi #ex1_validation([theta, phi,lam]) ## Z-gate # FILL IN YOUR CODE HERE theta = 0 phi = np.pi lam = 0 #ex2_validation([theta, phi,lam]) ## Y-gate # FILL IN YOUR CODE HERE theta = np.pi phi = np.pi/2 lam = np.pi/2 #ex3_validation([theta, phi,lam]) ## Hadamard # FILL IN YOUR CODE HERE theta = np.pi/2 phi = 0 lam = np.pi #ex4_validation([theta, phi, lam]) ## Which rotation corresponds to the gate set H-Y-S-T ? #Circuit: qc=QuantumCircuit(1) qc.h(0) qc.y(0) qc.s(0) qc.t(0) ##FILL IN YOUR ANSWER HERE theta = np.pi/2 phi = 7*np.pi/4 lam = np.pi #Check the result with the u3 rotation gate (arbitrary single qubit rotations) qc2=QuantumCircuit(1) qc2.u3(theta,phi,lam,0) #ex5_validation(qc2) state = Statevector.from_instruction(qc) plot_bloch_multivector(state) state2 = Statevector.from_instruction(qc2) plot_bloch_multivector(state2)
https://github.com/swe-train/qiskit__qiskit
swe-train
from qiskit import * from qiskit.tools.visualization import plot_bloch_multivector import matplotlib.pyplot as plt from qiskit.visualization.gate_map import plot_coupling_map, plot_gate_map from qiskit.visualization.state_visualization import plot_bloch_vector, plot_state_city, plot_state_paulivec circuit = QuantumCircuit(1,1) circuit.x(0) simulator = Aer.get_backend('statevector_simulator') result = execute(circuit, backend = simulator).result() statevector = result.get_statevector() print(statevector) simulator2 = Aer.get_backend('unitary_simulator') result = execute(circuit, backend= simulator2).result() unitary = result.get_unitary() print(unitary)
https://github.com/Dpbm/scientific-research-1-quantum-oracles
Dpbm
from qiskit import QuantumCircuit, transpile, QuantumRegister, ClassicalRegister, AncillaRegister from qiskit_aer import AerSimulator from qiskit.circuit.library import MCMT, GroverOperator from qiskit.quantum_info import Statevector from math import pi from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.circuit import Parameter import numpy as np import pandas as pd import matplotlib.pyplot as plt from utils import get_image_path import seaborn as sns from qutip import Bloch, Qobj from itertools import combinations, product def get_diffuser(total_qubits): mct = MCMT('x', total_qubits-1, 1) qc = QuantumCircuit(total_qubits) qc.h(range(total_qubits)) qc.x(range(total_qubits)) qc.h(-1) qc.compose(mct, range(total_qubits), inplace=True) qc.h(-1) qc.x(range(total_qubits)) qc.h(range(total_qubits)) return qc def classical_grover(oracle): total_qubits = oracle.num_qubits qc = QuantumCircuit(total_qubits) grover = GroverOperator(oracle).decompose() qc.h(range(total_qubits)) qc.compose(grover, range(total_qubits), inplace=True) return qc def phase_oracle(states): total_qubits = len(states[0]) mct = MCMT('z', total_qubits-1, 1) qc = QuantumCircuit(total_qubits, name="oracle") for state in states: zeros = [i for i, bit in enumerate(state[::-1]) if bit == '0'] if(zeros): qc.x(zeros) qc.compose(mct,range(total_qubits),inplace=True) if(zeros): qc.x(zeros) return qc oracle = phase_oracle(['100']) oracle.draw('mpl') classical_grover(oracle).draw('mpl') def get_counts(qc, sim=AerSimulator(), shots=1000): qc_c = qc.copy() qc_c.measure_all() transpiled = transpile(qc_c, sim) return sim.run(transpiled, shots=shots).result().get_counts() def new_grover(oracle): theta = Parameter('theta') total_qubits = oracle.num_qubits qc = QuantumCircuit(total_qubits) qc.ry(theta, range(total_qubits)) qc.barrier() qc.append(oracle, range(total_qubits)) qc.barrier() qc.compose(get_diffuser(total_qubits), range(total_qubits), inplace=True) return qc, theta n_grover,theta = new_grover(oracle) n_grover.draw('mpl') def find_best_angle(theta, qc, values_space, target_bit_string, debug=False): best_angle = 0 best_total = 0 for angle in values_space: bc = qc.assign_parameters({theta:angle}) counts = get_counts(bc) value = 0 if(counts.get(target_bit_string)): value = counts[target_bit_string] if(value > best_total): best_total = value best_angle = angle if(debug): print(angle, value) return best_angle, best_total best_angle, best_total = find_best_angle(theta, n_grover, np.linspace(0, pi, num=1000), '001', debug=True) best_angle, best_total BIT_STRINGS_3 = ['000', '001', '010', '011', '100', '101', '110', '111'] def compare_old_new_1_bit_string(bit_strings, values_space, debug=False): old = {} new = {} angles = {} for bit_string in bit_strings: oracle = phase_oracle([bit_string]) old_ = classical_grover(oracle.copy()) if(debug): display(old_.draw('mpl')) old_counts = get_counts(old_) old_total = 0 if(old_counts.get(bit_string)): old[bit_string] = old_counts[bit_string] new_, theta = new_grover(oracle.copy()) angle, max_ = find_best_angle(theta, new_, values_space, bit_string) new[bit_string] = max_ angles[bit_string] = angle data = {"old":old, "new":new, "angles":angles} return pd.DataFrame(data, columns=("old", "new", "angles"), index=bit_strings) results_1 = compare_old_new_1_bit_string(BIT_STRINGS_3, np.linspace(0, pi, num=500)) results_1 plt.plot(results_1.index.tolist(), results_1['new'], label="new") plt.plot(results_1.index.tolist(), results_1['old'], label="old") plt.title('old vs new Grover improvement (range [0, $\pi$])') plt.xlabel("bit string") plt.ylabel("counts") plt.legend(loc="upper right") plt.savefig(get_image_path("superposition-improvement-grover-algorithm-range-0-to-pi.png")) plt.show() results_2 = compare_old_new_1_bit_string(BIT_STRINGS_3, np.linspace(0, 2*pi, num=500)) results_2 plt.plot(results_2.index.tolist(), results_2['new'], label="new") plt.plot(results_2.index.tolist(), results_2['old'], label="old") plt.title('old vs new Grover improvement (range [0, $2\pi$])') plt.xlabel("bit string") plt.ylabel("counts") plt.legend(loc="upper right") plt.savefig(get_image_path("superposition-improvement-grover-algorithm-range-0-to-2pi.png")) plt.show() plt.plot(BIT_STRINGS_3, results_1['angles'], label="first") plt.plot(BIT_STRINGS_3, results_2['angles'], label="second") plt.title('angles comparation ([0, $\pi$] vs [0, $2\pi$])') plt.xlabel("bit string") plt.ylabel("angle") plt.legend(loc="upper right") plt.savefig(get_image_path("improvement-grover-algorithm-angles-comparation-0-pi-and-2pi.png")) plt.show() results_3 = compare_old_new_1_bit_string([bin(i)[2:].zfill(4) for i in range(2**4)], np.linspace(0, 2*pi, num=500)) results_3 plt.plot(results_3.index.tolist(), results_3['new'], label="new") plt.plot(results_3.index.tolist(), results_3['old'], label="old") plt.title('old vs new Grover improvement (range [0, $2\pi$])') plt.xlabel("bit string") plt.ylabel("counts") plt.xticks(rotation = 45) plt.legend(loc="upper right") plt.savefig(get_image_path("improvement-grover-algorithm-4bits-0-to-2pi.png")) plt.show() pi/2 mid_values = results_3["angles"].drop(["0000", "1111"]) mid_values mid_values.describe() mid_values.mean(), pi/2 bloch_data = results_3 bloch_data['alfa'] = np.cos(bloch_data["angles"]/2) bloch_data['beta'] = np.sin(bloch_data["angles"]/2) bloch_data def show_bloch(states): bloch = Bloch() bloch.make_sphere() bloch.add_states(states) display(bloch.show()) for i in bloch_data.index.tolist(): print(i, i.count('0')) states = [] for i in range(len(bloch_data)): row = bloch_data.iloc[i] alfa,beta = row['alfa'], row['beta'] states.append(Qobj([[alfa], [beta]])) show_bloch(states) states = [] for i in range(len(bloch_data)): row = bloch_data.iloc[i] if(row.name.count('0') >= 3): alfa,beta = row['alfa'], row['beta'] states.append(Qobj([[alfa], [beta]])) show_bloch(states) states = [] for i in range(len(bloch_data)): row = bloch_data.iloc[i] if(row.name.count('0') == 2): alfa,beta = row['alfa'], row['beta'] states.append(Qobj([[alfa], [beta]])) show_bloch(states) states = [] for i in range(len(bloch_data)): row = bloch_data.iloc[i] if(row.name.count('0') <= 1): alfa,beta = row['alfa'], row['beta'] states.append(Qobj([[alfa], [beta]])) show_bloch(states) def show_unitary(qc, sim=AerSimulator()): qc_c = qc.copy() qc_c.save_unitary() transpiled = transpile(qc_c, sim) u = sim.run(transpiled, shots=1000).result().get_unitary() display(array_to_latex(u, max_size=100000)) d = pd.DataFrame(columns=("a", "b", "c")) d["a"] = BIT_STRINGS_2 = ['00', '01', '10', '11'] def test_angle_with_multiple_bit_strings(bit_strings): df = pd.DataFrame(columns=("angle", *bit_strings, "default"), index=bit_strings) for string in bit_strings: oracle = phase_oracle([string]) n_grover,theta = new_grover(oracle.copy()) best_angle, best_total = find_best_angle(theta, n_grover, np.linspace(0, pi, num=1000), string, debug=False) df.loc[string]['angle'] = best_angle df.loc[string][string] = best_total default = classical_grover(oracle.copy()) default_counts = get_counts(default) default_total = 0 if(default_counts.get(string)): default_total = default_counts[string] df.loc[string]['default'] = default_total for string2 in set(bit_strings)-{string}: oracle = phase_oracle([string2]) n_grover_2,theta_2 = new_grover(oracle.copy()) bc = n_grover_2.assign_parameters({theta_2: best_angle}) counts = get_counts(bc) total = 0 if(counts.get(string2)): total = counts[string2] df.loc[string2][string] = total return df df = test_angle_with_multiple_bit_strings(BIT_STRINGS_2) df fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) ax1.plot(BIT_STRINGS_2, df['00']) ax2.plot(BIT_STRINGS_2, df['01']) ax3.plot(BIT_STRINGS_2, df['10']) ax4.plot(BIT_STRINGS_2, df['11']) plt.show() df = test_angle_with_multiple_bit_strings(BIT_STRINGS_3) df plt.figure(figsize=(13, 7)) sns.set_palette("Blues") for string in BIT_STRINGS_3: sns.lineplot(data=df, x=BIT_STRINGS_3, y=string, label=f"{string} angle") sns.lineplot(data=df, x=BIT_STRINGS_3, y="default", label="classical Grover", color="red") plt.xlabel("bit strings") plt.ylabel("counts") plt.legend(loc="upper right") plt.show() df.describe() df.std() angles = df['angle'][1:-2] angles = angles.reset_index() angles = angles.drop(columns=['index']) angles.loc[5] = pi/2 angles angles.std() data = pd.DataFrame(columns=("+", "=", "-"), index=BIT_STRINGS_3) default_theta = pi/2 deviation = angles.std()['angle'] for index, t_value in (('-', default_theta-deviation), ('=', default_theta), ('+', default_theta+deviation)): for bit_string in BIT_STRINGS_3: oracle = phase_oracle([bit_string]) ng, theta = new_grover(oracle) bc = ng.assign_parameters({theta:t_value}) counts = get_counts(bc) total = 0 if(counts.get(bit_string)): total = counts[bit_string] data.loc[bit_string][index] = total data data.describe() data.std() sns.set_palette("flare") sns.lineplot(data=data, x=BIT_STRINGS_3, y='-', label="-deviation") sns.lineplot(data=data, x=BIT_STRINGS_3, y='=', label="=") sns.lineplot(data=data, x=BIT_STRINGS_3, y='+', label="+deviation") plt.xlabel("bit strings") plt.ylabel("counts") plt.legend(loc="upper right") plt.show() oracle = phase_oracle(['010', '110']) oracle.draw('mpl') ng, theta = new_grover(oracle) ng.draw('mpl') def find_best_angle_multiple_bs(theta, qc, values_space, target_bit_strings, debug=False): best_angle = 0 best_total = 0 for angle in values_space: bc = qc.assign_parameters({theta:angle}) counts = get_counts(bc) value = 0 for bit_string in target_bit_strings: if(counts.get(bit_string)): value += counts[bit_string] if(value > best_total): best_total = value best_angle = angle if(debug): print(angle, value) return best_angle, best_total angle, max_ = find_best_angle_multiple_bs(theta, ng, np.linspace(0, pi, num=1000), ['010', '110']) angle,max_ ng, theta = new_grover(oracle) bc = ng.assign_parameters({theta:angle}) bc.draw('mpl') plot_histogram(get_counts(bc)) c = classical_grover(oracle) plot_histogram(get_counts(c)) df = pd.DataFrame(columns=("bs_1", "bs_2", "bs_3", "angle","max_new", "max_old")) for i, comb in enumerate(combinations(BIT_STRINGS_3, 3)): oracle = phase_oracle(comb) old_ = classical_grover(oracle.copy()) new_,theta = new_grover(oracle.copy()) #get old old_counts = get_counts(old_) total_old = 0 for c in comb: if(old_counts.get(c)): total_old += old_counts[c] #get new angle, max_ = find_best_angle_multiple_bs(theta, new_, np.linspace(0, pi, num=200), comb) df.loc[i] = (comb[0], comb[1], comb[2], angle, max_, total_old) df data = df data["data"] = df["bs_1"] + " " + df["bs_2"] + " " + df["bs_3"] data plt.figure(figsize=(20,7)) sns.lineplot(data=data, x="data", y="max_old", label="grover") sns.lineplot(data=data, x="data", y="max_new", label="new grover") plt.xlabel("") plt.ylabel("counts") plt.xticks(rotation=90) plt.legend(loc="upper right") plt.savefig(get_image_path("multiple_strings_new_grover_best_angles.png")) plt.show() data['alfa'] = np.cos(data["angle"]/2) data['beta'] = np.sin(data["angle"]/2) data states = [] for i in range(len(data)): row = data.loc[i] alfa,beta = row['alfa'], row['beta'] states.append(Qobj([[alfa], [beta]])) show_bloch(states) plt.figure(figsize=(20, 7)) sns.lineplot(data=data, x="data", y="alfa") sns.lineplot(data=data, x="data", y="beta") plt.xticks(rotation=90) plt.show() data["t_zeros"] = data["data"].str.count('0') data more_zeros = data[data['t_zeros'] >= 5] more_zeros more_zeros[['alfa', 'beta', 't_zeros']].describe() more_zeros['alfa'].mean() #alfa = cos(theta/2) #cos^-1(alfa) = theta/2 #(cos^-1(alfa))*2 = theta theta = np.arccos(more_zeros['alfa'].mean())*2 theta, np.degrees(theta) melted = pd.melt(more_zeros, id_vars=['t_zeros'], value_vars=['alfa', 'beta'], var_name="amplitude") melted sns.barplot(data=melted, x="t_zeros", y="value", hue="amplitude") plt.legend(loc="lower right") plt.show() data_2 = data data_2 = data_2[['t_zeros', 'alfa', 'beta']] data_2 melted_entire = pd.melt(data_2, id_vars=['t_zeros'], value_vars=['alfa', 'beta'], var_name="amplitude") melted_entire sns.barplot(data=melted_entire, x="t_zeros", y="value", hue="amplitude") plt.legend(loc="lower right") plt.ylabel("amplitude") plt.savefig(get_image_path("amplitudes_based_on_total_zeros_new_grover.png")) plt.show() df = compare_old_new_1_bit_string(BIT_STRINGS_3, np.linspace(0, pi, num=200)) df df['alfa'] = np.cos(df['angles']/2) df['beta'] = np.sin(df['angles']/2) df df['t_zeros'] = df.index.str.count('0') df melted_entire_2 = pd.melt(df, id_vars=['t_zeros'], value_vars=['alfa', 'beta'], var_name="amplitude") melted_entire_2 sns.barplot(data=melted_entire_2, x="t_zeros", y="value", hue="amplitude") plt.legend(loc="lower right") plt.ylabel("amplitude") plt.savefig(get_image_path("amplitudes_based_on_total_zeros_new_grover_one_bit_string.png")) plt.show() q = QuantumCircuit(2) q.ry(1.957575,0) q.ry(1.294526,1) plot_bloch_multivector(q) np.degrees((3*pi)/4) def create_grover(strings): total_zeros = sum([ string.count('0') for string in strings ]) n_qubits = len(strings[0]) N = 2**n_qubits t = N/2 if(n_qubits == 2): angle = pi/2 if(total_zeros == n_qubits): angle = 0.963001 elif(total_zeros == 0): angle = 2.099657 else: angle = 1.657624 oracle = phase_oracle(strings) ng, theta = new_grover(oracle) bc = ng.assign_parameters({theta:angle}) return bc g = create_grover(['111']) plot_histogram(get_counts(g)) o = phase_oracle(['000']) c = classical_grover(o) plot_histogram(get_counts(c)) plot_histogram(get_counts(create_grover(['100','111', '000']))) o = phase_oracle(['100','111', '000']) c = classical_grover(o) plot_histogram(get_counts(c)) def run_for_2(bit_strings): df = pd.DataFrame(columns=("bs_1", "bs_2", "angle","max_new", "max_old")) for i, comb in enumerate(combinations(bit_strings, 2)): oracle = phase_oracle(comb) old_ = classical_grover(oracle.copy()) new_,theta = new_grover(oracle.copy()) #get old old_counts = get_counts(old_) total_old = 0 for c in comb: if(old_counts.get(c)): total_old += old_counts[c] #get new angle, max_ = find_best_angle_multiple_bs(theta, new_, np.linspace(0, pi, num=200), comb) df.loc[i] = (comb[0], comb[1], angle, max_, total_old) return df df = run_for_2(BIT_STRINGS_3) df.head() # all angles get around pi/2 df['angle'].unique() data = df data["data"] = df["bs_1"] + " " + df["bs_2"] data.head() sns.lineplot(data=data, x="data", y="max_new") sns.lineplot(data=data, x="data", y="max_old") plt.xticks(rotation=90) plt.xlabel("bit strings") plt.ylabel("counts") plt.savefig(get_image_path("2_bit_strings_l3_new_grover.png")) plt.show() plt.plot(df['angle']) plt.show() df = run_for_2(BIT_STRINGS_2) df.head() data = df data["data"] = df["bs_1"] + " " + df["bs_2"] data.head() sns.lineplot(data=data, x="data", y="max_new", label="new") sns.lineplot(data=data, x="data", y="max_old", label="old") plt.xticks(rotation=90) plt.xlabel("bit strings") plt.ylabel("counts") plt.legend(loc="upper right") plt.savefig(get_image_path("2_bit_strings_l2_new_grover.png")) plt.show() plt.plot(df['angle']) plt.show() BIT_STRINGS_4 = [''.join(i) for i in product('01', repeat=4)] BIT_STRINGS_4 df = run_for_2(BIT_STRINGS_4) df.head() data = df data["data"] = df["bs_1"] + " " + df["bs_2"] data.head() plt.figure(figsize=(20, 7)) sns.lineplot(data=data, x="data", y="max_new", label="new") sns.lineplot(data=data, x="data", y="max_old", label="old") plt.xticks(rotation=90) plt.xlabel("bit strings") plt.ylabel("counts") plt.legend(loc="upper right") plt.savefig(get_image_path("2_bit_strings_l4_new_grover.png")) plt.show() def get_statistics_for_bit_strings(bit_strings_l): for bs in bit_strings_l: oracle = phase_oracle(bs) ng, theta = new_grover(oracle.copy()) angle, max_ = find_best_angle_multiple_bs(theta, ng, np.linspace(0, pi, num=200), bs) total_bit_strings = len(bs) l = len(bs[0]) bc = ng.assign_parameters({theta:angle}) print(f"----{total_bit_strings} bit strings with length {l}----") display(bc.draw('mpl', filename=get_image_path(f"new_grover_rotation_for_{total_bit_strings}_bit_strings_l{l}.png"))) plot_histogram(get_counts(bc), filename=get_image_path(f"new_grover_for_{total_bit_strings}_bit_strings_l{l}_outcomes.png")) display(plot_histogram(get_counts(bc))) c = classical_grover(oracle.copy()) display(c.draw('mpl', filename=get_image_path(f"classical_grover_for_{total_bit_strings}_bit_strings_l{l}.png"))) plot_histogram(get_counts(c), filename=get_image_path(f"classical_grover_for_{total_bit_strings}_bit_strings_l{l}_outcomes.png")) display(plot_histogram(get_counts(c))) get_statistics_for_bit_strings([ ['01'], ['01', '10'], ['01', '10', '00'], ['010'], ['010', '101'], ['010', '101', '110'], ['0101'], ['0101', '1101'], ['0101', '1101', '1001'], ['01011'], ['01011', '01101'], ['01011', '01101', '10111'], ])
https://github.com/rochisha0/quantum-ugly-duckling
rochisha0
import math import statistics import matplotlib.pyplot as plt import numpy as np from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers.aer import QasmSimulator # Import from Qiskit Aer noise module from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise import QuantumError, ReadoutError from qiskit.providers.aer.noise import pauli_error def runsTest(l, l_median): ''' Returns Z; If Z>1.96 then numbers are not random ''' runs, n1, n2 = 0, 0, 0 # Checking for start of new run for i in range(len(l)): # no. of runs if (l[i] >= l_median and l[i-1] < l_median) or (l[i] < l_median and l[i-1] >= l_median): runs += 1 # no. of positive values if(l[i]) >= l_median: n1 += 1 # no. of negative values else: n2 += 1 runs_exp = ((2*n1*n2)/(n1+n2))+1 stan_dev = math.sqrt((2*n1*n2*(2*n1*n2-n1-n2))/ (((n1+n2)**2)*(n1+n2-1))) z = (runs-runs_exp)/stan_dev return z def get_noise(): ''' It returns the the noise model that uses bit flip error noise model. When applying a single qubit gate, flip the state of the qubit with probability p_gate1. When applying a 2-qubit gate apply single-qubit errors to each qubit. When resetting a qubit reset to 1 instead of 0 with probability p_reset. When measuring a qubit, flip the state of the qubit with probability p_meas. ''' p_reset = 0.03 p_meas = 0.1 p_gate1 = 0.05 # QuantumError objects error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)]) error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)]) error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)]) error_gate2 = error_gate1.tensor(error_gate1) # Add errors to noise model noise_bit_flip = NoiseModel() noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset") noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure") noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"]) noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"]) return noise_bit_flip def random_number(): ''' Returns random numbers between 0 to 15 ''' circ = QuantumCircuit(4) simulator = QasmSimulator() #NQRNS Circuit for i in range(200): circ.u3(0,0,0,0) circ.u3(0,0,0,1) circ.u3(0,0,0,2) circ.u3(0,0,0,3) circ.cx(0,1) circ.cx(1,2) circ.cx(0,2) circ.cx(0,3) circ.cx(1,3) circ.cx(2,3) circ.barrier() circ.measure_all() noise_bit_flip = get_noise() #get output job = execute(circ, simulator, basis_gates=noise_bit_flip.basis_gates, noise_model=noise_bit_flip, shots= 1) result_bit_flip = job.result() counts_bit_flip = result_bit_flip.get_counts(0) num=list(counts_bit_flip.keys())[0] num = int(num, 2) return num l= [] for i in range(100): l.append(random_number()) l_median= statistics.median(l) Z = abs(runsTest(l, l_median)) print('Z-statistic= ', Z) dt = .1 #some time n = 1000 #n-number of datapoints for i in range(1000): l.append(random_number()) fhat=np.fft.fft(l,n) #f-data ,n-number of datapoints per set freq=(1/(dt*n))*np.arange(n) PSD2=np.log(np.abs(np.fft.fftshift(fhat))**2) plt.plot(freq.real,PSD2.real) plt.xlabel('frequency') plt.ylabel('number of occurence') plt.show()
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. import cirq import numpy as np import pyquil import pytest import qiskit from cirq import Circuit from mitiq.pec.types import NoisyBasis, NoisyOperation, OperationRepresentation from mitiq.utils import _equal icirq = Circuit(cirq.I(cirq.LineQubit(0))) xcirq = Circuit(cirq.X(cirq.LineQubit(0))) ycirq = Circuit(cirq.Y(cirq.LineQubit(0))) zcirq = Circuit(cirq.Z(cirq.LineQubit(0))) hcirq = Circuit(cirq.H(cirq.LineQubit(0))) cnotcirq = Circuit(cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1))) def test_init_with_cirq_circuit(): real = np.zeros(shape=(4, 4)) noisy_op = NoisyOperation(zcirq, real) assert isinstance(noisy_op._circuit, cirq.Circuit) assert noisy_op.qubits == (cirq.LineQubit(0),) assert np.allclose(noisy_op.channel_matrix, real) assert noisy_op.channel_matrix is not real assert noisy_op._native_type == "cirq" assert _equal(zcirq, noisy_op.circuit) assert _equal(noisy_op._native_circuit, noisy_op.circuit) @pytest.mark.parametrize( "qubit", (cirq.LineQubit(0), cirq.GridQubit(1, 2), cirq.NamedQubit("Qubit")), ) def test_init_with_different_qubits(qubit): ideal_op = Circuit(cirq.H.on(qubit)) real = np.zeros(shape=(4, 4)) noisy_op = NoisyOperation(ideal_op, real) assert isinstance(noisy_op._circuit, cirq.Circuit) assert _equal( noisy_op.circuit, cirq.Circuit(ideal_op), require_qubit_equality=True, ) assert noisy_op.qubits == (qubit,) assert np.allclose(noisy_op.channel_matrix, real) assert noisy_op.channel_matrix is not real assert noisy_op._native_type == "cirq" assert _equal(cirq.Circuit(ideal_op), noisy_op.circuit) assert _equal(noisy_op._native_circuit, noisy_op.circuit) def test_init_with_cirq_input(): qreg = cirq.LineQubit.range(2) circ = cirq.Circuit(cirq.H.on(qreg[0]), cirq.CNOT.on(*qreg)) real = np.zeros(shape=(16, 16)) noisy_op = NoisyOperation(circ, real) assert isinstance(noisy_op._circuit, cirq.Circuit) assert _equal(noisy_op.circuit, circ, require_qubit_equality=True) assert set(noisy_op.qubits) == set(qreg) assert np.allclose(noisy_op.channel_matrix, real) assert noisy_op.channel_matrix is not real def test_init_with_qiskit_circuit(): qreg = qiskit.QuantumRegister(2) circ = qiskit.QuantumCircuit(qreg) _ = circ.h(qreg[0]) _ = circ.cx(*qreg) cirq_qreg = cirq.LineQubit.range(2) cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg)) real = np.zeros(shape=(16, 16)) noisy_op = NoisyOperation(circ, real) assert isinstance(noisy_op._circuit, cirq.Circuit) assert _equal(noisy_op._circuit, cirq_circ) assert _equal(noisy_op.circuit, cirq_circ) assert noisy_op.native_circuit == circ assert noisy_op._native_circuit == circ assert noisy_op._native_type == "qiskit" assert np.allclose(noisy_op.channel_matrix, real) assert noisy_op.channel_matrix is not real @pytest.mark.parametrize( "gate", ( cirq.H, cirq.H(cirq.LineQubit(0)), qiskit.circuit.library.HGate, qiskit.circuit.library.CHGate, pyquil.gates.H, ), ) def test_init_with_gates_raises_error(gate): rng = np.random.RandomState(seed=1) with pytest.raises(TypeError, match="Failed to convert to an internal"): NoisyOperation(circuit=gate, channel_matrix=rng.rand(4, 4)) def test_init_with_pyquil_program(): circ = pyquil.Program(pyquil.gates.H(0), pyquil.gates.CNOT(0, 1)) cirq_qreg = cirq.LineQubit.range(2) cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg)) real = np.zeros(shape=(16, 16)) noisy_op = NoisyOperation(circ, real) assert isinstance(noisy_op._circuit, cirq.Circuit) assert _equal(noisy_op._circuit, cirq_circ) assert _equal(noisy_op.circuit, cirq_circ) assert noisy_op.native_circuit == circ assert noisy_op._native_circuit == circ assert noisy_op._native_type == "pyquil" assert np.allclose(noisy_op.channel_matrix, real) assert noisy_op.channel_matrix is not real def test_init_dimension_mismatch_error(): ideal = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) real = np.zeros(shape=(3, 3)) with pytest.raises(ValueError, match="has shape"): NoisyOperation(ideal, real) def test_unknown_channel_matrix(): qreg = qiskit.QuantumRegister(2) circ = qiskit.QuantumCircuit(qreg) _ = circ.h(qreg[0]) _ = circ.cx(*qreg) cirq_qreg = cirq.LineQubit.range(2) cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg)) noisy_op = NoisyOperation(circ) assert isinstance(noisy_op._circuit, cirq.Circuit) assert _equal(noisy_op._circuit, cirq_circ) assert _equal(noisy_op.circuit, cirq_circ) assert noisy_op.native_circuit == circ assert noisy_op._native_circuit == circ assert noisy_op._native_type == "qiskit" with pytest.raises(ValueError, match="The channel matrix is unknown."): _ = noisy_op.channel_matrix def test_add_simple(): circuit1 = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))]) circuit2 = cirq.Circuit([cirq.Y.on(cirq.NamedQubit("Q"))]) super_op1 = np.random.rand(4, 4) super_op2 = np.random.rand(4, 4) noisy_op1 = NoisyOperation(circuit1, super_op1) noisy_op2 = NoisyOperation(circuit2, super_op2) noisy_op = noisy_op1 + noisy_op2 correct = cirq.Circuit( [cirq.X.on(cirq.NamedQubit("Q")), cirq.Y.on(cirq.NamedQubit("Q"))], ) assert _equal(noisy_op._circuit, correct, require_qubit_equality=True) assert np.allclose(noisy_op.channel_matrix, super_op2 @ super_op1) def test_add_pyquil_noisy_operations(): ideal = pyquil.Program(pyquil.gates.X(0)) real = np.random.rand(4, 4) noisy_op1 = NoisyOperation(ideal, real) noisy_op2 = NoisyOperation(ideal, real) noisy_op = noisy_op1 + noisy_op2 correct = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))] * 2) assert _equal(noisy_op._circuit, correct, require_qubit_equality=False) assert np.allclose(noisy_op.channel_matrix, real @ real) def test_add_qiskit_noisy_operations(): qreg = qiskit.QuantumRegister(1) ideal = qiskit.QuantumCircuit(qreg) _ = ideal.x(qreg) real = np.random.rand(4, 4) noisy_op1 = NoisyOperation(ideal, real) noisy_op2 = NoisyOperation(ideal, real) noisy_op = noisy_op1 + noisy_op2 correct = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))] * 2) assert _equal(noisy_op._circuit, correct, require_qubit_equality=False) assert np.allclose(noisy_op.channel_matrix, real @ real) def test_add_bad_type(): ideal = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))]) real = np.random.rand(4, 4) noisy_op = NoisyOperation(ideal, real) with pytest.raises(ValueError, match="must be a NoisyOperation"): noisy_op + ideal def test_add_noisy_operation_no_channel_matrix(): noisy_op1 = NoisyOperation(cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))])) noisy_op2 = NoisyOperation( cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))]), channel_matrix=np.random.rand(4, 4), ) with pytest.raises(ValueError): (noisy_op1 + noisy_op2).channel_matrix def test_noisy_operation_str(): noisy_op = NoisyOperation(circuit=icirq, channel_matrix=np.identity(4)) assert isinstance(noisy_op.__str__(), str) def test_noisy_basis_deprecation_error(): with pytest.raises(NotImplementedError, match="NoisyBasis"): NoisyBasis() with pytest.raises(NotImplementedError, match="NoisyBasis"): NoisyBasis(zcirq, xcirq) def get_test_representation(): ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0))) noisy_xop = NoisyOperation( circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4)) ) noisy_zop = NoisyOperation( circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4)) ) decomp = OperationRepresentation( ideal, [noisy_xop, noisy_zop], [0.5, -0.5], ) return ideal, noisy_xop, noisy_zop, decomp def test_representation_simple(): ideal, noisy_xop, noisy_zop, decomp = get_test_representation() assert _equal(decomp.ideal, ideal) assert decomp.coeffs == [0.5, -0.5] assert np.allclose(decomp.distribution, np.array([0.5, 0.5])) assert np.isclose(decomp.norm, 1.0) assert isinstance(decomp.basis_expansion[0][0], float) assert set(decomp.noisy_operations) == {noisy_xop, noisy_zop} def test_representation_bad_type(): ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0))) noisy_xop = NoisyOperation( circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4)) ) with pytest.raises(TypeError, match="All elements of `noisy_operations`"): OperationRepresentation( ideal=ideal, noisy_operations=[0.1], coeffs=[0.1], ) with pytest.raises(TypeError, match="All elements of `coeffs` must"): OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop], coeffs=["x"], ) def test_representation_sample(): _, noisy_xop, noisy_zop, decomp = get_test_representation() for _ in range(10): noisy_op, sign, coeff = decomp.sample() assert sign in (-1, 1) assert coeff in (-0.5, 0.5) assert noisy_op in (noisy_xop, noisy_zop) case_one = noisy_op == noisy_xop and coeff == 0.5 case_two = noisy_op == noisy_zop and coeff == -0.5 assert case_one or case_two def test_representation_sample_seed(): _, noisy_xop, noisy_zop, decomp = get_test_representation() seed1 = np.random.RandomState(seed=1) seed2 = np.random.RandomState(seed=1) for _ in range(10): _, sign1, coeff1 = decomp.sample(random_state=seed1) _, sign2, coeff2 = decomp.sample(random_state=seed2) assert sign1 == sign2 assert np.isclose(coeff1, coeff2) def test_representation_sample_bad_seed_type(): _, _, _, decomp = get_test_representation() with pytest.raises(TypeError, match="should be of type"): decomp.sample(random_state="8") def test_representation_sample_zero_coefficient(): ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0))) noisy_xop = NoisyOperation( circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4)) ) noisy_zop = NoisyOperation( circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4)) ) decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop, noisy_zop], coeffs=[0.5, 0.0], # 0 term should never be sampled. ) random_state = np.random.RandomState(seed=1) for _ in range(500): noisy_op, sign, coeff = decomp.sample(random_state=random_state) assert sign == 1 assert coeff == 0.5 assert np.allclose( cirq.unitary(noisy_op.circuit), cirq.unitary(cirq.X), ) def test_print_cirq_operation_representation(): ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0))) noisy_xop = NoisyOperation( circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4)) ) noisy_zop = NoisyOperation( circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4)) ) # Positive first coefficient decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop, noisy_zop], coeffs=[0.5, 0.5], ) expected = r"0: ───H─── = 0.500*(0: ───X───)+0.500*(0: ───Z───)" assert str(decomp) == expected # Negative first coefficient decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop, noisy_zop], coeffs=[-0.5, 1.5], ) expected = r"0: ───H─── = -0.500*(0: ───X───)+1.500*(0: ───Z───)" assert str(decomp) == expected # Empty representation decomp = OperationRepresentation(ideal, [], []) expected = r"0: ───H─── = 0.000" assert str(decomp) == expected # Small coefficient approximation decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop, noisy_zop], coeffs=[1.00001, 0.00001], ) expected = r"0: ───H─── = 1.000*(0: ───X───)" assert str(decomp) == expected # Small coefficient approximation different position decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop, noisy_zop], coeffs=[0.00001, 1.00001], ) expected = r"0: ───H─── = 1.000*(0: ───Z───)" # Small coefficient approximation different position decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop], coeffs=[0.00001], ) expected = r"0: ───H─── = 0.000" assert str(decomp) == expected def test_print_operation_representation_two_qubits(): qreg = cirq.LineQubit.range(2) ideal = cirq.Circuit(cirq.CNOT(*qreg)) noisy_a = NoisyOperation( circuit=cirq.Circuit( cirq.H.on_each(qreg), cirq.CNOT(*qreg), cirq.H.on_each(qreg) ) ) noisy_b = NoisyOperation( circuit=cirq.Circuit( cirq.Z.on_each(qreg), cirq.CNOT(*qreg), cirq.Z.on_each(qreg), ) ) decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_a, noisy_b], coeffs=[0.5, 0.5], ) expected = f""" 0: ───@─── │ 1: ───X─── ={" "} 0.500 0: ───H───@───H─── │ 1: ───H───X───H─── +0.500 0: ───Z───@───Z─── │ 1: ───Z───X───Z───""" # Remove initial newline expected = expected[1:] assert str(decomp) == expected def test_print_operation_representation_two_qubits_neg(): qreg = cirq.LineQubit.range(2) ideal = cirq.Circuit(cirq.CNOT(*qreg)) noisy_a = NoisyOperation( circuit=cirq.Circuit( cirq.H.on_each(qreg[0]), cirq.CNOT(*qreg), cirq.H.on_each(qreg[1]) ) ) noisy_b = NoisyOperation(circuit=cirq.Circuit(cirq.Z.on_each(*qreg))) decomp = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_a, noisy_b], coeffs=[-0.5, 1.5], ) expected = f""" 0: ───@─── │ 1: ───X─── ={" "} -0.500 0: ───H───@─────── │ 1: ───────X───H─── +1.500 0: ───Z─── 1: ───Z───""" # Remove initial newline expected = expected[1:] assert str(decomp) == expected def test_equal_method_of_representations(): q = cirq.LineQubit(0) ideal = cirq.Circuit(cirq.H(q)) noisy_xop_a = NoisyOperation( circuit=cirq.Circuit(cirq.X(q)), channel_matrix=np.zeros(shape=(4, 4)), ) noisy_zop_a = NoisyOperation( circuit=cirq.Circuit(cirq.Z(q)), channel_matrix=np.zeros(shape=(4, 4)), ) rep_a = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_a, noisy_zop_a], coeffs=[0.5, 0.5], ) noisy_xop_b = NoisyOperation( circuit=cirq.Circuit(cirq.X(q)), channel_matrix=np.ones(shape=(4, 4)), ) noisy_zop_b = NoisyOperation( circuit=cirq.Circuit(cirq.Z(q)), channel_matrix=np.ones(shape=(4, 4)), ) rep_b = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_b, noisy_zop_b], coeffs=[0.5, 0.5], ) # Equal representation up to real superoperators assert rep_a == rep_b # Different ideal ideal_b = cirq.Circuit(cirq.X(q)) rep_b = OperationRepresentation( ideal=ideal_b, noisy_operations=[noisy_xop_b, noisy_zop_b], coeffs=[0.5, 0.5], ) assert rep_a != rep_b # Different type q_b = qiskit.QuantumRegister(1) ideal_b = qiskit.QuantumCircuit(q_b) ideal_b.x(q_b) noisy_opx = NoisyOperation(ideal_b) rep_b = OperationRepresentation( ideal=ideal_b, noisy_operations=[noisy_opx, noisy_opx], coeffs=[0.5, 0.5], ) assert rep_a != rep_b # Different length rep_b = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_b], coeffs=[0.5], ) assert rep_a != rep_b # Different operations noisy_diff = NoisyOperation(circuit=cirq.Circuit(cirq.H(q))) rep_b = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_b, noisy_diff], coeffs=[0.5, 0.5], ) assert rep_a != rep_b # Different coefficients rep_b = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_b, noisy_zop_b], coeffs=[0.7, 0.5], ) assert rep_a != rep_b # Different value of is_qubit_dependent rep_b = OperationRepresentation( ideal=ideal, noisy_operations=[noisy_xop_a, noisy_zop_a], coeffs=[0.5, 0.5], is_qubit_dependent=False, ) assert rep_a != rep_b def test_operation_representation_warnings(): with pytest.warns(UserWarning, match="different from 1"): OperationRepresentation( ideal=xcirq, noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)], coeffs=[0.5, 0.1], ) def test_different_qubits_error(): """Ideal operation and noisy operations must have equal qubits.""" with pytest.raises(ValueError, match="must act on the same qubits"): OperationRepresentation( ideal=cirq.Circuit(cirq.X(cirq.NamedQubit("a"))), noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)], coeffs=[0.5, 0.5], ) def test_different_length_error(): """The number of coefficients must be equal to the number of noisy operations. """ with pytest.raises(ValueError, match="must have equal length"): OperationRepresentation( ideal=cirq.Circuit(cirq.X(cirq.LineQubit(0))), noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)], coeffs=[0.5, 0.5, 0.4], )
https://github.com/CynthiaRios/quantum_orchestra
CynthiaRios
!(./jupyter_images/header.png "Header") #Will redo on quentin's computer tomorrow (today) pip install ipywidgets #conda install -c conda-forge ipywidgets from IPython.display import clear_output pip install music21 pip install pydub pip install RISE from shutil import copyfile from qiskit.visualization import plot_histogram from qiskit import Aer, QuantumCircuit, execute from qiskit import IBMQ import qiskit.tools.jupyter import os %qiskit_job_watcher from IPython.display import Audio import wave import numpy as np ## Button Display Imports (Needs installations mentioned above) from IPython.display import display, Markdown, clear_output # widget packages import ipywidgets as widgets from pydub import AudioSegment from music21 import * ![alt text](./jupyter_images/quantumgates.png "Quantum Gates") #Will redo on quentin's computer tomorrow (today) piano_input = [None] * 5 piano = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') piano5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([piano, piano2, piano3, piano4, piano5]) box guitar_input = [None] * 5 guitar = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') guitar5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([guitar, guitar2, guitar3, guitar4, guitar5]) box trumpet_input = [None] * 5 trumpet = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') trumpet5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([trumpet, trumpet2, trumpet3, trumpet4, trumpet5]) box bass_input = [None] * 5 bass = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass2 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass3 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass4 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') bass5 = widgets.Dropdown( options=['No Gate', 'X-Gate', 'Y-Gate', 'Z-Gate'], value='No Gate', description='Insert a :') box = widgets.VBox([bass, bass2, bass3, bass4, bass5]) box def GetGates(piano_input, guitar_input, bass_input, trumpet_input): if (piano.value == 'No Gate'): piano_input[0] = 'n' if (piano.value == 'X-Gate'): piano_input[0] = 'x' if (piano.value == 'Y-Gate'): piano_input[0] = 'y' if (piano.value == 'Z-Gate'): piano_input[0] = 'z' if (piano2.value == 'No Gate'): piano_input[1] = 'n' if (piano2.value == 'X-Gate'): piano_input[1] = 'x' if (piano2.value == 'Y-Gate'): piano_input[1] = 'y' if (piano2.value == 'Z-Gate'): piano_input[1] = 'z' if (piano3.value == 'No Gate'): piano_input[2] = 'n' if (piano3.value == 'X-Gate'): piano_input[2] = 'x' if (piano3.value == 'Y-Gate'): piano_input[2] = 'y' if (piano3.value == 'Z-Gate'): piano_input[2] = 'z' if (piano4.value == 'No Gate'): piano_input[3] = 'n' if (piano4.value == 'X-Gate'): piano_input[3] = 'x' if (piano4.value == 'Y-Gate'): piano_input[3] = 'y' if (piano4.value == 'Z-Gate'): piano_input[3] = 'z' if (piano5.value == 'No Gate'): piano_input[4] = 'n' if (piano5.value == 'X-Gate'): piano_input[4] = 'x' if (piano5.value == 'Y-Gate'): piano_input[4] = 'y' if (piano5.value == 'Z-Gate'): piano_input[4] = 'z' if (guitar.value == 'No Gate'): guitar_input[0] = 'n' if (guitar.value == 'X-Gate'): guitar_input[0] = 'x' if (guitar.value == 'Y-Gate'): guitar_input[0] = 'y' if (guitar.value == 'Z-Gate'): guitar_input[0] = 'z' if (guitar2.value == 'No Gate'): guitar_input[1] = 'n' if (guitar2.value == 'X-Gate'): guitar_input[1] = 'x' if (guitar2.value == 'Y-Gate'): guitar_input[1] = 'y' if (guitar2.value == 'Z-Gate'): guitar_input[1] = 'z' if (guitar3.value == 'No Gate'): guitar_input[2] = 'n' if (guitar3.value == 'X-Gate'): guitar_input[2] = 'x' if (guitar3.value == 'Y-Gate'): guitar_input[2] = 'y' if (guitar3.value == 'Z-Gate'): guitar_input[2] = 'z' if (guitar4.value == 'No Gate'): guitar_input[3] = 'n' if (guitar4.value == 'X-Gate'): guitar_input[3] = 'x' if (guitar4.value == 'Y-Gate'): guitar_input[3] = 'y' if (guitar4.value == 'Z-Gate'): guitar_input[3] = 'z' if (guitar5.value == 'No Gate'): guitar_input[4] = 'n' if (guitar5.value == 'X-Gate'): guitar_input[4] = 'x' if (guitar5.value == 'Y-Gate'): guitar_input[4] = 'y' if (guitar5.value == 'Z-Gate'): guitar_input[4] = 'z' if (bass.value == 'No Gate'): bass_input[0] = 'n' if (bass.value == 'X-Gate'): bass_input[0] = 'x' if (bass.value == 'Y-Gate'): bass_input[0] = 'y' if (bass.value == 'Z-Gate'): bass_input[0] = 'z' if (bass2.value == 'No Gate'): bass_input[1] = 'n' if (bass2.value == 'X-Gate'): bass_input[1] = 'x' if (bass2.value == 'Y-Gate'): bass_input[1] = 'y' if (bass2.value == 'Z-Gate'): bass_input[1] = 'z' if (bass3.value == 'No Gate'): bass_input[2] = 'n' if (bass3.value == 'X-Gate'): bass_input[2] = 'x' if (bass3.value == 'Y-Gate'): bass_input[2] = 'y' if (bass3.value == 'Z-Gate'): bass_input[2] = 'z' if (bass4.value == 'No Gate'): bass_input[3] = 'n' if (bass4.value == 'X-Gate'): bass_input[3] = 'x' if (bass4.value == 'Y-Gate'): bass_input[3] = 'y' if (bass4.value == 'Z-Gate'): bass_input[3] = 'z' if (bass5.value == 'No Gate'): bass_input[4] = 'n' if (bass5.value == 'X-Gate'): bass_input[4] = 'x' if (bass5.value == 'Y-Gate'): bass_input[4] = 'y' if (bass5.value == 'Z-Gate'): bass_input[4] = 'z' if (trumpet.value == 'No Gate'): trumpet_input[0] = 'n' if (trumpet.value == 'X-Gate'): trumpet_input[0] = 'x' if (trumpet.value == 'Y-Gate'): trumpet_input[0] = 'y' if (trumpet.value == 'Z-Gate'): trumpet_input[0] = 'z' if (trumpet2.value == 'No Gate'): trumpet_input[1] = 'n' if (trumpet2.value == 'X-Gate'): trumpet_input[1] = 'x' if (trumpet2.value == 'Y-Gate'): trumpet_input[1] = 'y' if (trumpet2.value == 'Z-Gate'): trumpet_input[1] = 'z' if (trumpet3.value == 'No Gate'): trumpet_input[2] = 'n' if (trumpet3.value == 'X-Gate'): trumpet_input[2] = 'x' if (trumpet3.value == 'Y-Gate'): trumpet_input[2] = 'y' if (trumpet3.value == 'Z-Gate'): trumpet_input[2] = 'z' if (trumpet4.value == 'No Gate'): trumpet_input[3] = 'n' if (trumpet4.value == 'X-Gate'): trumpet_input[3] = 'x' if (trumpet4.value == 'Y-Gate'): trumpet_input[3] = 'y' if (trumpet4.value == 'Z-Gate'): trumpet_input[3] = 'z' if (trumpet5.value == 'No Gate'): trumpet_input[4] = 'n' if (trumpet5.value == 'X-Gate'): trumpet_input[4] = 'x' if (trumpet5.value == 'Y-Gate'): trumpet_input[4] = 'y' if (trumpet5.value == 'Z-Gate'): trumpet_input[4] = 'z' return (piano_input, guitar_input, bass_input, trumpet_input) piano_input, guitar_input, bass_input, trumpet_input = GetGates(piano_input, guitar_input, bass_input, trumpet_input) from qiskit.test.mock import FakeVigo fake_vigo = FakeVigo() #minimum user input will just be for them to fill out the create quantum circuit function inthe backend n = 5 #number of gates s = 1024 piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] def CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input): cct1 = QuantumCircuit(1,1) cct2 = QuantumCircuit(1,1) cct3 = QuantumCircuit(1,1) cct4 = QuantumCircuit(1,1) piano_states = [] guitar_states = [] bass_states = [] trumpet_states = [] for i in range(n): cct1.h(0) cct1.barrier() if piano_input[i-1] == 'x': cct1.x(0) if piano_input[i-1] == 'y': cct1.y(0) if piano_input[i-1] == 'z': cct1.z(0) cct1.barrier() cct1.measure(0,0) #plot_histogram(c1) cct2.h(0) cct2.barrier() if guitar_input[i-1] == 'x': cct2.x(0) if guitar_input[i-1] == 'y': cct2.y(0) if guitar_input[i-1] == 'z': cct2.z(0) cct2.barrier() cct2.measure(0,0) #plot_histogram(c2) cct3.h(0) cct3.barrier() if bass_input[i-1] == 'x': cct3.x(0) if bass_input[i-1] == 'y': cct3.y(0) if bass_input[i-1] == 'z': cct3.z(0) cct3.barrier() cct3.measure(0,0) #plot_histogram(c3) cct4.h(0) cct4.barrier() if trumpet_input[i-1] == 'x': cct4.x(0) if trumpet_input[i-1] == 'y': cct4.y(0) if trumpet_input[i-1] == 'z': cct4.z(0) cct4.barrier() cct4.measure(0,0) c1 = execute(cct1, fake_vigo, shots=s).result().get_counts() piano_states.append(c1) c2 = execute(cct2, fake_vigo, shots=s).result().get_counts() guitar_states.append(c2) c3 = execute(cct3, fake_vigo, shots=s).result().get_counts() bass_states.append(c3) c4 = execute(cct4, fake_vigo, shots=s).result().get_counts() trumpet_states.append(c4) return c1,c2,c3,c4,piano_states, guitar_states, bass_states, trumpet_states, cct1, cct2, cct3, cct4 c1,c2,c3,c4,piano_states, guitar_states, bass_states, trumpet_states, cct1, cct2,cct3,cct4 = CreateQuantumCircuit(piano_input, guitar_input, bass_input, trumpet_input) print(trumpet_states) def ins(states,s): res = [] for key in states[0].keys(): res.append(states[0][key]/s) return res s = 1024 piano_prob = ins(piano_states,s) guitar_prob = ins(guitar_states,s) bass_prob = ins(bass_states,s) trumpet_prob = ins(trumpet_states,s) print(trumpet_prob) def MusicalTransformation(probs): tune_array=[] for i in range(n+1): if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.4 and probs[1] < 0.45)): tune_array.append('c') tune_array.append('g') tune_array.append('e') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.45 and probs[1] < 0.5)): tune_array.append('c') tune_array.append('f') tune_array.append('g') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.5 and probs[1] < 0.55)): tune_array.append('d') tune_array.append('f') tune_array.append('a') if((probs[0] > 0.4 and probs[0] < 0.5) and (probs[1] > 0.55 and probs[1] < 0.6)): tune_array.append('f') tune_array.append('a') tune_array.append('c') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.4 and probs[1] < 0.45)): tune_array.append('g') tune_array.append('b') tune_array.append('d') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.45 and probs[1] < 0.5)): tune_array.append('d') tune_array.append('f') tune_array.append('a') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.5 and probs[1] < 0.55)): tune_array.append('e') tune_array.append('g') tune_array.append('b') if((probs[0] > 0.5 and probs[0] < 0.6) and (probs[1] > 0.55 and probs[1] < 0.6)): tune_array.append('a') tune_array.append('c') tune_array.append('b') if(probs[0] < 0.4 or probs[0] > 0.6 or probs[1] < 0.4 or probs[1] > 0.6): tune_array.append('n') tune_array.append('n') tune_array.append('n') return tune_array tune_array_piano = MusicalTransformation(piano_prob) tune_array_guitar = MusicalTransformation(guitar_prob) tune_array_bass = MusicalTransformation(bass_prob) tune_array_trumpet = MusicalTransformation(trumpet_prob) def PlayPianoTune(character, songs): if character == 'a': sound_file = "./Audio/Piano/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Piano/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Piano/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Piano/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Piano/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Piano/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Piano/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayGuitarTune(character, songs): if character == 'a': sound_file = "./Audio/Guitar/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Guitar/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Guitar/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Guitar/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Guitar/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Guitar/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Guitar/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayBassTune(character, songs): if character == 'a': sound_file = "./Audio/Bass/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Bass/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Bass/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Bass/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Bass/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Bass/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Bass/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs def PlayTrumpetTune(character, songs): if character == 'a': sound_file = "./Audio/Trumpet/1.wav" songs.append(sound_file) if character == 'b': sound_file = "./Audio/Trumpet/2.wav" songs.append(sound_file) if character == 'c': sound_file = "./Audio/Trumpet/3.wav" songs.append(sound_file) if character == 'd': sound_file = "./Audio/Trumpet/4.wav" songs.append(sound_file) if character == 'e': sound_file = "./Audio/Trumpet/5.wav" songs.append(sound_file) if character == 'f': sound_file = "./Audio/Trumpet/6.wav" songs.append(sound_file) if character == 'g': sound_file = "./Audio/Trumpet/7.wav" songs.append(sound_file) if character == 'n': sound_file = "./Audio/blank.wav" songs.append(sound_file) return songs piano_song = [] for i in range(len(tune_array_piano)): character = tune_array_piano[i-1] piano_song = PlayPianoTune(character, piano_song) os.remove("./pianosounds.wav") copyfile('./Audio/blank.wav','./pianosounds.wav') for i in range(len(tune_array_piano)): infiles = [piano_song[i-1], "pianosounds.wav"] outfile = "pianosounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() guitar_song = [] for i in range(len(tune_array_guitar)): character = tune_array_piano[i-1] guitar_song = PlayGuitarTune(character, guitar_song) os.remove("./guitarsounds.wav") copyfile('./Audio/blank.wav','./guitarsounds.wav') for i in range(len(tune_array_guitar)): infiles = [guitar_song[i-1], "guitarsounds.wav"] outfile = "guitarsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() bass_song = [] for i in range(len(tune_array_bass)): character = tune_array_bass[i-1] bass_song = PlayBassTune(character, bass_song) os.remove("./basssounds.wav") copyfile('./Audio/blank.wav','./basssounds.wav') for i in range(len(tune_array_bass)): infiles = [bass_song[i-1], "basssounds.wav"] outfile = "basssounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() trumpet_song = [] for i in range(len(tune_array_trumpet)): character = tune_array_trumpet[i-1] trumpet_song = PlayTrumpetTune(character, trumpet_song) os.remove("./trumpetsounds.wav") copyfile('./Audio/blank.wav','./trumpetsounds.wav') for i in range(len(tune_array_trumpet)): infiles = [trumpet_song[i-1], "trumpetsounds.wav"] outfile = "trumpetsounds.wav" data= [] for infile in infiles: w = wave.open(infile, 'rb') data.append( [w.getparams(), w.readframes(w.getnframes())] ) w.close() output = wave.open(outfile, 'wb') output.setparams(data[0][0]) for i in range(len(data)): output.writeframes(data[i][1]) output.close() sound1 = AudioSegment.from_file("./trumpetsounds.wav") sound2 = AudioSegment.from_file("./basssounds.wav") combined = sound1.overlay(sound2) combined.export("./combined.wav", format='wav') sound3 = AudioSegment.from_file("./guitarsounds.wav") sound4 = AudioSegment.from_file("./pianosounds.wav") combined2 = sound3.overlay(sound4) combined2.export("./combined2.wav", format='wav') sound5 = AudioSegment.from_file("./combined.wav") sound6 = AudioSegment.from_file("./combined2.wav") output_song = sound5.overlay(sound6) output_song.export("./output_song.wav", format='wav') sound_file = "./output_song.wav" Audio(sound_file, autoplay=True) print(tune_array_piano) a = 64 b = 65 c = 66 d = 67 e = 68 f = 69 g = 70 print(tune_array_piano[0]) streamPiano = stream.Stream() instrumentPiano = [] for i in range(18): instrumentPiano.append(note.Note(tune_array_piano[i])) streamPiano.append(instrumentPiano) streamPiano.show() a = 57 b = 58 c = 59 d = 60 e = 61 f = 62 g = 63 print(tune_array_guitar) streamGuitar = stream.Stream() instrumentGuitar = [] for i in range(18): instrumentGuitar.append(note.Note(tune_array_guitar[i])) streamGuitar.append(instrumentGuitar) streamGuitar.show() a = 50 b = 51 c = 52 d = 53 e = 54 f = 55 g = 56 print(tune_array_trumpet) streamTrumpet = stream.Stream() streamBass = stream.Stream() instrumentTrumpet = [] for i in range(18): instrumentTrumpet.append(note.Note(tune_array_trumpet[i])) streamTrumpet.append(instrumentTrumpet) streamTrumpet.show() a = 43 b = 44 c = 45 d = 46 e = 47 f = 48 g = 49 print(tune_array_bass) streamBass = stream.Stream() instrumentBass = [] for i in range(18): instrumentBass.append(note.Note(tune_array_bass[i])) streamBass.append(instrumentBass) streamBass.show() excerpt = streamPiano.measures(1, 4) excerpt.show() streamPiano.getElementsByClass('Measure').insert(0.0, instrument.Piano()) streamGuitar.getElementsByClass('Measure').insert(1.0, instrument.Guitar()) streamTrumpet.getElementsByClass('Measure').insert(2.0, instrument.Trumpet()) streamBass.getElementsByClass('Measure').insert(3.0, instrument.Bass()) s = stream.Score() s.insert(0, streamPiano) s.insert(0, streamGuitar) s.insert(0, streamTrumpet) s.insert(0, streamBass) s.show() s.show('musicxml') #this show on musescore
https://github.com/qiskit-community/qiskit-cold-atom
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Spin circuit solver tests""" import numpy as np from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit_nature.second_q.operators import FermionicOp, SpinOp from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver from qiskit_cold_atom.exceptions import QiskitColdAtomError class TestSpinCircuitSolver(QiskitTestCase): """class to test the SpinCircuitSolver class.""" def setUp(self): super().setUp() # Set up the simulator self.solver = SpinCircuitSolver(spin=3 / 2) def test_spin_solver_initialization(self): """test constructor of SpinCircuitSolver""" with self.assertRaises(QiskitColdAtomError): SpinCircuitSolver(spin=2 / 3) def test_get_initial_state(self): """test initialization of the state for the simulation""" circ = QuantumCircuit(1) init_state = self.solver.get_initial_state(circ) target = np.array([1, 0, 0, 0]) self.assertTrue(np.all(init_state.toarray().T == target)) def test_embed_operator(self): """test embedding of an operator""" fer_op = FermionicOp({"+_0 -_1": 1}, num_spin_orbitals=2) # define a spin operator that has terms with different prefactors, support and power spin_op = SpinOp( {"X_0 X_1": 1, "Y_0 X_1": 1j, "X_0 Y_1": -1j, "Y_0 Y_1": 1}, num_spins=2 ) + 2 * SpinOp({"X_0^2": 1}, num_spins=2) num_wires = 4 qargs = [1, 3] qargs_wrong = [0, 1, 3] with self.subTest("check operator type"): with self.assertRaises(QiskitColdAtomError): self.solver._embed_operator(fer_op, num_wires, qargs) with self.subTest("check operator wiring"): with self.assertRaises(QiskitColdAtomError): self.solver._embed_operator(spin_op, num_wires, qargs_wrong) with self.subTest("operator embedding"): embedded_op = self.solver._embed_operator(spin_op, num_wires, qargs) target_op = SpinOp( {"X_1 X_3": 1, "Y_1 X_3": 1j, "X_1 Y_3": -1j, "Y_1 Y_3": 1, "X_1^2": 2.0}, spin=3 / 2, num_spins=4, ) self.assertTrue( np.allclose(embedded_op.simplify().to_matrix(), target_op.simplify().to_matrix()) ) def test_preprocess_circuit(self): """test whether preprocessing of the circuit correctly sets the dimension""" circ = QuantumCircuit(2) self.solver.preprocess_circuit(circ) self.assertEqual(self.solver.dim, 4**2) def test_draw_shots(self): """test drawing of the shots from a measurement distribution""" n_spins = 5 circ = QuantumCircuit(n_spins) circ.rly(np.pi / 2, [3]) self.solver.preprocess_circuit(circ) dim = int((2 * self.solver.spin + 1) ** n_spins) with self.subTest("check missing shot number"): # error because the number of shots is not specified with self.assertRaises(QiskitColdAtomError): self.solver.draw_shots(np.ones(dim) / dim) self.solver.shots = 3 with self.subTest("check match of dimensions"): # error because there is a mismatch in the dimension with self.assertRaises(QiskitColdAtomError): self.solver.draw_shots(np.ones(dim - 1) / (dim - 1)) with self.subTest("formatting of measurement outcomes"): meas_distr = np.abs(self.solver(circ)["statevector"]) ** 2 self.solver.seed = 45 outcomes = self.solver.draw_shots(meas_distr) # Note the second index changing with the gate being applied to wire [3] of 5 self.assertEqual(outcomes, ["0 3 0 0 0", "0 2 0 0 0", "0 1 0 0 0"]) def test_to_operators(self): """test the to_operators method inherited form BaseCircuitSolver""" test_circ = QuantumCircuit(2) test_circ.rlx(0.5, [0, 1]) test_circ.rlz2(0.25, 1) test_circ.measure_all() with self.subTest("test ignore barriers"): self.solver.ignore_barriers = False with self.assertRaises(NotImplementedError): self.solver.to_operators(test_circ) self.solver.ignore_barriers = True with self.subTest("check for gate generators"): qubit_circ = QuantumCircuit(1) qubit_circ.h(0) with self.assertRaises(QiskitColdAtomError): self.solver.to_operators(qubit_circ) with self.subTest("gate after previous measurement instruction"): meas_circ = QuantumCircuit(2) meas_circ.measure_all() meas_circ.rlx(0.5, 0) with self.assertRaises(QiskitColdAtomError): self.solver.to_operators(meas_circ) with self.subTest("check returned operators"): operators = self.solver.to_operators(test_circ) target = [ SpinOp({"X_0": (0.5 + 0j)}, spin=3 / 2, num_spins=2), SpinOp({"X_1": (0.5 + 0j)}, spin=3 / 2, num_spins=2), SpinOp({"Z_1^2": (0.25 + 0j)}, spin=3 / 2, num_spins=2), ] for i, op in enumerate(operators): self.assertTrue( np.allclose(op.simplify().to_matrix(), target[i].simplify().to_matrix()) ) def test_call_method(self): """test the call method inherited from BaseCircuitSolver that simulates a circuit""" test_circ = QuantumCircuit(1) test_circ.rlx(np.pi / 2, 0) test_circ.measure_all() with self.subTest("running the circuit"): self.solver.shots = 5 self.solver.seed = 45 simulation = self.solver(test_circ) self.assertEqual(simulation["memory"], ["3", "2", "1", "0", "1"]) self.assertEqual(simulation["counts"], {"0": 1, "1": 2, "2": 1, "3": 1}) self.assertTrue( np.allclose( simulation["statevector"], np.array( [ np.sqrt(1 / 8), -1j * np.sqrt(3 / 8), -np.sqrt(3 / 8), 1j * np.sqrt(1 / 8), ] ), ) ) self.assertTrue( np.allclose( simulation["unitary"], np.array( [ [ np.sqrt(1 / 8), -1j * np.sqrt(3 / 8), -np.sqrt(3 / 8), 1j * np.sqrt(1 / 8), ], [ -1j * np.sqrt(3 / 8), -np.sqrt(1 / 8), -1j * np.sqrt(1 / 8), -np.sqrt(3 / 8), ], [ -np.sqrt(3 / 8), -1j * np.sqrt(1 / 8), -np.sqrt(1 / 8), -1j * np.sqrt(3 / 8), ], [ 1j * np.sqrt(1 / 8), -np.sqrt(3 / 8), -1j * np.sqrt(3 / 8), np.sqrt(1 / 8), ], ] ), ) ) with self.subTest("check for maximum dimension"): self.solver.max_dimension = 3 with self.assertRaises(QiskitColdAtomError): self.solver(test_circ) self.solver.max_dimension = 100 with self.subTest("check if shots are specified"): self.solver.shots = None simulation = self.solver(test_circ) self.assertEqual(simulation["memory"], []) self.assertEqual(simulation["counts"], {}) self.solver.shots = 5 multiple_wire_circ = QuantumCircuit(2) multiple_wire_circ.rlx(np.pi / 2, [0]) multiple_wire_circ.rlz(-np.pi / 2, [0, 1]) with self.subTest("formatting of multiple wires"): self.solver.seed = 45 simulation = self.solver(multiple_wire_circ) self.assertTrue(simulation["memory"], ["0 3", "0 2", "0 1", "0 0", "0 1"]) self.assertTrue(simulation["counts"], {"0 2": 1, "0 0": 1, "0 3": 1, "0 1": 2}) with self.subTest("check equivalence to qubits for spin-1/2"): from qiskit_aer import AerSimulator qubit_circ = QuantumCircuit(2) qubit_circ.rx(np.pi / 2, [0]) qubit_circ.rz(-np.pi / 2, [0, 1]) qubit_circ.save_unitary() qubit_backend = AerSimulator() job = qubit_backend.run(qubit_circ) qubit_unitary = job.result().get_unitary() spin_half_solver = SpinCircuitSolver(spin=1 / 2) simulation = spin_half_solver(multiple_wire_circ) spin_unitary = simulation["unitary"] # Switch some axes in the spin simulator unitary because the basis of qiskit_nature.SpinOp # uses an ordering of the states (00, 10, 01, 11) that is different from qiskit Aer which # uses (00, 01, 10, 11) spin_unitary[[1, 2]] = spin_unitary[[2, 1]] spin_unitary[:, [1, 2]] = spin_unitary[:, [2, 1]] self.assertTrue(np.allclose(qubit_unitary, spin_unitary))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spin_orbitals = 10 from qiskit_nature.second_q.circuit.library import UCCSD ansatz = UCCSD() ansatz.num_spatial_orbitals = 5 from qiskit_nature.circuit.library import UCC, UVCC ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None) uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None) from qiskit_nature.second_q.circuit.library import UCC, UVCC ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None) uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None) from qiskit_nature.circuit.library import HartreeFock, VSCF from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper hf = HartreeFock( num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper()) ) vscf = VSCF(num_modals=[2, 2]) from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter hf = HartreeFock() hf.num_spatial_orbitals = 2 hf.num_particles = (1, 1) hf.qubit_converter = QubitConverter(JordanWignerMapper()) vscf = VSCF() vscf.num_modals = [2, 2] from qiskit.providers.basicaer import BasicAer from qiskit.utils import QuantumInstance from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator")) vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory from qiskit_nature.algorithms.excited_states_solvers import QEOM from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper vqe_factory = VQEUCCFactory() converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver) from qiskit.algorithms.optimizers import SLSQP from qiskit.primitives import Estimator from qiskit_nature.second_q.circuit.library import UCCSD from qiskit_nature.second_q.algorithms.ground_state_solvers import ( GroundStateEigensolver, VQEUCCFactory, ) from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter estimator = Estimator() ansatz = UCCSD() optimizer = SLSQP() vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer) converter = QubitConverter(JordanWignerMapper()) ground_state_solver = GroundStateEigensolver(converter, vqe_factory) qeom = QEOM(ground_state_solver, estimator) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) # You can reverse the order of the qubits. from qiskit.quantum_info import DensityMatrix qc = QuantumCircuit(2) qc.h([0, 1]) qc.t(1) qc.s(0) qc.cx(0,1) matrix = DensityMatrix(qc) plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
rodneyosodo
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas_profiling as pp from sklearn.datasets import load_wine, load_iris %matplotlib inline # Constants CLEAN_DATA_PATH = "../../Data/Processed/iris_csv.csv" raw_data = load_iris() features = pd.DataFrame(data=raw_data['data'],columns=raw_data['feature_names']) data = features data['target']=raw_data['target'] data['class']=data['target'].map(lambda ind: raw_data['target_names'][ind]) data.head() data.shape data.columns print(raw_data['DESCR']) data.info() data.describe() def check_unique(df): """" Checks the unique value in each column :param df: The dataframe """ for col in df.columns: unique = df[col].unique() print("Column: {} has {} unique values\n".format(col, unique)) check_unique(data) fig = plt.figure() sns.countplot(x="target", data=data, palette="gist_rainbow_r") plt.xlabel("Classes(0 = setosa, 1 = versicolor, 2 = verginica)") plt.title("Target distribution") plt.show() data = data[data['class'] != 'virginica'] data.duplicated().sum() data.drop_duplicates(inplace=True) data.drop('target', axis=1).corrwith(data['target']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target") pp.ProfileReport(df=data, dark_mode=True, explorative=True) data data = data[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)', 'target']] data.to_csv(CLEAN_DATA_PATH, index=False)
https://github.com/daimurat/qiskit-implementation
daimurat
from qiskit import Aer from qiskit.circuit.library import QFT from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.quantum_info import state_fidelity from qiskit.aqua.algorithms import HHL, NumPyLSsolver from qiskit.aqua.components.eigs import EigsQPE from qiskit.aqua.components.reciprocals import LookupRotation from qiskit.aqua.operators import MatrixOperator from qiskit.aqua.components.initial_states import Custom import numpy as np def create_eigs(matrix, num_ancillae, num_time_slices, negative_evals): ne_qfts = [None, None] if negative_evals: num_ancillae += 1 # The QFT and IQFT circuits for handling negative eigenvalues ne_qfts = [QFT(num_ancillae - 1), QFT(num_ancillae - 1).inverse()] """ Specifically, this class is based on PhaseEstimationCircuit with no measurements and has additional handling of negative eigenvalues """ return EigsQPE(MatrixOperator(matrix=matrix), QFT(num_ancillae).inverse(), num_time_slices=num_time_slices, num_ancillae=num_ancillae, expansion_mode='suzuki', expansion_order=2, evo_time=None, # This is t, can set to: np.pi*3/4 negative_evals=negative_evals, ne_qfts=ne_qfts) # 信頼度 def fidelity(hhl, ref): solution_hhl_normed = hhl / np.linalg.norm(hhl) solution_ref_normed = ref / np.linalg.norm(ref) fidelity = state_fidelity(solution_hhl_normed, solution_ref_normed) print("Fidelity:\t\t %f" % fidelity) matrix = [[1, -1/3], [-1/3, 1]] vector = [1, 0] orig_size = len(vector) # 行列Aがハミルトニアンでない場合はtrancate_hermitian利用 matrix, vector, truncate_powerdim, truncate_hermitian = HHL.matrix_resize(matrix, vector) # Initialize eigenvalue finding module eigs = create_eigs(matrix, 3, 50, False) num_q, num_a = eigs.get_register_sizes() # Initialize initial state module init_state = Custom(num_q, state_vector=vector) # Initialize reciprocal rotation module reci = LookupRotation(negative_evals=eigs._negative_evals, evo_time=eigs._evo_time) """ Args: matrix: The input matrix of linear system of equations vector: The input vector of linear system of equations truncate_powerdim: Flag indicating expansion to 2**n matrix to be truncated truncate_hermitian: Flag indicating expansion to hermitian matrix to be truncated eigs: The eigenvalue estimation instance init_state: The initial quantum state preparation reciprocal: The eigenvalue reciprocal and controlled rotation instance num_q: Number of qubits required for the matrix Operator instance num_a: Number of ancillary qubits for Eigenvalues instance orig_size: The original dimension of the problem (if truncate_powerdim) quantum_instance: Quantum Instance or Backend """ algo = HHL(matrix, vector, truncate_powerdim, truncate_hermitian, eigs, init_state, reci, num_q, num_a, orig_size) result = algo.run(QuantumInstance(Aer.get_backend('statevector_simulator'))) print("Solution:\t\t", np.round(result['solution'], 5)) result_ref = NumPyLSsolver(matrix, vector).run() print("Classical Solution:\t", np.round(result_ref['solution'], 5)) print("Probability:\t\t %f" % result['probability_result']) fidelity(result['solution'], result_ref['solution']) algo = HHL(matrix, vector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.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)) ghz.draw(output='mpl')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # 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. """Utils for reading a user preference config files.""" import configparser import os from qiskit import exceptions DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"), '.qiskit', 'settings.conf') class UserConfig: """Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl """ def __init__(self, filename=None): """Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used. """ if filename is None: self.filename = DEFAULT_FILENAME else: self.filename = filename self.settings = {} self.config_parser = configparser.ConfigParser() def read_config_file(self): """Read config file and parse the contents into the settings attr.""" if not os.path.isfile(self.filename): return self.config_parser.read(self.filename) if 'default' in self.config_parser.sections(): circuit_drawer = self.config_parser.get('default', 'circuit_drawer') if circuit_drawer: if circuit_drawer not in ['text', 'mpl', 'latex', 'latex_source']: raise exceptions.QiskitUserConfigError( "%s is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', or 'latex_source'" % circuit_drawer) self.settings['circuit_drawer'] = circuit_drawer def get_config(): """Read the config file from the default location or env var It will read a config file at either the default location ~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var. It will return the parsed settings dict from the parsed config file. Returns: dict: The settings dict from the parsed config file. """ filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME) if not os.path.isfile(filename): return {} user_config = UserConfig(filename) user_config.read_config_file() return user_config.settings
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
alpine-quantum-technologies
# This code is part of Qiskit. # # (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json import math import uuid from unittest import mock import httpx import pydantic as pdt import pytest from polyfactory.factories.pydantic_factory import ModelFactory from pytest_httpx import HTTPXMock from qiskit import QuantumCircuit from qiskit.providers.exceptions import JobTimeoutError from qiskit_aqt_provider import api_models from qiskit_aqt_provider.aqt_job import AQTJob from qiskit_aqt_provider.aqt_options import AQTOptions from qiskit_aqt_provider.aqt_resource import AQTResource from qiskit_aqt_provider.test.circuits import assert_circuits_equal, empty_circuit from qiskit_aqt_provider.test.fixtures import MockSimulator from qiskit_aqt_provider.test.resources import DummyResource, TestResource from qiskit_aqt_provider.versions import USER_AGENT class OptionsFactory(ModelFactory[AQTOptions]): __model__ = AQTOptions query_timeout_seconds = 10.0 def test_options_set_query_timeout(offline_simulator_no_noise: AQTResource) -> None: """Set the query timeout for job status queries with different values.""" backend = offline_simulator_no_noise # doesn't work with str with pytest.raises(pdt.ValidationError): backend.options.update_options(query_timeout_seconds="abc") # works with integers backend.options.update_options(query_timeout_seconds=123) assert backend.options.query_timeout_seconds == 123 # works with floats backend.options.update_options(query_timeout_seconds=123.45) assert backend.options.query_timeout_seconds == 123.45 # works with None (no timeout) backend.options.update_options(query_timeout_seconds=None) assert backend.options.query_timeout_seconds is None def test_options_set_query_period(offline_simulator_no_noise: AQTResource) -> None: """Set the query period for job status queries with different values.""" backend = offline_simulator_no_noise # works with integers backend.options.update_options(query_period_seconds=123) assert backend.options.query_period_seconds == 123 # works with floats backend.options.update_options(query_period_seconds=123.45) assert backend.options.query_period_seconds == 123.45 # doesn't work with None with pytest.raises(pdt.ValidationError): backend.options.update_options(query_period_seconds=None) # doesn't work with str with pytest.raises(pdt.ValidationError): backend.options.update_options(query_period_seconds="abc") def test_query_timeout_propagation() -> None: """Check that the query timeout is properly propagated from the backend options to the job result polling loop. Acquire a resource with 10s processing time, but set the job result timeout to 1s. Check that calling `result()` on the job handle fails with a timeout error. """ response_delay = 10.0 timeout = 1.0 assert timeout < response_delay backend = TestResource(min_running_duration=response_delay) backend.options.update_options(query_timeout_seconds=timeout, query_period_seconds=0.5) qc = QuantumCircuit(1) qc.rx(3.14, 0) job = backend.run(qc) with pytest.raises(JobTimeoutError): job.result() def test_query_period_propagation() -> None: """Check that the query wait duration is properly propagated from the backend options to the job result polling loop. Set the polling period (much) shorter than the backend's processing time. Check that the backend is polled the calculated number of times. """ response_delay = 2.0 period_seconds = 0.5 timeout_seconds = 3.0 assert timeout_seconds > response_delay # won't time out backend = TestResource(min_running_duration=response_delay) backend.options.update_options( query_timeout_seconds=timeout_seconds, query_period_seconds=period_seconds ) qc = QuantumCircuit(1) qc.rx(3.14, 0) qc.measure_all() job = backend.run(qc) with mock.patch.object(AQTJob, "status", wraps=job.status) as mocked_status: job.result() lower_bound = math.floor(response_delay / period_seconds) upper_bound = math.ceil(response_delay / period_seconds) + 1 assert lower_bound <= mocked_status.call_count <= upper_bound def test_run_options_propagation(offline_simulator_no_noise: MockSimulator) -> None: """Check that options passed to AQTResource.run are propagated to the corresponding job.""" default = offline_simulator_no_noise.options.copy() while True: overrides = OptionsFactory.build() if overrides != default: break qc = QuantumCircuit(1) qc.measure_all() # don't submit the circuit to the simulator with mock.patch.object(AQTJob, "submit") as mocked_submit: job = offline_simulator_no_noise.run(qc, **overrides.dict()) assert job.options == overrides mocked_submit.assert_called_once() def test_run_options_unknown(offline_simulator_no_noise: MockSimulator) -> None: """Check that AQTResource.run accepts but warns about unknown options.""" default = offline_simulator_no_noise.options.copy() overrides = {"shots": 123, "unknown_option": True} assert set(overrides) - set(default) == {"unknown_option"} qc = QuantumCircuit(1) qc.measure_all() with mock.patch.object(AQTJob, "submit") as mocked_submit: with pytest.warns(UserWarning, match="not used"): job = offline_simulator_no_noise.run(qc, **overrides) assert job.options.shots == 123 mocked_submit.assert_called_once() def test_run_options_invalid(offline_simulator_no_noise: MockSimulator) -> None: """Check that AQTResource.run reject valid option names with invalid values.""" qc = QuantumCircuit(1) qc.measure_all() with pytest.raises(pdt.ValidationError, match="shots"): offline_simulator_no_noise.run(qc, shots=-123) def test_double_job_submission(offline_simulator_no_noise: MockSimulator) -> None: """Check that attempting to re-submit a job raises a RuntimeError.""" qc = QuantumCircuit(1) qc.r(3.14, 0.0, 0) qc.measure_all() # AQTResource.run submits the job job = offline_simulator_no_noise.run(qc) with pytest.raises(RuntimeError, match=f"{job.job_id()}"): job.submit() # Check that the job was actually submitted ((submitted_circuit,),) = offline_simulator_no_noise.submitted_circuits assert_circuits_equal(submitted_circuit, qc) def test_offline_simulator_invalid_job_id(offline_simulator_no_noise: MockSimulator) -> None: """Check that the offline simulator raises UnknownJobError if the job id passed to `result()` is invalid. """ qc = QuantumCircuit(1) qc.measure_all() job = offline_simulator_no_noise.run([qc], shots=1) job_id = uuid.UUID(hex=job.job_id()) invalid_job_id = uuid.uuid4() assert invalid_job_id != job_id with pytest.raises(api_models.UnknownJobError, match=str(invalid_job_id)): offline_simulator_no_noise.result(invalid_job_id) # querying the actual job is successful result = offline_simulator_no_noise.result(job_id) assert result.job.job_id == job_id def test_submit_valid_response(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.submit passes the authorization token and extracts the correct job_id when the response payload is valid. """ token = str(uuid.uuid4()) backend = DummyResource(token) expected_job_id = uuid.uuid4() def handle_submit(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert request.headers["authorization"] == f"Bearer {token}" return httpx.Response( status_code=httpx.codes.OK, json=json.loads( api_models.Response.queued( job_id=expected_job_id, resource_id=backend.resource_id, workspace_id=backend.workspace_id, ).json() ), ) httpx_mock.add_callback(handle_submit, method="POST") job_id = backend.submit([empty_circuit(2)], shots=10) assert job_id == expected_job_id def test_submit_bad_request(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.submit raises an HTTPError if the request is flagged invalid by the server. """ backend = DummyResource("") httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST) with pytest.raises(httpx.HTTPError): backend.submit([empty_circuit(2)], shots=10) def test_result_valid_response(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result passes the authorization token and returns the raw response payload. """ token = str(uuid.uuid4()) backend = DummyResource(token) job_id = uuid.uuid4() payload = api_models.Response.cancelled( job_id=job_id, resource_id=backend.resource_id, workspace_id=backend.workspace_id ) def handle_result(request: httpx.Request) -> httpx.Response: assert request.headers["user-agent"] == USER_AGENT assert request.headers["authorization"] == f"Bearer {token}" return httpx.Response(status_code=httpx.codes.OK, json=json.loads(payload.json())) httpx_mock.add_callback(handle_result, method="GET") response = backend.result(job_id) assert response == payload def test_result_bad_request(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result raises an HTTPError if the request is flagged invalid by the server. """ backend = DummyResource("") httpx_mock.add_response(status_code=httpx.codes.BAD_REQUEST) with pytest.raises(httpx.HTTPError): backend.result(uuid.uuid4()) def test_result_unknown_job(httpx_mock: HTTPXMock) -> None: """Check that AQTResource.result raises UnknownJobError if the API responds with an UnknownJob payload. """ backend = DummyResource("") job_id = uuid.uuid4() httpx_mock.add_response(json=json.loads(api_models.Response.unknown_job(job_id=job_id).json())) with pytest.raises(api_models.UnknownJobError, match=str(job_id)): backend.result(job_id) def test_resource_fixture_detect_invalid_circuits( offline_simulator_no_noise: MockSimulator, ) -> None: """Pass a circuit that cannot be converted to the AQT API to the mock simulator. This must fail. """ qc = QuantumCircuit(2) qc.h(0) qc.cnot(0, 1) qc.measure_all() with pytest.raises(ValueError, match="^Circuit cannot be converted"): offline_simulator_no_noise.run(qc)
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
from dell_runtime import DellRuntimeProvider from dell_runtime import BackendProvider provider = BackendProvider() provider.backends() backend = provider.get_backend(name="emulator") backend_config = backend.configuration() backend_config.backend_name from qiskit import QuantumCircuit, execute qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) job = backend.run(qc, shots=1024) result = job.result() counts = result.get_counts(qc) from qiskit.tools.visualization import plot_histogram, plot_state_city plot_histogram(counts, title='Bell-State counts')
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. """ n-qubit controlled gate """ from collections import namedtuple import numpy as np import qiskit from qiskit.circuit import Gate from qiskit import QuantumCircuit, QuantumRegister from qclib.gates.util import check_u2, apply_ctrl_state from qclib.gates.multitargetmcsu2 import MultiTargetMCSU2 from qclib.gates.ldmcu import Ldmcu # pylint: disable=protected-access class MCU(Gate): """ Approximated Multi-Controlled Unitary Gate https://arxiv.org/abs/2310.14974 ----------------------------------------- Implements gate decomposition of a multi-controlled operator in U(2) """ def __init__(self, unitary, num_controls, error=0, ctrl_state: str = None): """ Parameters ---------- unitary: U(2) gate num_controls (int): Number of controls error (float): max_error ctrl_state (str or int): Control state in decimal or as a bitstring """ check_u2(unitary) self.unitary = unitary self.error = error if num_controls > 0: self.control_qubits = QuantumRegister(num_controls) else: self.control_qubits = [] self.target_qubit = QuantumRegister(1) self.n_ctrl_base = self._get_num_base_ctrl_qubits(self.unitary, self.error) if self.n_ctrl_base == 0: raise ValueError("The number of base qubits is 0") if self.n_ctrl_base > num_controls: raise ValueError("The number of control qubits is too low") self.ctrl_state = ctrl_state super().__init__("McuApprox", num_controls + 1, [], "McuApprox") def _define(self): if len(self.control_qubits) > 0: self.definition = QuantumCircuit(self.control_qubits, self.target_qubit) self._apply_ctrl_state() gate_circuit = qiskit.QuantumCircuit(self.num_qubits, name="T" + str(0)) self._c1c2(self.num_qubits, gate_circuit) self._c1c2(self.num_qubits, gate_circuit, step=-1) self._c1c2(self.num_qubits - 1, gate_circuit, False) self._c1c2(self.num_qubits - 1, gate_circuit, False, -1) self.definition.append( gate_circuit, [*self.control_qubits, self.target_qubit] ) self._apply_ctrl_state() else: self.definition = QuantumCircuit(self.target_qubit) self.definition.unitary(self.unitary, 0) @staticmethod def _get_num_base_ctrl_qubits(unitary, error): """ Get the baseline number of control qubits for the approximation given an error args: unitary: Unitary to be approximated error: Error of the approximation """ eig_vals, _ = np.linalg.eig(unitary) angles = np.angle(eig_vals) if (1 - np.cos(angles[0])) >= (1 - np.cos(angles[1])): angle = angles[0] else: angle = angles[1] quotient = angle / np.arccos(1 - error**2 / 2) return int(np.ceil(np.log2(quotient))) + 1 def get_n_base(self, unitary, error): return self._get_num_base_ctrl_qubits(unitary, error) def _c1c2(self, n_qubits, gate_circ, first=True, step=1): extra_q, n_qubits_base = self._calc_extra_qubits(first, n_qubits) qubit_pairs = self._compute_qubit_pairs(n_qubits_base, step) unitary_list = [] targets = [] for pair in qubit_pairs: param = self._compute_param(pair) signal = -1 if (pair.control == 0 and not first) else 1 signal = step * signal # Perform a translation of the qubits by extra_q qubits in all cases # When target == last qubit and first==true apply the U gates, except # when control==0, in which case we don't do anything if pair.target == n_qubits_base - 1 and first: if pair.control != 0: csqgate = MCU._gate_u(self.unitary, param, signal) gate_circ.compose( csqgate, qubits=[pair.control + extra_q, pair.target + extra_q], inplace=True, ) # For the controlled rotations, when control==0, apply a multi-controlled # rotation with the extra control qubits else: if pair.control == 0 and extra_q >= 1: # Apply a multi-controlled Rx gate with the additional control qubits control_list = np.array(range(0, extra_q + 1)) unitary_list.append(self._compute_rx_matrix(param, signal)) targets.append(pair.target + extra_q) if pair.target == 1: MultiTargetMCSU2.multi_target_mcsu2( gate_circ, unitary_list, control_list, targets ) else: gate_circ.crx( signal * np.pi / param, pair.control + extra_q, pair.target + extra_q, ) def _calc_extra_qubits(self, first, n_qubits): if first: n_qubits_base = self.n_ctrl_base + 1 else: n_qubits_base = self.n_ctrl_base extra_q = n_qubits - n_qubits_base return extra_q, n_qubits_base @staticmethod def _compute_param(pair): exponent = pair.target - pair.control if pair.control == 0: exponent = exponent - 1 param = 2**exponent return param @staticmethod def _compute_rx_matrix(param, signal): theta = signal * np.pi / param rx_matrix = np.array( [ [np.cos(theta / 2), (-1j) * np.sin(theta / 2)], [(-1j) * np.sin(theta / 2), np.cos(theta / 2)], ] ) return rx_matrix @staticmethod def _compute_qubit_pairs(n_qubits_base, step): pairs = namedtuple("pairs", ["control", "target"]) if step == 1: start = 0 reverse = True else: start = 1 reverse = False qubit_pairs = [ pairs(control, target) for target in range(n_qubits_base) for control in range(start, target) ] qubit_pairs.sort(key=lambda e: e.control + e.target, reverse=reverse) return qubit_pairs @staticmethod def _gate_u(a_gate, coefficient, signal): param = 1 / np.abs(coefficient) values, vectors = np.linalg.eig(a_gate) gate = ( np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T ) gate = ( gate + np.power(values[1] + 0j, param) * vectors[:, [1]] @ vectors[:, [1]].conj().T ) if signal < 0: gate = np.linalg.inv(gate) s_q_gate = QuantumCircuit(1, name="U^1/" + str(coefficient)) s_q_gate.unitary(gate, 0) # pylint: disable=maybe-no-member c_s_q_gate = s_q_gate.control(1) return c_s_q_gate @staticmethod def mcu(circuit, unitary, controls, target, error, ctrl_state=None): """ Approximated Multi-Controlled Unitary Gate https://arxiv.org/abs/2310.14974 """ if error == 0: circuit.append( Ldmcu(unitary, len(controls), ctrl_state=ctrl_state), [*controls, target] ) else: circuit.append( MCU(unitary, len(controls), error, ctrl_state=ctrl_state), [*controls, target], ) MCU._apply_ctrl_state = apply_ctrl_state
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
import numpy as np import cirq def main(): circuit = make_bell_test_circuit() print("Circuit:") print(circuit) #Run Simulation sim = cirq.Simulator() repetitions = 1000 print("Simulating {} repetitions".format(repetitions)) result = sim.run(program=circuit, repetitions=repetitions) ## Collect Results a = np.array(result.measurements['a'] [:, 0]) b = np.array(result.measurements['b'] [:, 0]) x = np.array(result.measurements['x'] [:, 0]) y = np.array(result.measurements['y'] [:, 0]) outcomes = a ^ b == x & y win_percent = len([e for e in outcomes if e]) * 100/repetitions print() print('Results') print('a:', bitstring(a)) print('b:', bitstring(b)) print('x:', bitstring(x)) print('y:', bitstring(y)) print('(a XOR b) == (x AND y): \n', bitstring(outcomes)) print('Win rate: {}%' .format(win_percent)) def make_bell_test_circuit(): alice = cirq.GridQubit(0, 0) bob = cirq.GridQubit(1, 0) alice_referee = cirq.GridQubit(0, 1) bob_referee = cirq.GridQubit(1,1) circuit = cirq.Circuit() ## Prepare shared entanglement circuit.append([cirq.H(alice), cirq.CNOT(alice, bob), cirq.X(alice)**-0.25,]) ## Referee flip coins circuit.append([cirq.H(alice_referee), cirq.H(bob_referee), ]) ## Players do oa sqrt based on their referee coin circuit.append([cirq.CNOT(alice_referee, alice)**0.5, cirq.CNOT(bob_referee, bob)**0.5, ]) circuit.append([ cirq.measure(alice, key = 'a'), cirq.measure(bob, key = 'b'), cirq.measure(alice_referee, key = 'x'), cirq.measure(bob_referee, key = 'y'), ]) return circuit def bitstring(bits): return ''.join('1' if e else '_' for e in bits) if __name__ == '__main__': main()
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
https://github.com/Seanaventure/HighErrorRateRouting
Seanaventure
import matplotlib.pyplot as plt import networkx as nx import qiskit import HERR from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes.routing import BasicSwap from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.converters import dag_to_circuit from math import pi from qiskit.compiler import transpile, assemble from qiskit.providers.aer.noise import NoiseModel import qiskit.providers.aer.noise as noise from qiskit.tools.visualization import dag_drawer import random from qiskit.circuit.instruction import Instruction couplingList = list() for i in range(4): for j in range(4): if i is not j: couplingList.append([i, j]) provider = IBMQ.load_account() backend = provider.get_backend('ibmq_lima') basis_gates = backend.configuration().basis_gates couplingMap = CouplingMap(couplingList) squareCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: squareCouplingList.append([i, j]) squareCouplingList.append(([0, 3])) squareCouplingList.append(([3, 0])) squareCouplingMap = CouplingMap(squareCouplingList) gridCouplingList = list() for i in range(4): for j in range(4): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) for i in range(4,8): for j in range(4,8): if i is not j: if abs(i-j) == 1: gridCouplingList.append([i, j]) gridCouplingList.append(([0, 4])) gridCouplingList.append(([4, 0])) gridCouplingList.append(([1, 5])) gridCouplingList.append(([5, 1])) gridCouplingList.append(([2, 6])) gridCouplingList.append(([6, 2])) gridCouplingList.append(([3, 7])) gridCouplingList.append(([7, 3])) gridCouplingMap = CouplingMap(gridCouplingList) jakatraCouplingList = [[0, 1], [1, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3,5], [5,3], [4,5], [5,4], [6,5], [5,6]] jakatraCouplingMap = CouplingMap(jakatraCouplingList) def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates def countTwoQubitGates(transpiledCircuit): num = 0 for gate in transpiledCircuit.data: # print(type(gate[0])) if issubclass(type(gate[0]), Instruction): if gate[0].name == "cx": num += 1 return num s = '1011011' n = len(s) # Let's see how it looks: circuit = QuantumCircuit(n) for ii, yesno in enumerate(reversed(s)): if yesno == '1': circuit.x(ii) qft(circuit, n) circuit = inverse_qft(circuit, n) circuit.measure_all() circDag = circuit_to_dag(circuit) targetCouplingMap = jakatraCouplingMap # Transpile non HERR transpiledBasic = transpile(circuit, Aer.get_backend('qasm_simulator'), coupling_map=targetCouplingMap, basis_gates=basis_gates, routing_method='basic', layout_method='trivial') transpiledSabre = transpile(circuit, Aer.get_backend('qasm_simulator'), coupling_map=targetCouplingMap, basis_gates=basis_gates, routing_method='sabre', layout_method='trivial') transpiledStochastic = transpile(circuit, Aer.get_backend('qasm_simulator'), coupling_map=targetCouplingMap, basis_gates=basis_gates, routing_method='stochastic', layout_method='trivial') transpiledLookahead = transpile(circuit, Aer.get_backend('qasm_simulator'), coupling_map=targetCouplingMap, basis_gates=basis_gates, routing_method='lookahead', layout_method='trivial') for i in range(200): # Create a noise model for the simulations noise_model = noise.NoiseModel() errorRates = list() qiskitErrors = list() for i in range(len(jakatraCouplingList)//2): errorRates.append(random.randrange(1, 10, 1)/100.0) qiskitErrors.append(noise.depolarizing_error(errorRates[i], 2)) edges = targetCouplingMap.get_edges() uniqueEdges = set() for edge in edges: uniqueEdges.add(tuple(sorted(edge))) noiseGraph = nx.Graph() noiseGraph.add_nodes_from([0, 7]) errorIdex = 0 for edge in uniqueEdges: noise_model.add_quantum_error(qiskitErrors[errorIdex], ['cx'], edge) noiseGraph.add_edge(edge[0], edge[1], weight=errorRates[errorIdex]) errorIdex += 1 herr = HERR.HERR(targetCouplingMap, noiseGraph) basSwap = BasicSwap(targetCouplingMap) #print(gridCouplingMap) # Run HERR HERRRes = herr.run(circDag) updatedCirc = dag_to_circuit(HERRRes) bSwapRes = basSwap.run(circDag) bSwapCirc = dag_to_circuit(bSwapRes) # Transpile HERR transpiledHERR = transpile(updatedCirc, Aer.get_backend('qasm_simulator'), coupling_map=targetCouplingMap, basis_gates=basis_gates, routing_method='basic', layout_method='trivial') # if transpiledNormal != transpiledHERR: # fName = "HERRQFTCouplingOutputs/HERRCirc" + str(i) + ".png" # fName2 = "HERRQFTCouplingOutputs/NonCirc" + str(i) + ".png" # transpiledHERR.draw(output='mpl', filename=fName) # transpiledNormal.draw(output='mpl', filename=fName2) # break # HERRCnotGateNum = countTwoQubitGates(transpiledHERR) # normalCnotGateNum = countTwoQubitGates(transpiledNormal) # print(str(HERRCnotGateNum) + " " + str(normalCnotGateNum)) sim = Aer.get_backend('qasm_simulator') simResultHERR = sim.run(transpiledHERR, noise_model=noise_model).result() simResultBasic = sim.run(transpiledBasic, noise_model=noise_model).result() simResultSabre = sim.run(transpiledSabre, noise_model=noise_model).result() simResultLookahead = sim.run(transpiledLookahead, noise_model=noise_model).result() simResultStochastic = sim.run(transpiledStochastic, noise_model=noise_model).result() # Output file and print results fName = "HERRQFTCouplingOutputs/HERRCirc" + str(i) + ".png" fName2 = "HERRQFTCouplingOutputs/NonCirc" + str(i) + ".png" #updatedCirc.draw(output='mpl', filename=fName) #bSwapCirc.draw(output='mpl', filename=fName2) #if transpiledNormal != transpiledHERR: #print("CIRCUIT CHANGED") #updatedCirc.draw(output='mpl', filename=fName) #bSwapCirc.draw(output='mpl', filename=fName2) #print("Iter: " + str(i) + " ErrorRate of edges (0,1) (1, 2), (0, 2), (1, 3), (2, 3), (0, 3) counts for HERR/nonHERR:") #print(str(err1Rate) + " " + str(err2Rate) + " " + str(err3Rate) + " " + str(err4Rate) + " " + str(err5Rate) + " " + str(err6Rate)) if s in simResultHERR.get_counts() and s in simResultBasic.get_counts() and s in simResultSabre.get_counts() and s in simResultLookahead.get_counts() and s in simResultStochastic.get_counts(): print(str(simResultHERR.get_counts()[s]/1024.0) + " " + str(simResultBasic.get_counts()[s]/1024.0) + " " + str(simResultSabre.get_counts()[s]/1024.0) + " " + str(simResultLookahead.get_counts()[s]/1024.0) + " " + str(simResultStochastic.get_counts()[s]/1024.0)) else: print("Key error! Oops!") #print("----------------------")
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. """Tests from circuit basics tutorial.""" import math import ddt from qiskit import QuantumCircuit, transpile from qiskit_neko import decorators from qiskit_neko.tests import base @ddt.ddt class TestCircuitBasics(base.BaseTestCase): """Tests adapted from circuit basics tutorial.""" def setUp(self): super().setUp() self.circ = QuantumCircuit(3) self.circ.h(0) self.circ.cx(0, 1) self.circ.cx(0, 2) @decorators.component_attr("terra", "backend") @ddt.data(0, 1, 2, 3) def test_ghz_circuit(self, opt_level): """Test execution of ghz circuit.""" self.circ.measure_all() tqc = transpile(self.circ, self.backend, optimization_level=opt_level) run_kwargs = {} expected_value = None if hasattr(self.backend.options, "shots"): run_kwargs["shots"] = 1000 expected_value = 500 if hasattr(self.backend.options, "seed_simulator"): run_kwargs["seed_simulator"] = 42 job = self.backend.run(tqc, **run_kwargs) result = job.result() counts = result.get_counts() if expected_value is None: expected_value = sum(counts.values()) / 2 expected = {"000": expected_value, "111": expected_value} delta = 10 ** math.floor(math.log10(expected_value)) self.assertDictAlmostEqual(counts, expected, delta=delta)
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 QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/biswaroopmukherjee/Quantum-Waddle
biswaroopmukherjee
# Library for implementing XOR import qiskit import numpy as np from qiskit import( IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister, execute, QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram, plot_state_city if __name__ == "__main__": pass def binary_it(alpha): ''' binary_it: returns a list that is indexed according to power, binaried[0] = is LSB. ''' binaried = [int(x) for x in bin(alpha)[2:]] binaried.reverse() return binaried def invert(alpha): return [ 1 - x for x in alpha] def xor_gate_v_each(circuit, a,b,r, v,c,a0): ''' xor_gate_v_each: See paper 'An Example of the Difference Between Quantum and Classical Random Walks' args: circuit -- the py object that holds the quantum circuit. a -- q. reg. for the vertex. b -- q. reg. for holding neighbor vertex. r -- q. reg. for checking valid edge. f(c, a0) -- function that returns the neighboring -- vertex of a0 using label c for the vertex label. c -- label of the edge a0 -- label of the vertex ''' #vc = v(c,a0); vc = 1 #build in the not's for the a0 check. binaried = binary_it(a0) #match binaried if len(binaried) > len(a): binaried = binaried[:len(a)] elif len(a) > len(binaried): for i in range(len(a)-len(binaried)): binaried.append(0) notMask = invert(binaried) for i in range(len(notMask)): if notMask[i]: circuit.x(a[i]); #build in the cnots for xoring b binaried = binary_it(vc) #match binaried if len(binaried) > len(a): binaried = binaried[:len(a)] elif len(a) > len(binaried): for i in range(len(a)-len(binaried)): binaried.append(0) for i in range(len(binaried)): if binaried[i]: circuit.mct(a,b[i], None, mode='noancilla') #build in the not's for the a0 return. for i in range(len(notMask)): if notMask[i]: circuit.x(a[i]); def xor_gate_f_each(circuit, a,b,r, v,c,a0): ''' xor_gate_v_each: See paper 'An Example of the Difference Between Quantum and Classical Random Walks' args: circuit -- the py object that holds the quantum circuit. a -- q. reg. for the vertex. b -- q. reg. for holding neighbor vertex. r -- q. reg. for checking valid edge. f(c, a0) -- function that returns the neighboring -- vertex of a0 using label c for the vertex label. c -- label of the edge a0 -- label of the vertex ''' #fc = f(c,a0); fc = 1 #build in the not's for the a0 check. binaried = binary_it(a0) #match binaried if len(binaried) > len(a): binaried = binaried[:len(a)] elif len(a) > len(binaried): for i in range(len(a)-len(binaried)): binaried.append(0) notMask = invert(binaried) for i in range(len(notMask)): if notMask[i]: circuit.x(a[i]); #build in the cnots for xoring b binaried = binary_it(fc) #match binaried if len(binaried) > len(r): binaried = binaried[:len(r)] elif len(r) > len(binaried): for i in range(len(r)-len(binaried)): binaried.append(0) for i in range(len(binaried)): if binaried[i]: circuit.mct(a,r[i], None, mode='noancilla') #build in the not's for the a0 return. for i in range(len(notMask)): if notMask[i]: circuit.x(a[i]); n = 2 simulator = Aer.get_backend('qasm_simulator') a = QuantumRegister(n, 'a') b = QuantumRegister(n, 'b') r = QuantumRegister(1, 'r') circuit = QuantumCircuit(a, b, r) a0 = 1 xor_gate_v_each(circuit, a,b,r, 0,0,a0) circuit.barrier() a0 = 2 xor_gate_f_each(circuit, a,b,r, 0,0,a0) circuit.draw()
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
Andres8bit
# Deutsch-Josza: # first example of a quantum algorithm that performs better than the best classical algorithm. # Problem: given a string of bits and a hidden boolean function f, which returns either 0 || 1 # The function is guaranteed to either be balanced or constant: # balance -> return's 0 or 1 with exactly 50/50 probability. # constant -> return's all 0's or all 1's for any input. # determine whether the functionc is balanced or constant. # # Classical Approach: # The classical approach requires two queries per bit. # If the two are the same we have a constant function, otherwise it must be balanced. # Quantum Approach: # Using a quantum circuit we can solve this problem with a single query. # We can express the probability that the function is constatn as a function of k inputs as: # P(k) = 1- 1/2^(k-1), for k <= 2^(n-1) # Steps: # 1. Prepare two quantum registers: # The first is n-qubit register initialised to |0>. # The second is a 1-qubit register initialised to |1>\ # 2. Apply a Hadamard gate to each qubit: # after this step the input register is in an equal superposition of all states. # When the oracle is balanced, phase kick back adds a negative phase to 1/2 of the states. # 3. Apply the wuantym oracle |x>|y> to |x|y NOT f(x)> # 4. Apply a Hadamard gate to each qubit in the first register: # we reverse step 2 to obtain the init. quantum state of the first register. # 5. Measure the first register %matplotlib inline import numpy as np # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.tools.monitor import job_monitor # Loading your IBM Q account(s) provider = IBMQ.load_account() # import basic plot tools from qiskit.visualization import plot_histogram # n = 3 # const_oracle = QuantumCircuit(n+1) # output = np.random.randint(2) # if output == 1: # const_oracle.x(n) # 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() def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw() backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer) # Using a real Quantum Device: provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 1024 job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts() plot_histogram(answer)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit.compiler import transpile from qiskit import QuantumCircuit from qiskit.transpiler import InstructionDurations from qiskit.providers.fake_provider import FakeMelbourne from .utils import build_qv_model_circuit class TranspilerLevelBenchmarks: params = [0, 1, 2, 3] param_names = ["transpiler optimization level"] timeout = 600 def setup(self, _): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.basis_gates = ["u1", "u2", "u3", "cx", "id"] self.qv_50_x_20 = build_qv_model_circuit(50, 20, 0) self.qv_14_x_14 = build_qv_model_circuit(14, 14, 0) self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = QuantumCircuit.from_qasm_file(large_qasm_path) self.melbourne = FakeMelbourne() self.durations = InstructionDurations( [ ("u1", None, 0), ("id", None, 160), ("u2", None, 160), ("u3", None, 320), ("cx", None, 800), ("measure", None, 3200), ], dt=1e-9, ) def time_quantum_volume_transpile_50_x_20(self, transpiler_level): transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_quantum_volume_transpile_50_x_20(self, transpiler_level): return transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm(self, transpiler_level): transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_transpile_from_large_qasm(self, transpiler_level): return transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): return transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_transpile_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_qv_14_x_14(self, transpiler_level): return transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_schedule_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level, scheduling_method="alap", instruction_durations=self.durations, ) # limit optimization levels to reduce time time_schedule_qv_14_x_14.params = [0, 1]