repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit.circuit import Parameter from qiskit import pulse from qiskit.test.mock.backends.almaden import * phase = Parameter('phase') with pulse.build(FakeAlmaden()) as phase_test_sched: pulse.shift_phase(phase, pulse.drive_channel(0)) phase_test_sched.instructions # ()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization import QuadraticProgram qp = QuadraticProgram() qp.binary_var("x") qp.binary_var("y") qp.integer_var(lowerbound=0, upperbound=7, name="z") qp.maximize(linear={"x": 2, "y": 1, "z": 1}) qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq") qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq") print(qp.prettyprint()) from qiskit_optimization.converters import InequalityToEquality ineq2eq = InequalityToEquality() qp_eq = ineq2eq.convert(qp) print(qp_eq.prettyprint()) print(qp_eq.prettyprint()) from qiskit_optimization.converters import IntegerToBinary int2bin = IntegerToBinary() qp_eq_bin = int2bin.convert(qp_eq) print(qp_eq_bin.prettyprint()) print(qp_eq_bin.prettyprint()) from qiskit_optimization.converters import LinearEqualityToPenalty lineq2penalty = LinearEqualityToPenalty() qubo = lineq2penalty.convert(qp_eq_bin) print(qubo.prettyprint()) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit, execute from qiskit.quantum_info import Statevector qc = QuantumCircuit(8, 8) sv = Statevector.from_label("11011000") qc.initialize(sv, range(8)) qc.cx(0, 1) qc.cx(2, 3) qc.cx(4, 5) qc.cx(6, 7) qc.measure(range(8), range(8)) qc.draw("mpl")
https://github.com/sorin-bolos/QiskitCampAsia2019
sorin-bolos
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import run_algorithm from qiskit.aqua.input import EnergyInput from qiskit.aqua.translators.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance from qiskit.quantum_info import Pauli from qiskit.aqua.operators import WeightedPauliOperator from collections import OrderedDict # setup aqua logging import logging from qiskit.aqua import set_qiskit_aqua_logging # set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log def get_values_qubitops(values): num_values = len(values) pauli_list = [] shift = 0 for i in range(num_values): xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = True pauli_list.append([0.5 * values[i], Pauli(zp, xp)]) shift -= 0.5 * values[i] return WeightedPauliOperator(paulis=pauli_list), shift values = [3, 6, -4, 8] qubitOp, offset = get_values_qubitops(values) algo_input = EnergyInput(qubitOp) ee = ExactEigensolver(qubitOp, k=1) result = ee.run() def sample_most_likely(state_vector): if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict): # get the binary string with the largest count binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0] x = np.asarray([int(y) for y in reversed(list(binary_string))]) return x else: n = int(np.log2(state_vector.shape[0])) k = np.argmax(np.abs(state_vector)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x most_lightly = result['eigvecs'][0] x = sample_most_likely(most_lightly) x seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) result_statevector = vqe.run(quantum_instance) most_lightly = result_statevector['eigvecs'][0] x_statevector = sample_most_likely(most_lightly) x_statevector # run quantum algorithm with shots seed = 10598 spsa = SPSA(max_trials=300) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result_shots = vqe.run(quantum_instance) most_lightly_shots = result_shots['eigvecs'][0] x_shots = sample_most_likely(most_lightly_shots) x_shots
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import numpy as np import pandas as pd import itertools import cma import os import sys import argparse import pickle import random import re from pprint import pprint import qiskit from qiskit import * from qiskit import Aer from qiskit import IBMQ from qiskit.providers.aer.noise.noise_model import NoiseModel from qiskit.test.mock import * from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import mitiq IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='', group='internal', project='hirashi-jst') print("provider:", provider) L = 3 p = 2 dt = 1.0 tf = 20 shots = 8192 def TwirlCircuit(circ: str) -> QuantumCircuit: """ そのまま使う: 修正は後回し """ #! qasm ベタ書き def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'id q[{qb}];\n' 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) #! 生のqasmコードを持ってきてる: オペレータに分解 for op in ops: if (op[:2] == 'cx'): # can add for cz, etc. num = random.randrange(len(paulis)) #! permute 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 qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ) # とりあえずOK def evolve(alpha: float, q0: Union[int, QuantumRegister], q1: Union[int, QuantumRegister]) -> QuantumCircuit: """ The implementation of Fig. 4 in https://arxiv.org/abs/2112.12654 """ qc = QuantumCircuit(2) qc.rz(-np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(alpha - np.pi / 2, q0) qc.ry(np.pi / 2 - alpha, q1) qc.cnot(q0, q1) qc.ry(alpha - np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(np.pi / 2, q0) return qc # とりあえずOK def make_ansatz_circuit(num_qubits: int, ansatz_depth: int, parameters: np.array) -> QuantumCircuit: """ Prepare ansatz circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == AnsatzCircuit(param, p) -> QuantumCircuit Args: parameters: 1d array (for 2d parameters on circuit) """ qc = QuantumCircuit(num_qubits) for l in range(ansatz_depth): if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace=True) else: for i in range(0, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) return qc # とりあえずOK def make_trotter_circuit(num_qubits: int, time_interval: float) -> QuantumCircuit: """ Prepare Trotter circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == TrotterEvolveCircuit(dt, nt, init) -> QuantumCircuit """ qc = QuantumCircuit(num_qubits) for n in range(trotter_steps): #! time_interval の符号に注意 if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 else: for i in range(0, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 return qc #TODO VTCとは別実装?→ no, 同じ実装に。 def SimulateAndReorder(circ): """ #! execution wrapper Executes a circuit using the statevector simulator and reorders basis to match with standard """ backend = Aer.get_backend('statevector_simulator') return execute(circ.reverse_bits(), backend).result().get_statevector() def Simulate(circ): """ #! execution wrapper Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC """ backend = Aer.get_backend('statevector_simulator') return execute(circ, backend).result().get_statevector() #TODO def LoschmidtEchoExecutor(circuits, backend, shots, filter): """ #! 回路を実行 Returns the expectation value to be mitigated. :param circuit: Circuit to run. #! ここでのcircuitsは :param backend: backend to run the circuit on :param shots: Number of times to execute the circuit to compute the expectation value. :param fitter: measurement error mitigator """ # circuits = [TwirlCircuit(circ) for circ in circuits] scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ folded_circuits = [] #! ZNE用の回路 for circuit in circuits: folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化 folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す! print("length of circuit in job", len(folded_circuits)) #! jobを投げる job = qiskit.execute( experiments=folded_circuits, backend=backend, optimization_level=0, shots=shots ) print("casted job") #! fidelity測定用(VTCをしないなら、ここはtomographyで良い) c = ['1','1','0'] #! これをpermutationする # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ''.join(c)[::-1] #! endianを反転 (big endianへ) res = job.result() if (filter is not None): #! QREM res = filter.apply(res) print("retrieved job") all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))] expectation_values = [] for counts in all_counts: total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots]) if counts.get(c) is None: expectation_values.append(0) else: expectation_values.append(counts.get(c)/total_allowed_shots) # expectation_values = [counts.get(c) / shots for counts in all_counts] zero_noise_values = [] if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim for i in range(len(circuits)): zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) else: #device_sim, real_device fac = mitiq.zne.inference.LinearFactory(scale_factors) for i in range(len(circuits)): zero_noise_values.append(fac.extrapolate(scale_factors, expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) print("zero_noise_values") pprint(zero_noise_values) print() return zero_noise_values #TODO def LoschmidtEchoCircuit(params, U_v, U_trot, init, p): """ #! 回路を作成 Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots :param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function :param U_v: variational circuit that stores the state before the trotter step :param U_trot: trotter step :param init: initial state :param p: number of ansatz steps """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ.measure_all() return circ def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter): """ #! 実行パート """ circs = [] for param in params: circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成 print("length of circuits without zne:", len(circs)) res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行 return abs(1 - np.array(res)) def LoschmidtEchoExact(params, U_v, U_trot, init, p): """ #! unused function """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ_vec = Simulate(circ) init_vec = Simulate(init) return 1 - abs(np.conj(circ_vec) @ init_vec)**2 def CMAES(U_v, U_trot, init, p, backend, shots, filter): """ #! 実行 + 最適化パート """ init_params = np.random.uniform(0, 2*np.pi, (L-1)*p) es = cma.CMAEvolutionStrategy(init_params, np.pi/2) es.opts.set({'ftarget':5e-3, 'maxiter':1000}) # es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb')) while not es.stop(): #! 最適化パート # solutions = es.ask(25) # ! 25 = number of returned solutions solutions = es.ask(10) print("solutions") pprint(solutions) es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート # es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート es.disp() open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps()) return es.result_pretty() def VTC(tf, dt, p, init, backend, shots, filter): """ #! tf: 総経過時間 #! dt: trotter step size: 時間間隔 #! p: ansatzのステップ数 """ VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値) VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector] # TrotterFixStepList = [init] TimeStep = [0] if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) temp = VTCParamList.iloc[-1] print(temp, "th time interval") U_v = AnsatzCircuit(temp, p) else: #! 最初はこっちに入る VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) print("0 th time interval") print() U_v = QuantumCircuit(L) ts = VTCParamList.index #! 時間間隔 U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る print() print("start CMAES") print() res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!! print() print("res") pprint(res) #! 新しいループ結果を追加し、tsを更新 res = res.xbest # ! best solution evaluated print("res.xbest") pprint(res) VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res) VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p))) ts = VTCParamList.index # VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) # VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) #! csvファイルを更新 VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv') VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv') if (ts[-1] >= tf): return else: print("next step") VTC(tf, dt, p, init, backend, shots, filter) #! ここからQREM回路 qr = QuantumRegister(L) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # device_backend = FakeJakarta() # device_sim = AerSimulator.from_backend(device_backend) real_device = provider.get_backend('ibmq_jakarta') noise_model = NoiseModel.from_backend(real_device) device_sim = QasmSimulator(method='statevector', noise_model=noise_model) exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector') t_qc = transpile(meas_calibs) qobj = assemble(t_qc, shots=8192) # cal_results = real_device.run(qobj, shots=8192).result() cal_results = device_sim.run(qobj, shots=8192).result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print("qrem done") # np.around(meas_fitter.cal_matrix, decimals=2) init = QuantumCircuit(L) # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識??? #! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか? for q in range(len(c)): if (c[q] == '1'): init.x(q) #! ここまでQREM回路 nt = int(np.ceil(tf / (dt * p))) # f = open(f'./results_{L}/logging.txt', 'a') # sys.stdout = f #! tf: シミュレーションの(経過)時間 #! dt: trotter分解のステップ数 #! p: ansatzのステップ数 (論文中のL) # VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理 print("vtc start!!!! \n\n\n") VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理 # f.close()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ print("Ch 7: Adding the noise profile of an IBM Q machine to your local simulator") print("--------------------------------------------------------------------------") # Import Qiskit and load account from qiskit import Aer, IBMQ, QuantumCircuit, execute from qiskit.providers.aer.noise import NoiseModel from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor import numpy as np np.set_printoptions(precision=3) from IPython.core.display import display print("Getting provider...") if not IBMQ.active_account(): IBMQ.load_account() provider = IBMQ.get_provider() global backend, noise_model def select_backend(): # Get all available and operational backends. available_backends = provider.backends(filters=lambda b: not b.configuration().simulator and b.configuration().n_qubits > 1 and b.status().operational) # Fish out criteria to compare print("{0:20} {1:<10} {2:<10}".format("Name","#Qubits","Pending jobs")) print("{0:20} {1:<10} {2:<10}".format("----","-------","------------")) for n in range(0, len(available_backends)): backend = provider.get_backend(str(available_backends[n])) print("{0:20} {1:<10}".format(backend.name(),backend.configuration().n_qubits),backend.status().pending_jobs) select_backend=input("Select a backend ('exit' to end): ") if select_backend!="exit": backend = provider.get_backend(select_backend) else: backend=select_backend return(backend) def build_noise_model(backend): # Construct the noise model from backend noise_model = NoiseModel.from_backend(backend) print(noise_model) return(noise_model) def execute_circuit(backend, noise_model): # Basis gates for the noise model basis_gates = noise_model.basis_gates # Coupling map coupling_map = backend.configuration().coupling_map print("Coupling map: ",coupling_map) # Construct the GHZ-state quantum circuit circ = QuantumCircuit(3, 3) circ.h(0) circ.cx(0, 1) circ.cx(0, 2) circ.measure([0,1,2], [0,1,2]) print(circ) # Execute on QASM simulator and get counts counts = execute(circ, Aer.get_backend('qasm_simulator')).result().get_counts(circ) display(plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state on local qasm_simulator')) # Execute noisy simulation on QASM simulator and get counts counts_noise = execute(circ, Aer.get_backend('qasm_simulator'), noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result().get_counts(circ) display(plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with noise model on local qasm simulator")) # Execute noisy simulation on the ibmq_qasm_simulator and get counts counts_noise_ibmq = execute(circ, provider.get_backend('ibmq_qasm_simulator'), noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result().get_counts(circ) display(plot_histogram(counts_noise_ibmq, title="Counts for 3-qubit GHZ state with noise model on IBMQ qasm simulator")) # Execute job on IBM Q backend and get counts job = execute(circ, backend) job_monitor(job) counts_ibmq=job.result().get_counts() title="Counts for 3-qubit GHZ state on IBMQ backend " + backend.name() display(plot_histogram(counts_ibmq, title=title)) # Display the results for all runs display(plot_histogram([counts, counts_noise, counts_noise_ibmq, counts_ibmq], bar_labels=True, legend=["Baseline","Noise on simulator", "Noise on IBMQ simulator", "IBM Q backend"], title="Comparison")) while True: # Select backend back=select_backend() if back=="exit": break # Build noise model and then run the circuit noise=build_noise_model(back) execute_circuit(back, noise)
https://github.com/arthurfaria/QC_basic_agorithms_qiskit
arthurfaria
###### Import Libraries import numpy as np from qiskit import Aer from qiskit_nature.drivers import UnitsType, Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.converters.second_quantization import QubitConverter from qiskit_nature.mappers.second_quantization import JordanWignerMapper import time molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["F", [0.0, 0.0, 0.9554]]], charge=0, multiplicity=1 ) print(molecule.geometry) ###### Define the electronic structure driver driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF, ) # define the electronic structure problem as a function of the driver es_problem = ElectronicStructureProblem(driver) # build the second quantized Hamiltonian of the molecule second_q_op = es_problem.second_q_ops() # print the Hamiltonian, no. of spin orbitals or qubits, and the no. of paticles print('\n',"The second quantized form of the electronic Hamiltonian is" , second_q_op[0]) print('\n',"The no. of spin orbitals is", es_problem.num_spin_orbitals) print('\n', "The total no. of electrons is", es_problem.num_particles) qubit_converter = QubitConverter(JordanWignerMapper()) %%time from qiskit.algorithms import NumPyMinimumEigensolver from qiskit_nature.algorithms import GroundStateEigensolver ############################## # Provide your code here numpy_solver = NumPyMinimumEigensolver() numpy_ground_state_solver = GroundStateEigensolver(qubit_converter=qubit_converter, solver=numpy_solver) numpy_results = numpy_ground_state_solver.solve(problem=es_problem) ############################## exact_energy = np.real(numpy_results.electronic_energies + numpy_results.nuclear_repulsion_energy)[0] print(f"Exact electronic energy: {exact_energy:.6f} Hartree\n") print(numpy_results) %%time from qiskit.utils import QuantumInstance from qiskit_nature.algorithms import VQEUCCFactory #backend backend=Aer.get_backend("aer_simulator_statevector") # Select the simulator to run the calculation quantum_instance = QuantumInstance(backend=backend) # define the VQE simulator vqe_solver = VQEUCCFactory(quantum_instance) %%time from qiskit_nature.algorithms import GroundStateEigensolver # do the calculation calc = GroundStateEigensolver(qubit_converter, vqe_solver) # save the result res = calc.solve(es_problem) # print the result print(res) from qiskit.algorithms.optimizers import COBYLA from qiskit_nature.drivers.second_quantization import PySCFDriver driver_reduced = PySCFDriver(atom='H 0.0, 0.0, 0.0; F 0.0, 0.0, 0.9554', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='STO3G') es_problem = ElectronicStructureProblem(driver_reduced) properties = driver_reduced.run() from qiskit_nature.circuit.library import HartreeFock from qiskit.circuit.library import EfficientSU2 from qiskit_nature.properties.second_quantization.electronic import ParticleNumber particle_number = properties.get_property(ParticleNumber) init_state = HartreeFock(num_spin_orbitals=particle_number.num_spin_orbitals, num_particles=particle_number.num_particles, qubit_converter=qubit_converter) init_state.barrier() ############################## ansatz = EfficientSU2(num_qubits=particle_number.num_spin_orbitals, reps=1, entanglement='linear', initial_state=init_state, insert_barriers=True) ############################## ansatz.decompose().draw('mpl') from qiskit.providers.aer import StatevectorSimulator from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.algorithms import VQE ############################## # Provide your code here backend1 = StatevectorSimulator() optimizer = L_BFGS_B(maxfun=400) ############################## from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver from jupyterplot import ProgressPlot error_threshold = 10 # mHartree np.random.seed(5) # fix seed for reproducibility initial_point = np.random.random(ansatz.num_parameters) from qiskit.providers.aer import StatevectorSimulator from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.algorithms import VQE ############################## # Provide your code here backend1 = StatevectorSimulator() optimizer = L_BFGS_B(maxfun=400) ############################## from qiskit_nature.algorithms import VQEUCCFactory, GroundStateEigensolver from jupyterplot import ProgressPlot error_threshold = 10 # mHartree np.random.seed(5) # fix seed for reproducibility initial_point = np.random.random(ansatz.num_parameters) %%time # for live plotting pp = ProgressPlot(plot_names=['Energy'], line_names=['Runtime VQE', f'Target + {error_threshold}mH', 'Target']) intermediate_info = { 'nfev': [], 'parameters': [], 'energy': [], 'stddev': [] } def callback(nfev, parameters, energy, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['energy'].append(energy) intermediate_info['stddev'].append(stddev) pp.update([[energy, exact_energy+error_threshold/1000, exact_energy]]) ############################## # Provide your code here vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=backend1, callback=callback, initial_point=initial_point) vqe_ground_state_solver = GroundStateEigensolver(qubit_converter=qubit_converter, solver=vqe) vqe_results = vqe_ground_state_solver.solve(problem=es_problem) ############################## print(vqe_results) error = (vqe_results.computed_energies[0] - exact_energy) * 1000 # mHartree print(f'Error is: {error:.3f} Hartree') %%time WITHOUT__ActiveSpace = ElectronicStructureProblem(driver_reduced) second_q_ops = WITHOUT__ActiveSpace.second_q_ops() main_op = second_q_ops[0] # particle_number = problem.molecule_data_transformed # num_particles = (particle_number.num_alpha, particle_numbaer.num_beta) # num_spin_orbitals = particle_number.num_molecular_orbitals*2 molecule = driver.run() simulation = QuantumInstance(backend=backend) mapper = JordanWignerMapper() qubit_converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) qubit_op = qubit_converter.convert(main_op, num_particles=2) %%time shots=10 begin = time.time() VQE = VQEUCCFactory(simulation, optimizer=COBYLA(maxiter=shots)) calculation = GroundStateEigensolver(qubit_converter, VQE) result0 = calculation.solve(WITHOUT__ActiveSpace) end = time.time() print(f"Total runtime of the program is {end - begin}") np.real(result0.electronic_energies + result0.nuclear_repulsion_energy)[0] # from qiskit_nature.transformers import ActiveSpaceTransformer from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer transformer = ActiveSpaceTransformer(2, 2, [4,5]) %%time WITH_ActiveSpace = ElectronicStructureProblem(driver_reduced, transformers=[transformer]) second_q_ops = WITH_ActiveSpace.second_q_ops() main_op = second_q_ops[0] # particle_number = problem.molecule_data_transformed # num_particles = (particle_number.num_alpha, particle_number.num_beta) # num_spin_orbitals = particle_number.num_molecular_orbitals*2 molecule = driver.run() simulation = QuantumInstance(backend=backend) mapper = JordanWignerMapper() qubit_converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) qubit_op = qubit_converter.convert(main_op, num_particles=2) shots=10 simulation = QuantumInstance(backend=backend) begin = time.time() VQE = VQEUCCFactory(simulation, optimizer=COBYLA(maxiter=shots)) calculation = GroundStateEigensolver(qubit_converter, VQE) result1 = calculation.solve(WITH_ActiveSpace) end = time.time() print(f"Total runtime of the program is {end - begin}") np.real(result1.electronic_energies + result1.nuclear_repulsion_energy)[0]
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
mcoggins96
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ IBMQ.enable_account('Enter API token here') provider = IBMQ.get_provider(hub='ibm-q') q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') circuit = QuantumCircuit(q,c) circuit.x(q[0]) # Pauli x gate applied to first qubit circuit.cx(q[0],q[1]) # CNOT applied to both qubits circuit.measure(q,c) # Qubits states are measured backend = provider.get_backend('ibmq_qasm_simulator') # Specifying qasm simulator as the target device print('Provider: ',backend) print('') job = execute(circuit, backend, shots=1) print('Executing Job...') print('') result = job.result() counts = result.get_counts(circuit) print('RESULT: ',counts) print('') print('Press any key to close') input()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Statevector Sampler.""" from __future__ import annotations import unittest import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import PrimitiveResult, PubResult from qiskit.primitives.containers import BitArray from qiskit.primitives.containers.data_bin import DataBin from qiskit.primitives.containers.sampler_pub import SamplerPub from qiskit.primitives.statevector_sampler import StatevectorSampler from qiskit.providers import JobStatus from test import QiskitTestCase # pylint: disable=wrong-import-order class TestStatevectorSampler(QiskitTestCase): """Test for StatevectorSampler""" def setUp(self): super().setUp() self._shots = 10000 self._seed = 123 self._cases = [] hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) self._cases.append((hadamard, None, {0: 5000, 1: 5000})) # case 0 bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._cases.append((bell, None, {0: 5000, 3: 5000})) # case 1 pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() self._cases.append((pqc, [0] * 6, {0: 10000})) # case 2 self._cases.append((pqc, [1] * 6, {0: 168, 1: 3389, 2: 470, 3: 5973})) # case 3 self._cases.append((pqc, [0, 1, 1, 2, 3, 5], {0: 1339, 1: 3534, 2: 912, 3: 4215})) # case 4 self._cases.append((pqc, [1, 2, 3, 4, 5, 6], {0: 634, 1: 291, 2: 6039, 3: 3036})) # case 5 pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() self._cases.append( (pqc2, [0, 1, 2, 3, 4, 5, 6, 7], {0: 1898, 1: 6864, 2: 928, 3: 311}) ) # case 6 def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol=1e-1): self.assertEqual(bitarray.shape, target.shape) for idx in np.ndindex(bitarray.shape): int_counts = bitarray.get_int_counts(idx) target_counts = ( target.get_int_counts(idx) if isinstance(target, BitArray) else target[idx] ) max_key = max(max(int_counts.keys()), max(target_counts.keys())) ary = np.array([int_counts.get(i, 0) for i in range(max_key + 1)]) tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, err_msg=f"index: {idx}") def test_sampler_run(self): """Test run().""" with self.subTest("single"): bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run( [(pqc, {params: [param_vals, param_vals, param_vals]})], shots=self._shots ) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) def test_sampler_run_multiple_times(self): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result1 = sampler.run([bell], shots=self._shots).result() meas1 = result1[0].data.meas result2 = sampler.run([bell], shots=self._shots).result() meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) def test_sample_run_multiple_circuits(self): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell, bell, bell], shots=self._shots).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target)) self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) def test_sampler_run_with_parameterized_circuits(self): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target1)) self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_single_circuit(self): """Test for single circuit case.""" with self.subTest("No parameter"): circuit, _, target = self._cases[1] param_target = [ (None, np.array(target)), ({}, np.array(target)), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) param_target = [ ({"x": np.pi}, np.array({1: self._shots})), ({param: np.pi}, np.array({1: self._shots})), ({"x": np.array(np.pi)}, np.array({1: self._shots})), ({param: np.array(np.pi)}, np.array({1: self._shots})), ({"x": [np.pi]}, np.array({1: self._shots})), ({param: [np.pi]}, np.array({1: self._shots})), ({"x": np.array([np.pi])}, np.array({1: self._shots})), ({param: np.array([np.pi])}, np.array({1: self._shots})), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, target) with self.subTest("More than one parameter"): circuit, param, target = self._cases[3] param_target = [ (param, np.array(target)), (tuple(param), np.array(target)), (np.array(param), np.array(target)), ((param,), np.array([target])), ([param], np.array([target])), (np.array([param]), np.array([target])), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) # qc({x: 0, y: 0}) self._assert_allclose(result[0].data.c, np.array({1: self._shots})) # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1, 1) with qc3.for_loop(range(5)): qc3.h(0) sampler = StatevectorSampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, [])]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, None)]).result() with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2])]).result() with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2] * 100)]).result() with self.subTest("with control flow"): with self.assertRaises(QiskitError): _ = sampler.run([qc3]).result() with self.subTest("negative shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=-1).result() with self.subTest("negative shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, -1)]).result() with self.subTest("negative shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() with self.subTest("zero shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=0).result() with self.subTest("zero shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, 0)]).result() with self.subTest("zero shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=0)]).result() with self.subTest("missing []"): with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): _ = sampler.run(qc1).result() with self.subTest("missing [] for pqc"): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = StatevectorSampler(seed=self._seed) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, np.array({0: self._shots})) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) params_list = params_array.tolist() sampler = StatevectorSampler(seed=self._seed) target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() self.assertEqual(len(result), k) for i in range(k): self._assert_allclose( result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) def test_run_with_shots_option(self): """test with shots option.""" bell, _, _ = self._cases[1] shots = 100 with self.subTest("run arg"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("default shots"): sampler = StatevectorSampler(seed=self._seed) default_shots = sampler.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("setting default shots"): default_shots = 100 sampler = StatevectorSampler(default_shots=default_shots, seed=self._seed) self.assertEqual(sampler.default_shots, default_shots) result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("pub-like"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("pub"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("multiple pubs"): sampler = StatevectorSampler(seed=self._seed) shots1 = 100 shots2 = 200 result = sampler.run( [ SamplerPub(bell, shots=shots1), SamplerPub(bell, shots=shots2), ], shots=self._shots, ).result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, shots1) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots1) self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) self.assertIn("shots", result[1].metadata) self.assertEqual(result[1].metadata["shots"], shots2) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) def test_primitive_job_status_done(self): """test primitive job's status""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_seed(self): """Test for seed options""" with self.subTest("empty"): sampler = StatevectorSampler() self.assertIsNone(sampler.seed) with self.subTest("set int"): sampler = StatevectorSampler(seed=self._seed) self.assertEqual(sampler.seed, self._seed) with self.subTest("set generator"): sampler = StatevectorSampler(seed=np.random.default_rng(self._seed)) self.assertIsInstance(sampler.seed, np.random.Generator) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" with self.subTest("identity"): gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) with self.subTest("X"): gate = UnitaryGate([[0, 1], [1, 0]]) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) def test_circuit_with_multiple_cregs(self): """Test for circuit with multiple classical registers.""" cases = [] # case 1 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} cases.append(("use all cregs", qc, target)) # case 2 a = ClassicalRegister(1, "a") b = ClassicalRegister(5, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = { "a": {0: 5000, 1: 5000}, "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, "c": {0: 10000}, } cases.append(("use only a and b", qc, target)) # case 3 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure(1, 5) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c", qc, target)) # case 4 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2], [5, 5, 5]) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c multiple qubits", qc, target)) # case 5 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} cases.append(("no measure", qc, target)) for title, qc, target in cases: with self.subTest(title): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg in qc.cregs: self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) def test_circuit_with_aliased_cregs(self): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.ry(np.pi / 4, 2) qc.cx(2, 1) qc.cx(0, 1) qc.h(0) qc.measure(0, c1) qc.measure(1, c2) qc.z(2).c_if(c1, 1) qc.x(2).c_if(c2, 1) qc2 = QuantumCircuit(5, 5) qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) cregs = [creg.name for creg in qc2.cregs] target = { cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc2], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg_name, creg in target.items(): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) def test_no_cregs(self): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) sampler = StatevectorSampler() with self.assertWarns(UserWarning): result = sampler.run([qc]).result() self.assertEqual(len(result), 1) self.assertEqual(len(result[0].data), 0) def test_iter_pub(self): """Test of an iterable of pubs""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler() result = sampler.run(iter([qc, qc2]), shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) if __name__ == "__main__": unittest.main()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc.width() qc.depth() qc.num_qubits qc.count_ops() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.width() qc.qregs qc.qubits qc.num_qubits qc.cregs qc.clbits qc.num_clbits qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(1) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() #Let's apply a barrier gate with no arguments qc=QuantumCircuit(1) qc.h(0) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.barrier() qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.qubits qc.num_qubits qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.count_ops()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
from qiskit import QuantumCircuit from circuit_grid import CircuitGridModel, CircuitGridNode import circuit_node_types as node_types from sympy import pi import logging id_gate = CircuitGridNode(node_types.ID) x_gate = CircuitGridNode(node_types.X, 1) y_gate = CircuitGridNode(node_types.Y, 1) z_gate = CircuitGridNode(node_types.Z, 1) h_gate = CircuitGridNode(node_types.H, 1) s_gate = CircuitGridNode(node_types.S, 1) sdg_gate = CircuitGridNode(node_types.SDG, 1) t_gate = CircuitGridNode(node_types.T, 1) tdg_gate = CircuitGridNode(node_types.TDG, 1) u1_gate = CircuitGridNode(node_types.U1, 1, theta=pi) u2_gate = CircuitGridNode(node_types.U2, 1, theta=pi, phi=pi) u3_gate = CircuitGridNode(node_types.U3, 1, theta=pi, phi=pi, lam=pi) rx_gate = CircuitGridNode(node_types.RX, 1, theta=pi) ry_gate = CircuitGridNode(node_types.RY, 1, theta=pi) rz_gate = CircuitGridNode(node_types.RZ, 1, theta=pi) cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0) cy_gate = CircuitGridNode(node_types.CY, 2, ctrl_a=1) cz_gate = CircuitGridNode(node_types.CZ, 3, ctrl_a=2) ch_gate = CircuitGridNode(node_types.CH, 4, ctrl_a=3) crz_gate = CircuitGridNode(node_types.CRZ, 1, theta=pi, ctrl_a=0) cu1_gate = CircuitGridNode(node_types.CU1, 1, theta=pi, ctrl_a=0) cu3_gate = CircuitGridNode(node_types.CU3, 1, theta=pi, phi=pi, lam=pi, ctrl_a=0) ccx_gate = CircuitGridNode(node_types.CCX, 2, ctrl_a=0, ctrl_b=1) swap_gate = CircuitGridNode(node_types.SWAP, 1, swap=2) cswap_gate = CircuitGridNode(node_types.CSWAP, 1, ctrl_a=0, swap=2) barrier = CircuitGridNode(node_types.BARRIER, 1) measure_z = CircuitGridNode(node_types.MEASURE_Z, 1) reset = CircuitGridNode(node_types.RESET, 1) _if = CircuitGridNode(node_types.IF, 1) gates = [ id_gate, x_gate, y_gate, z_gate, h_gate, s_gate, sdg_gate, t_gate, tdg_gate, u1_gate, u2_gate, u3_gate, rx_gate, ry_gate, rz_gate, cx_gate, cy_gate, cz_gate, ch_gate, crz_gate, cu1_gate, cu3_gate, ccx_gate, swap_gate, cswap_gate, barrier, measure_z, reset, _if ] for gate in gates: print(gate) for gate in gates: print(gate.qasm()) circuit_grid = CircuitGridModel(4,7) print(circuit_grid) print(gates[0]) for j in range(circuit_grid.circuit_depth): for i in range(circuit_grid.qubit_count): circuit_grid.set_node(i,j,gates[j*circuit_grid.qubit_count + i]) print(circuit_grid) qasm_str = circuit_grid.create_qasm_for_circuit() print(qasm_str) qc = QuantumCircuit.from_qasm_str(qasm_str) qc.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit, transpile from qiskit.quantum_info import Kraus, SuperOp from qiskit_aer import AerSimulator from qiskit.tools.visualization import plot_histogram # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError, pauli_error, depolarizing_error, thermal_relaxation_error) # Construct a 1-qubit bit-flip and phase-flip errors p_error = 0.05 bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)]) phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)]) print(bit_flip) print(phase_flip) # Compose two bit-flip and phase-flip errors bitphase_flip = bit_flip.compose(phase_flip) print(bitphase_flip) # Tensor product two bit-flip and phase-flip errors with # bit-flip on qubit-0, phase-flip on qubit-1 error2 = phase_flip.tensor(bit_flip) print(error2) # Convert to Kraus operator bit_flip_kraus = Kraus(bit_flip) print(bit_flip_kraus) # Convert to Superoperator phase_flip_sop = SuperOp(phase_flip) print(phase_flip_sop) # Convert back to a quantum error print(QuantumError(bit_flip_kraus)) # Check conversion is equivalent to original error QuantumError(bit_flip_kraus) == bit_flip # Measurement miss-assignement probabilities p0given1 = 0.1 p1given0 = 0.05 ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]]) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates error = depolarizing_error(0.05, 1) noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3']) # Print noise model info print(noise_model) # Create an empty noise model noise_model = NoiseModel() # Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only error = depolarizing_error(0.05, 1) noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0]) # Print noise model info print(noise_model) # System Specification n_qubits = 4 circ = QuantumCircuit(n_qubits) # Test Circuit circ.h(0) for qubit in range(n_qubits - 1): circ.cx(qubit, qubit + 1) circ.measure_all() print(circ) # Ideal simulator and execution sim_ideal = AerSimulator() result_ideal = sim_ideal.run(circ).result() plot_histogram(result_ideal.get_counts(0)) # Example error probabilities 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"]) print(noise_bit_flip) # Create noisy simulator backend sim_noise = AerSimulator(noise_model=noise_bit_flip) # Transpile circuit for noisy basis gates circ_tnoise = transpile(circ, sim_noise) # Run and get counts result_bit_flip = sim_noise.run(circ_tnoise).result() counts_bit_flip = result_bit_flip.get_counts(0) # Plot noisy output plot_histogram(counts_bit_flip) # T1 and T2 values for qubits 0-3 T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec # Truncate random T2s <= T1s T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)]) # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_reset[j], "reset", [j]) noise_thermal.add_quantum_error(errors_measure[j], "measure", [j]) noise_thermal.add_quantum_error(errors_u1[j], "u1", [j]) noise_thermal.add_quantum_error(errors_u2[j], "u2", [j]) noise_thermal.add_quantum_error(errors_u3[j], "u3", [j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k]) print(noise_thermal) # Run the noisy simulation sim_thermal = AerSimulator(noise_model=noise_thermal) # Transpile circuit for noisy basis gates circ_tthermal = transpile(circ, sim_thermal) # Run and get counts result_thermal = sim_thermal.run(circ_tthermal).result() counts_thermal = result_thermal.get_counts(0) # Plot noisy output plot_histogram(counts_thermal) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import * Aer.backends() IBMQ.load_accounts() IBMQ.backends() from pprint import pprint backend_name = 'ibmqx4' backend = IBMQ.get_backend(backend_name) backend.status() backend.configuration() backend.properties() from qiskit.backends.ibmq import least_busy devices = IBMQ.backends(simulator=False) least_busy_device = least_busy(devices) least_busy_device.status() last_10_jobs = least_busy_device.jobs(limit=10) for j in last_10_jobs: print(j.job_id()) from qiskit.tools.visualization import circuit_drawer qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.tdg(qr[2]) circ.cx(qr[2], qr[1]) circ.x(qr[2]) circ.cx(qr[0], qr[2]) circ.cx(qr[1], qr[3]) circ.measure(qr, cr) circuit_drawer(circ, scale=0.5) %matplotlib inline qiskit.tools.visualization.matplotlib_circuit_drawer(circ) simulator_backend = IBMQ.get_backend(simulator=True, hub=None) job = execute(circ, simulator_backend) import time from qiskit.backends import JobStatus print(job.status()) while job.status() != JobStatus.DONE: time.sleep(1) print(job.status()) qobj = compile(circ, simulator_backend) compiled_circ = qobj_to_circuits(qobj)[0] circuit_drawer(compiled_circ, scale=0.5) qobj.as_dict() job = simulator_backend.run(qobj) result = job.result() import qiskit.wrapper.jupyter %%qiskit_job_status job = execute(circ, backend) %%qiskit_progress_bar qobj = compile(circ, backend) from qiskit import * from qiskit.tools.visualization.interactive import * q = QuantumRegister(5) circ1 = QuantumCircuit(q) circ1.h(q) circ1.ry(1.3, q[0]) circ1.cx(q[0], q[1]) statevector_simulator = Aer.get_backend('statevector_simulator') result = execute(circ1, statevector_simulator).result() psi = result.get_statevector() iplot_state(psi, method='qsphere') # method could be city, paulivec, qsphere, bloch, wigner # Not displayable in github c = ClassicalRegister(5) circ2 = QuantumCircuit(q, c) circ2.h(q) circ2.measure(q, c) circ3 = QuantumCircuit(q, c) circ3.h(q[0]) circ3.y(q[1]) circ3.cx(q[1], q[0]) circ3.measure(q, c) qasm_simulator = Aer.get_backend('qasm_simulator') result = execute([circ2, circ3], qasm_simulator).result() counts_list = [result.get_counts(circ) for circ in [circ2, circ3]] # Needs to be run in Jupyter, will not render on github iplot_histogram(counts_list, legend=['first circuit', 'second circuit']) # Not displayable in github
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u3(pi/2,pi/2,pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.u2(pi/2,pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.u1(pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.u0(pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.iden(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu1(pi/2,q[0], q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu3(pi/2, pi/2, pi/2, q[0], q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = execute(qc, backend) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = execute(qc, backend, shots=1024) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = execute(qc, backend, shots=1024) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = execute(qc, backend, shots=1024) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = execute(qc, backend, shots=1024) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = execute(qc, backend, shots=1024) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw(output='latex') backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state)
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/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Importing QISKit import math, sys from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # Import basic plotting tools from qiskit.tools.visualization import plot_histogram # Import methods to connect with remote backends from qiskit import available_backends, execute, register, get_backend # Import token to use remote backends try: sys.path.append("../../") # go to parent dir import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} except: qx_config = { "APItoken":"YOUR_TOKEN_HERE", "url":"https://quantumexperience.ng.bluemix.net/api"} #to enable sleep import time #connect to remote API to be able to use remote simulators and real devices register(qx_config['APItoken'], qx_config['url']) print("Available backends:", available_backends()) def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) q = QuantumRegister(3) c = ClassicalRegister(3) qft3 = QuantumCircuit(q, c) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) simulate = execute(qft3, backend="local_qasm_simulator", shots=1024).result() simulate.get_counts() backend = "ibmqx4" shots = 1024 if get_backend(backend).status["available"] is True: job_exp = execute(qft3, backend=backend, shots=shots) lapse = 0 interval = 10 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) results = job_exp.result() plot_histogram(results.get_counts())
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
https://github.com/krishphys/LiH_Variational_quantum_eigensolver
krishphys
from qiskit import BasicAer, Aer, IBMQ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, NumPyEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.circuit.library import EfficientSU2 from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError from qiskit.providers.aer.noise.errors import pauli_error from qiskit.providers.aer.noise.errors import depolarizing_error from qiskit.providers.aer.noise.errors import thermal_relaxation_error from qiskit.providers.aer import noise provider = IBMQ.load_account() import numpy as np import matplotlib.pyplot as plt from functools import partial import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) # Classically solve for the lowest eigenvalue # This is used just to compare how well you VQE approximation is performing def exact_solver(qubitOp, shift): ee = NumPyEigensolver(qubitOp) result = ee.run() ref = result['eigenvalues'] ref+= shift print('Reference value: {}'.format(ref)) return ref # Define your function for computing the qubit operations of LiH def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'): # Specify details of our molecule driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis) # Compute relevant 1 and 2 body integrals. molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) #print("# of electrons: {}".format(num_particles)) #print("# of spin orbitals: {}".format(num_spin_orbitals)) # Please be aware that the idx here with respective to original idx freeze_list = [0] remove_list = [-3, -2] # negative number denotes the reverse order # Prepare full idx of freeze_list and remove_list # Convert all negative idx to positive remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] # Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] # Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian # and if PARITY mapping is selected, reduction qubits energy_shift = 0.0 qubit_reduction = True if map_type == 'parity' else False ferOp = FermionicOperator(h1=h1, h2=h2) if len(freeze_list) > 0: ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: ferOp = ferOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = ferOp.mapping(map_type=map_type) qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp qubitOp.chop(10**-10) #Overall energy shift: shift = energy_shift + nuclear_repulsion_energy return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift map_type = 'parity' inter_dist = 1.6 qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , inter_dist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp , shift) # Specify your initial state init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type) # Choose where to run/simulate our circuit quantum_instance = Aer.get_backend('statevector_simulator') # Choose the classical optimizer optimizer = SPSA(max_trials = 1000) # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer) vqe_results = vqe.run(quantum_instance) # Calculating ground ststae energy from vqe results: ground_state_energy = vqe_results['eigenvalue'] + shift print(ground_state_energy) distances = np.arange(0.2 , 5 , 0.1) energies = [] for interdist in distances: qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp , shift) # Specify your initial state init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type) # Choose where to run/simulate our circuit quantum_instance = Aer.get_backend('statevector_simulator') # Choose the classical optimizer optimizer = SPSA(max_trials = 1000) # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer) vqe_results = vqe.run(quantum_instance) # Calculating ground state energy from vqe results: ground_state_energy = vqe_results['eigenvalue'] + shift energies.append(ground_state_energy) plt.plot(distances , energies) plt.title('Bond energy v. interatomic distance') plt.xlabel('Interatomic distance/ Angstroms') plt.ylabel('Energy / Hartrees') def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) map_type = 'parity' inter_dist = 1.6 # Dictionary of optimizers: opt_dict = {'SPSA' , 'SLSQP' , 'COBYLA' , 'L_BFGS_B'} for opt in opt_dict: print('Testing', str(opt) , 'optimizer') qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp , shift) # Specify your initial state init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type) # Choose where to run/simulate our circuit quantum_instance = Aer.get_backend('statevector_simulator') # Choose the classical optimizer if opt == 'SPSA': optimizer = SPSA(max_trials = 500) elif opt == 'SLSQP': optimizer = SLSQP(maxiter = 1000) elif opt == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun = 1000 , maxiter = 1000) elif opt == 'COBYLA': optimizer = COBYLA(maxiter = 1000) counts =[] values =[] params =[] deviation =[] # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer , callback = store_intermediate_result) vqe_results = vqe.run(quantum_instance) #Printing error in final value: ground_state_energy = vqe_results['eigenvalue'] + shift energy_error_ground = np.abs(np.real(ref) - ground_state_energy) print('Error:', str(energy_error_ground)) # Calculating energy error vqe_energies = np.real(values) + shift energy_error = np.abs(np.real(ref) - vqe_energies) plt.plot(counts , energy_error , label=str(opt)) plt.legend() plt.xlabel('Counts') plt.ylabel('Energy Error/ Hartree') plt.title('Energy Convergence of VQE: UCCSD Ansatz') map_type = 'parity' inter_dist = 1.6 # Dictionary of optimizers: opt_dict = {'SPSA' , 'SLSQP' , 'COBYLA' , 'L_BFGS_B'} for opt in opt_dict: print('Testing', str(opt) , 'optimizer') qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist) # Classically solve for the exact solution and use that as your reference value ref = exact_solver(qubitOp , shift) # Specify your initial state init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type) # Select a state preparation ansatz # Equivalently, choose a parameterization for our trial wave function. var_form = EfficientSU2(qubitOp.num_qubits , entanglement='full') # Choose where to run/simulate our circuit quantum_instance = Aer.get_backend('statevector_simulator') # Choose the classical optimizer if opt == 'SPSA': optimizer = SPSA(max_trials = 1000) elif opt == 'SLSQP': optimizer = SLSQP(maxiter = 1000) elif opt == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun = 1000 , maxiter = 1000) elif opt == 'COBYLA': optimizer = COBYLA(maxiter = 1000) counts =[] values =[] params =[] deviation =[] # Run your VQE instance vqe = VQE(qubitOp, var_form, optimizer , callback = store_intermediate_result) vqe_results = vqe.run(quantum_instance) #Printing error in final value: ground_state_energy = vqe_results['eigenvalue'] + shift energy_error_ground = np.abs(np.real(ref) - ground_state_energy) print('Error:', str(energy_error_ground)) # Calculating energy error vqe_energies = np.real(values) + shift energy_error = np.abs(np.real(ref) - vqe_energies) plt.plot(counts , energy_error , label=str(opt)) plt.legend() plt.xlabel('Counts') plt.ylabel('Energy Error/ Hartree') plt.title('Energy Convergence of VQE: RyRz Ansatz')
https://github.com/arnavdas88/QuGlassyIsing
arnavdas88
!pip install qiskit from qiskit.providers.aer import QasmSimulator from qiskit.providers.aer import AerSimulator from qiskit.circuit.library import TwoLocal from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import EfficientSU2 from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance # opflow is Qiskit's module for creating operators like yours from qiskit import * from qiskit.opflow import OperatorBase from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity import pylab import matplotlib.pyplot as plt import numpy as np counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) master_counts = [] master_values = [] for h in range (1,5,1): h=+h print(h) # or whatever value you have for h H = - h * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) # you can swap this for a real quantum device and keep the rest of the code the same! backend = QasmSimulator() # COBYLA usually works well for small problems like this one optimizer = COBYLA(maxiter=200) # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library ansatz = EfficientSU2(4, reps=1) # set the algorithm vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result) # run it with the Hamiltonian we defined above result = vqe.compute_minimum_eigenvalue(H) # print the result (it contains lot's of information) print(result) master_counts = [] master_values = [] for h in range (1,5,1): counts = [] values = [] result = vqe.compute_minimum_eigenvalue(H) master_counts.append(counts) master_values.append(values) plt.figure(figsize=(15,15)) plt.plot(master_counts[0],master_values[0]) plt.plot(master_counts[1],master_values[1]) plt.plot(master_counts[2],master_values[2]) plt.plot(master_counts[3],master_values[3]) plt.xlabel('optimization step') plt.ylabel('E') plt.legend(['h=1', 'h=2', 'h=3', 'h=4'], loc='upper right') plt.show() def HamiltonianPreparation(num_of_qubits:int): identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)] for i in range(num_of_qubits): identity_list[i][i] = 'X' hamiltonian_string = "" # for i in range(len): # for j in range(i): # hamiltonian = hamiltonian for row in identity_list: hamiltonian_string += " ( " for j in range(len(row)): if j < len(row) - 1: hamiltonian_string += row[j] + " ^ " else: hamiltonian_string += row[j] hamiltonian_string += " ) + " hamiltonian_string = hamiltonian_string[0:-3] return hamiltonian_string def HamiltonianPreparation_J(num_of_qubits:int): identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)] for i in range(num_of_qubits): if i!=num_of_qubits-1: identity_list[i][i] = 'Z' identity_list[i][i+1] = 'Z' else: identity_list[i][i] = 'Z' identity_list[i][0] = 'Z' hamiltonian_string = "" # for i in range(len): # for j in range(i): # hamiltonian = hamiltonian for row in identity_list: hamiltonian_string += "( " for j in range(len(row)): if j < len(row) - 1: hamiltonian_string += row[j] + " ^ " else: hamiltonian_string += row[j] hamiltonian_string += ") + " hamiltonian_string = hamiltonian_string[0:-3] return hamiltonian_string def HamiltonianPreparation_bz(num_of_qubits:int): identity_list = [['I' for i in range(num_of_qubits)] for j in range(num_of_qubits)] for i in range(num_of_qubits): identity_list[i][i] = 'Z' hamiltonian_string = "" # for i in range(len): # for j in range(i): # hamiltonian = hamiltonian for row in identity_list: hamiltonian_string += "( " for j in range(len(row)): if j < len(row) - 1: hamiltonian_string += row[j] + " ^ " else: hamiltonian_string += row[j] hamiltonian_string += " ) + " hamiltonian_string = hamiltonian_string[0:-3] return hamiltonian_string print(HamiltonianPreparation(36)) H = - B_Z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z) ) + J_z * ((( Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ Z) + ( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z))) - B_X * (( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X) ) master_counts = [] master_values = [] h = 1 # or whatever value you have for h H = - h * ((X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I) + (I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X)) # you can swap this for a real quantum device and keep the rest of the code the same! backend = AerSimulator(method='matrix_product_state') # COBYLA usually works well for small problems like this one optimizer = COBYLA(maxiter=200) # EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library ansatz = TwoLocal(num_qubits=50, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) # set the algorithm vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result) # run it with the Hamiltonian we defined above result = vqe.compute_minimum_eigenvalue(H) # print the result (it contains lot's of information) # print(result) print(result) counts import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) print(X) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) # A StrMethodFormatter is used automatically ax.zaxis.set_major_formatter('{x:.02f}') # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() import numpy as np from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.aqua.operators import * from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver from qiskit.circuit import QuantumCircuit, ParameterVector # pauli_terms = ['IIIIIIIZ', 'IIIIIIZI', 'IIIIIZII' ] # pauli_weights = [504.0, 1008.0, 2016.0] # pauli_dict = {'paulis': [{"coeff": {"imag": 0., "real": pauli_weights[i] }, "label": pauli_terms[i]} \ # for i in range(len(pauli_terms))]} Hamiltonian = - 1 * ((X ^ I ^ I ^ I) + (I ^ X ^ I ^ I) + (I ^ I ^ X ^ I) + (I ^ I ^ I ^ X)) ansatz = TwoLocal(num_qubits=4, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True) print(ansatz) backend = QasmSimulator() quantum_instance = QuantumInstance(backend, shots = 8192, initial_layout = None, optimization_level = 3) optimizer = COBYLA(maxiter= 100, tol=0.000000001) vqe = VQE(Hamiltonian, ansatz, optimizer, initial_point= None , include_custom = False) print('We are using:', quantum_instance.backend) vqe_result = vqe.run(quantum_instance) vqe_result['eigenstate'] from qiskit.visualization import plot_histogram plot_histogram(vqe_result['eigenstate'])
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/fvarchon/qiskit-intros
fvarchon
from qiskit import execute from qiskit import transpiler help(execute) from qiskit import Aer, BasicAer backend = Aer.get_backend("qasm_simulator") help(backend) backend = BasicAer.get_backend("qasm_simulator") help(backend)
https://github.com/iamr0b0tx/qiskit_practice
iamr0b0tx
import qiskit
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import numpy as np import matplotlib.pyplot as plt # from qiskit import BasicAer, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, Aer, transpile from qiskit.tools.visualization import plot_histogram import pandas as pd from fractions import Fraction from shor_algo_adder_method import shor_circiut import bit_functions N = 15 a = 13 N_COUNT = 2*bit_functions.bit_length(N) qc = shor_circiut(N, a) qc.draw('mpl', fold = -1) aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) # counts = execute(t_qc, aer_sim).result().get_counts() counts = aer_sim.run(t_qc).result().get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**N_COUNT) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**N_COUNT} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) guesses = {x[2] for x in rows if x[2] != 1} for curr_gess in guesses: if curr_gess % 2 == 0: num1 = int(a**(curr_gess/2)+1) num2 = int(a**(curr_gess/2)-1) q = np.gcd(num1, N) p = np.gcd(num2, N) print(f"for r = {curr_gess} factors are: {p}, {q}")
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.opflow import X, Z, I, Y import numpy as np QUBITS_NUM = 3 def create_pauli_string_with_pauli_op_on_index_i(pauli_op, i, qubits_num): if i == 1: pauli_string = pauli_op for qubit in range(qubits_num - 1): pauli_string = pauli_string ^ I return pauli_string pauli_string = I for qubit in range(2, qubits_num + 1): if qubit == i: pauli_string = pauli_string ^ pauli_op else: pauli_string = pauli_string ^ I return pauli_string def create_pauli_string_with_pauli_ops_on_index_i_and_j(pauli_op_second, i, pauli_op_first, j, qubits_num): if j == 1: pauli_string = pauli_op_first for qubit in range(2, qubits_num + 1): if qubit == i: pauli_string = pauli_string ^ pauli_op_second else: pauli_string = pauli_string ^ I return pauli_string pauli_string = I for qubit in range(2, qubits_num + 1): if qubit == j: pauli_string = pauli_string ^ pauli_op_first elif qubit == i: pauli_string = pauli_string ^ pauli_op_second else: pauli_string = pauli_string ^ I return pauli_string def get_Ising_model_hamiltonian(): hamiltonian = I for qubit in range(QUBITS_NUM - 1): hamiltonian = hamiltonian^I hamiltonian = 0 * hamiltonian for i in range(1, QUBITS_NUM + 1): a_i = np.random.random_sample() x_i = create_pauli_string_with_pauli_op_on_index_i(X, i, QUBITS_NUM) hamiltonian = hamiltonian + a_i * x_i for j in range(1, i): J_ij = np.random.random_sample() z_ij = create_pauli_string_with_pauli_ops_on_index_i_and_j(Z, i, Z, j, QUBITS_NUM) hamiltonian = hamiltonian + J_ij * z_ij return hamiltonian transverse_ising_3_qubits = get_Ising_model_hamiltonian() print(transverse_ising_3_qubits) from qiskit.opflow import X, Z, I H2_molecule_hamiltonian = 0.0 * (I^I^I) + 0.012764169333459807 * (X^I^I) + 0.7691573729160869 * (I^X^I) + 0.398094746026449 * (Z^Z^I) + 0.15250261906586637 * (I^I^X) + 0.2094051920882264 * (Z^I^Z) + 0.5131291860752999 * (I^Z^Z)
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
# Playing with models from qiskit.aqua.algorithms import VQC from qiskit.aqua.components.optimizers import SPSA import matplotlib.pyplot as plt import matplotlib.patches as mpatches from qiskit.ml.datasets import ad_hoc_data, wine # Data to play with # ad_hoc_data - returns ad hoc dataset - ad_hoc_data(training_size, test_size, n, gap, plot_data=False) # sample_ad_hoc_data - returns sample ad hoc data # breast_cancer - returns breast cancer dataset # digits - returns digits dataset # gaussian - returns gaussian dataset # iris - returns iris dataset # wine - returns wine dataset - wine(training_size, test_size, n, plot_data=False) _, training_data, test_data, _ = ad_hoc_data(10, 10, 2, 0.2) markers = ['o', '^'] plt.figure(figsize=(12,6)) plt.title('Training (full) and test (hollow) data') for marker, (label, data) in zip(markers, training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) for marker, (label, data) in zip(markers, test_data.items()): plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker) plt.legend(loc='best'); _, wine_training_data, wine_data, _ = wine(20, 20, 3) markers = ['o', '^'] plt.figure(figsize=(12,6)) plt.title('Training (full) and test (hollow) data') for marker, (label, data) in zip(markers, wine_training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) for marker, (label, data) in zip(markers, wine_data.items()): plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker) plt.legend(loc='best'); # Choose which trainint data test_data = wine_data training_data = wine_training_data from qiskit.circuit.library.data_preparation import ZZFeatureMap # can also drop .data_preparation data_preparation = ZZFeatureMap(2) data_preparation.draw(output='mpl') from qiskit.circuit.library.n_local import RealAmplitudes # can also drop .n_local classifier = RealAmplitudes(2) classifier.draw(output='mpl') optimizer = SPSA(max_trials=200) vqc = VQC(optimizer, data_preparation, classifier, training_data) from qiskit import Aer from qiskit.aqua import QuantumInstance backend = Aer.get_backend('qasm_simulator') result = vqc.run(backend) print('Loss:', result['training_loss']) points_a = test_data['A'] points_b = test_data['B'] _, predicted_a = vqc.predict(points_a) _, predicted_b = vqc.predict(points_b) print('Score:', sum(predicted_a == 0) + sum(predicted_b == 1), '/', (len(predicted_a) + len(predicted_b))) plt.figure(figsize=(12,6)) plt.title('Correctly predicted') plt.scatter(points_a[:,0], points_a[:,1], s=60, marker='o', color=['tab:green' if label == 0 else 'tab:red' for label in predicted_a]) plt.scatter(points_b[:,0], points_b[:,1], s=60, marker='^', color=['tab:green' if label == 1 else 'tab:red' for label in predicted_b]) for marker, (label, data) in zip(markers, training_data.items()): plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker) train = mpatches.Patch(color='tab:blue', label='training data') correct = mpatches.Patch(color='tab:green', label='correctly labeled') wrong = mpatches.Patch(color='tab:red', label='wrongly labeled') plt.legend(handles=[train, correct, wrong])
https://github.com/apcarrik/qiskit-dev
apcarrik
import numpy as np import pylab from qiskit import Aer from qiskit.opflow import X, Z, I from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.algorithms import VQE, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal # Create qubit operator of H2 molecule H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) # Show callback usage over set of optimizers optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)] converge_cnts = 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(ansatz, optimizer, callback=store_intermediate_result, quantum_instance= QuantumInstance( backend=Aer.get_backend('statevector_simulator') )) result = vqe.compute_minimum_eigenvalue(operator=H2_op) converge_cnts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print('\rOptimization complete ') # plot energy value at each objective funciton call each optimizer makes pylab.rcParams['figure.figsize'] = (12,8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_cnts[i], converge_vals[i], label=type(optimizer).__name__) pylab.xlabel('Eval count') pylab.ylabel('Energy') pylab.title('Energy convergence for variaous optimizers') pylab.legend(loc='upper right') pylab.show() # Run classical algorithm to obtain reference solution npme = NumPyMinimumEigensolver() result = npme.compute_minimum_eigenvalue(operator=H2_op) ref_value = result.eigenvalue.real print(f'Reference value: {ref_value:.5f}') # Plot difference from reference solution to optimizations pylab.rcParams['figure.figsize'] = (12,8) for i, optimizer in enumerate(optimizers): pylab.plot(converge_cnts[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') pylab.show() ### Using Gradient framework from qiskit.opflow.gradients import Gradient algorithm_globals.random_seed = 50 ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz') optimizer = SLSQP(maxiter=60) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) vqe = VQE(ansatz, optimizer, callback=store_intermediate_result, gradient=Gradient(grad_method='fin_diff'), quantum_instance=QuantumInstance( backend=Aer.get_backend('statevector_simulator') )) 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') pylab.show()
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the LayoutTransformation pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.converters import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.transpiler import CouplingMap, Layout, Target from qiskit.circuit.library import CXGate from qiskit.transpiler.passes import LayoutTransformation class TestLayoutTransformation(QiskitTestCase): """ Tests the LayoutTransformation pass. """ def test_three_qubit(self): """Test if the permutation {0->2,1->0,2->1} is implemented correctly.""" v = QuantumRegister(3, "v") # virtual qubits coupling = CouplingMap([[0, 1], [1, 2]]) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2}) to_layout = Layout({v[0]: 2, v[1]: 0, v[2]: 1}) ltpass = LayoutTransformation( coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(3) dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(3) expected.swap(1, 0) expected.swap(1, 2) self.assertEqual(circuit_to_dag(expected), output_dag) def test_four_qubit(self): """Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly.""" v = QuantumRegister(4, "v") # virtual qubits coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation( coupling_map=coupling, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(1, 2) expected.swap(2, 3) self.assertEqual(circuit_to_dag(expected), output_dag) def test_four_qubit_with_target(self): """Test if the permutation {0->3,1->0,2->1,3->2} is implemented correctly.""" v = QuantumRegister(4, "v") # virtual qubits target = Target() target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (2, 3): None}) from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation(target, from_layout=from_layout, to_layout=to_layout, seed=42) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(1, 2) expected.swap(2, 3) self.assertEqual(circuit_to_dag(expected), output_dag) @unittest.skip("rustworkx token_swapper produces correct, but sometimes random output") def test_full_connected_coupling_map(self): """Test if the permutation {0->3,1->0,2->1,3->2} in a fully connected map.""" # TODO: Remove skip when https://github.com/Qiskit/rustworkx/pull/897 is # merged and released. Should be rustworkx 0.13.1. v = QuantumRegister(4, "v") # virtual qubits from_layout = Layout({v[0]: 0, v[1]: 1, v[2]: 2, v[3]: 3}) to_layout = Layout({v[0]: 3, v[1]: 0, v[2]: 1, v[3]: 2}) ltpass = LayoutTransformation( coupling_map=None, from_layout=from_layout, to_layout=to_layout, seed=42 ) qc = QuantumCircuit(4) # input (empty) physical circuit dag = circuit_to_dag(qc) output_dag = ltpass.run(dag) expected = QuantumCircuit(4) expected.swap(1, 0) expected.swap(2, 1) expected.swap(3, 2) self.assertEqual(circuit_to_dag(expected), output_dag) if __name__ == "__main__": unittest.main()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Example showing how to use Qiskit-Terra at level 0 (novice). This example shows the most basic way to user Terra. It builds some circuits and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider). To control the compile parameters we have provided a transpile function which can be used as a level 1 user. """ # Import the Qiskit modules from qiskit import QuantumCircuit from qiskit import execute, BasicAer # making first circuit: bell state qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure([0, 1], [0, 1]) # making another circuit: superpositions qc2 = QuantumCircuit(2, 2) qc2.h([0, 1]) qc2.measure([0, 1], [0, 1]) # setting up the backend print("(BasicAER Backends)") print(BasicAer.backends()) # running the job job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator")) sim_result = job_sim.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2))
https://github.com/mberna/qce22-qiskit-runtime-tutorial
mberna
# instantiate runtime service from qiskit_ibm_runtime import QiskitRuntimeService QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN") service = QiskitRuntimeService(channel="ibm_quantum") # import required libraries and instantiate runtime service from qiskit_ibm_runtime import Session, Estimator, Options from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import SparsePauliOp # create circuits and observables psi1 = RealAmplitudes(num_qubits=2, reps=2) psi2 = RealAmplitudes(num_qubits=2, reps=3) H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)]) H2 = SparsePauliOp.from_list([("IZ", 1)]) H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)]) psi1.decompose().draw(output='mpl') psi2.decompose().draw(output='mpl') import numpy as np # generate random theta params np.random.seed(0) theta1 = np.random.rand(6) * np.pi theta2 = np.random.rand(8) * np.pi theta3 = np.random.rand(6) * np.pi print(theta1) print(theta2) print(theta3) with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session) from qiskit_ibm_runtime import Options options = Options(optimization_level=1) options.execution.shots = 1024 with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session, options=options) # calculate [ <psi1(theta1)|H1|psi1(theta1)> ] psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1]) print(psi1_H1.result()) # You can invoke run() multiple times! # calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ] psi1_H23 = estimator.run(circuits=[psi1, psi1], observables=[H2, H3], parameter_values=[theta1]*2) print(psi1_H23.result()) # Ex. 1: Calculate [ <psi2(theta2)|H2|psi2(theta2)> ] # psi2_H2 = ... # Ex. 2 calculate [ <psi1(theta1)|H1|psi1(theta1)>, # <psi2(theta2)|H2|psi2(theta2)>, # <psi1(theta3)|H3|psi1(theta3)> ] # psi12_H23 = ... # Ex. 3: use optimization_level 3 options = Options() # options... # hint: use autocomplete with Session(service=service, backend="ibmq_qasm_simulator") as session: estimator = Estimator(session=session, options=options) theta4 = [0, 1, 1, 2, 3, 5] # calculate [ <psi1(theta1)|H1|psi1(theta1)> ] psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4]) print(psi1_H1.result()) # Ex. 4: Apply REM to the following example # Remeber REM is enabled when resilience level is 1 options = Options() # options... # hint: use autocomplete with Session(service=service, backend="ibmq_qasm_simulator",) as session: estimator = Estimator(session=session, options=options) theta4 = [0, 1, 1, 2, 3, 5] psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4]) print(psi1_H1.result()) from qiskit import QuantumCircuit from qiskit_ibm_runtime import Sampler bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() with Session(service=service, backend="ibmq_qasm_simulator") as session: sampler = Sampler(session=session, options=options) job = sampler.run(circuits=bell) print(job.result()) # You can invoke run() multiple times. job = sampler.run(circuits=bell) print(job.result()) ## REM sampler from qiskit import QuantumCircuit from qiskit_ibm_runtime import Sampler, Options, Session bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() options_rem = Options(resilience_level=1) with Session(service=service, backend="ibmq_qasm_simulator") as session: sampler = Sampler(session=session) job = sampler.run(circuits=bell) sampler_rem = Sampler(session=session, options=options_rem) job_rem = sampler_rem.run(circuits=bell) print(f"Quasi_dist without EM {job.result().quasi_dists}") print(f"Quasi_dist with EM {job_rem.result().quasi_dists}")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Create circuit to test transpiler on from qiskit import QuantumCircuit from qiskit.circuit.library import GroverOperator, Diagonal oracle = Diagonal([1]*7 + [-1]) qc = QuantumCircuit(3) qc.h([0,1,2]) qc = qc.compose(GroverOperator(oracle)) # Use Statevector object to calculate the ideal output from qiskit.quantum_info import Statevector ideal_distribution = Statevector.from_instruction(qc).probabilities_dict() from qiskit.visualization import plot_histogram plot_histogram(ideal_distribution) from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService() backend = service.backend('ibm_algiers') # Need to add measurements to the circuit qc.measure_all() from qiskit import transpile circuits = [] for optimization_level in [0, 3]: t_qc = transpile(qc, backend, optimization_level=optimization_level, seed_transpiler=0) print(f'CNOTs (optimization_level={optimization_level}): ', t_qc.count_ops()['cx']) circuits.append(t_qc) from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling from qiskit.circuit.library import XGate # Get gate durations so the transpiler knows how long each operation takes durations = InstructionDurations.from_backend(backend) # This is the sequence we'll apply to idling qubits dd_sequence = [XGate(), XGate()] # Run scheduling and dynamic decoupling passes on circuit pm = PassManager([ASAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)] ) circ_dd = pm.run(circuits[1]) # Add this new circuit to our list circuits.append(circ_dd) from qiskit_ibm_runtime import Sampler, Session with Session(service=service, backend=backend): sampler = Sampler() job = sampler.run( circuits=circuits, # sample all three circuits skip_transpilation=True, shots=8000) result = job.result() from qiskit.visualization import plot_histogram binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists] plot_histogram(binary_prob+[ideal_distribution], bar_labels=False, legend=['optimization_level=0', 'optimization_level=3', 'optimization_level=3 + dd', 'ideal distribution']) from qiskit.quantum_info import hellinger_fidelity for counts in result.quasi_dists: print( f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}" ) import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() from qiskit.tools.jupyter import * %qiskit_version_table %qiskit_copyright
https://github.com/Advanced-Research-Centre/QPULBA
Advanced-Research-Centre
from qiskit import QuantumCircuit circ = QuantumCircuit(1) import numpy as np # circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1]) circ.ry(np.pi/2,0) from qiskit import Aer, execute simulator = Aer.get_backend('statevector_simulator') sim_res = execute(circ, simulator).result() statevector = sim_res.get_statevector(circ) for i in statevector: print(i)
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from qiskit.transpiler import CouplingMap t = CouplingMap.from_heavy_hex(5) t.size() from transpile_benchy.library import CircuitLibrary from qiskit import transpile from mirror_gates.sqiswap_equiv import sel lib = CircuitLibrary.from_txt("medium_circuits.txt") for circuit in lib: # qc = transpile(circuit, basis_gates=["u", "xx_plus_yy"], optimization_level=0) # print(qc.count_ops()["cx"]) # save the qasm file circuit.qasm(filename=circuit.name + ".qasm") # qc.draw("mpl") # circuit.decompose().decompose().draw("mpl") from transpile_benchy.library import CircuitLibrary lib = CircuitLibrary(circuit_list=[]) for interface in lib.interfaces: print(interface.__class__.__name__) for circuit in interface.circuits: print(circuit) print() lib = CircuitLibrary.from_txt("medium_circuits.txt")
https://github.com/Qiskit/feedback
Qiskit
import pprint import numpy as np import qiskit from qiskit.transpiler import StagedPassManager, PassManager from qiskit.transpiler.passes import * from qiskit.transpiler import CouplingMap from qiskit.transpiler.preset_passmanagers import common from qiskit.circuit import QuantumCircuit # Only available starting with Qiskit 0.21.0 print(qiskit.__version__) default_staged_pm = StagedPassManager() print(default_staged_pm.stages) staged_pm = StagedPassManager(stages=['layout', 'translate']) print(staged_pm.stages) cmap = CouplingMap.from_heavy_hex(11) layout_stage = PassManager([VF2Layout(cmap, call_limit=int(5e9))]) layout_stage += common.generate_embed_passmanager(cmap) translation_stage = common.generate_translation_passmanager(None, ['u', 'cx']) staged_pm = StagedPassManager(stages=['layout', 'translate'], layout=layout_stage) staged_pm.translate = translation_stage staged_pm.draw() staged_pm.pre_layout = common.generate_unroll_3q(None, ['u', 'cx']) staged_pm.post_layout = common.generate_pre_op_passmanager(coupling_map=cmap) staged_pm.pre_translate = PassManager(Depth()) staged_pm.translate.append(Size()) staged_pm.draw() from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.providers.fake_provider import FakeGuadalupeV2 from qiskit.circuit.library import XGate, HGate, RXGate, PhaseGate, TGate, TdgGate backend = FakeGuadalupeV2() opt_level_1_pm = generate_preset_pass_manager(1, backend) print(type(opt_level_1_pm)) opt_level_1_pm.draw() circuit = QuantumCircuit(4) circuit.h(0) circuit.cx(0, 1) circuit.cx(0, 1) circuit.cx(0, 1) circuit.cx(0, 2) circuit.cx(0, 3) circuit.measure_all() circuit.draw('mpl') opt_level_1_pm.run(circuit).draw('mpl') backend_durations = backend.target.durations() dd_sequence = [XGate(), XGate()] scheduling_pm = PassManager([ ALAPScheduleAnalysis(backend_durations), PadDynamicalDecoupling(backend_durations, dd_sequence), ]) inverse_gate_list = [ HGate(), (RXGate(np.pi / 4), RXGate(-np.pi / 4)), (PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4)), (TGate(), TdgGate()), ] logical_opt = PassManager([ CXCancellation(), InverseCancellation([HGate(), (RXGate(np.pi / 4), RXGate(-np.pi / 4))]) ]) opt_level_1_pm.scheduling = scheduling_pm opt_level_1_pm.pre_layout = logical_opt opt_level_1_pm.draw() opt_level_1_pm.run(circuit).draw('mpl') from qiskit.converters import dag_to_circuit def callback(**kwargs): print(kwargs['pass_']) intermediate_circuit = dag_to_circuit(kwargs['dag']) intermediate_circuit.name = 'After:' +str(kwargs['pass_']) display(intermediate_circuit.draw('mpl')) opt_level_1_pm.run(circuit, callback=callback)
https://github.com/sebasmos/QuantumVE
sebasmos
import numpy as np import matplotlib.pyplot as plt def initial_state(num_positions): return np.ones(num_positions) / num_positions def predict_state(prior_prob, velocity): num_positions = len(prior_prob) predicted_prob = np.zeros(num_positions) for i in range(num_positions): predicted_prob[i] = prior_prob[(i - velocity) % num_positions] return predicted_prob def update_state(predicted_prob, observation, observation_noise): likelihood = np.exp(-0.5 * ((np.arange(len(predicted_prob)) - observation) / observation_noise)**2) posterior_prob = likelihood * predicted_prob posterior_prob /= np.sum(posterior_prob) # Normalize return posterior_prob # Simulation parameters num_positions = 100 velocity = 1 observation_noise = 10 num_steps = 50 # Initialize true_positions = np.zeros(num_steps) observations = np.zeros(num_steps) prior_prob = initial_state(num_positions) # Test initial state init_state_2 = np.zeros(num_positions) init_state_2[int(num_positions/2)] = 1 print(init_state_2) p_plus = predict_state(init_state_2, 1) print(p_plus) # Initialize true_positions = np.zeros(num_steps) observations = np.zeros(num_steps) estimated_positions = np.zeros(num_steps) # Store estimated positions # Run the Bayesian update cycle for step in range(num_steps): # True target position update (constant velocity) true_positions[step] = step * velocity # Generate noisy observation observations[step] = true_positions[step] + np.random.normal(0, observation_noise) # Bayesian prediction predicted_prob = predict_state(prior_prob, velocity) # Bayesian update prior_prob = update_state(predicted_prob, observations[step], observation_noise) # Calculate Metrics mse = np.mean((true_positions - estimated_positions) ** 2) # Symmetric Mean Absolute Percentage Error (SMAPE) smape_numerator = 2 * np.abs(estimated_positions - true_positions) smape_denominator = np.abs(estimated_positions) + np.abs(true_positions) smape = np.mean(np.nan_to_num(smape_numerator / smape_denominator)) # Mean Absolute Percentage Error (MAPE) mape_numerator = np.abs(estimated_positions - true_positions) mape_denominator = np.abs(true_positions) mape = np.mean(np.nan_to_num(mape_numerator / mape_denominator)) * 100 r2 = 1 - np.sum((true_positions - estimated_positions) ** 2) / np.sum((true_positions - np.mean(true_positions)) ** 2) mae = np.mean(np.abs(true_positions - estimated_positions)) # Print Metrics print("Mean Squared Error (MSE):", mse) print("Symmetric Mean Absolute Percentage Error (SMAPE):", smape) print("Mean Absolute Percentage Error (MAPE):", mape) print("R-squared (R2):", r2) print("Mean Absolute Error (MAE):", mae) # Plot the results plt.figure(figsize=(12, 6)) plt.plot(np.arange(num_positions), prior_prob, label='Posterior Distribution') plt.scatter(true_positions, np.ones_like(true_positions) * 0.01, color='r', marker='x', label='True Positions') plt.scatter(observations, np.ones_like(observations) * 0.01, color='g', marker='o', label='Noisy Observations') plt.title('Bayesian Multi-Target Tracking') plt.xlabel('Position') plt.ylabel('Probability') plt.legend() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Solovay Kitaev transpilation pass.""" import unittest import math import numpy as np import scipy from ddt import ddt, data from qiskit.test import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import TGate, TdgGate, HGate, SGate, SdgGate, IGate, QFT from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.synthesis.discrete_basis.generate_basis_approximations import ( generate_basic_approximations, ) from qiskit.synthesis.discrete_basis.commutator_decompose import commutator_decompose from qiskit.synthesis.discrete_basis.gate_sequence import GateSequence from qiskit.transpiler import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import UnitarySynthesis, Collect1qRuns, ConsolidateBlocks from qiskit.transpiler.passes.synthesis import SolovayKitaev, SolovayKitaevSynthesis def _trace_distance(circuit1, circuit2): """Return the trace distance of the two input circuits.""" op1, op2 = Operator(circuit1), Operator(circuit2) return 0.5 * np.trace(scipy.linalg.sqrtm(np.conj(op1 - op2).T.dot(op1 - op2))).real def _generate_x_rotation(angle: float) -> np.ndarray: return np.array( [[1, 0, 0], [0, math.cos(angle), -math.sin(angle)], [0, math.sin(angle), math.cos(angle)]] ) def _generate_y_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), 0, math.sin(angle)], [0, 1, 0], [-math.sin(angle), 0, math.cos(angle)]] ) def _generate_z_rotation(angle: float) -> np.ndarray: return np.array( [[math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1]] ) def is_so3_matrix(array: np.ndarray) -> bool: """Check if the input array is a SO(3) matrix.""" if array.shape != (3, 3): return False if abs(np.linalg.det(array) - 1.0) > 1e-10: return False if False in np.isreal(array): return False return True @ddt class TestSolovayKitaev(QiskitTestCase): """Test the Solovay Kitaev algorithm and transformation pass.""" def setUp(self): super().setUp() self.basic_approx = generate_basic_approximations([HGate(), TGate(), TdgGate()], 3) def test_unitary_synthesis(self): """Test the unitary synthesis transpiler pass with Solovay-Kitaev.""" circuit = QuantumCircuit(2) circuit.rx(0.8, 0) circuit.cx(0, 1) circuit.x(1) _1q = Collect1qRuns() _cons = ConsolidateBlocks() _synth = UnitarySynthesis(["h", "s"], method="sk") passes = PassManager([_1q, _cons, _synth]) compiled = passes.run(circuit) diff = np.linalg.norm(Operator(compiled) - Operator(circuit)) self.assertLess(diff, 1) self.assertEqual(set(compiled.count_ops().keys()), {"h", "s", "cx"}) def test_plugin(self): """Test calling the plugin directly.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data plugin = SolovayKitaevSynthesis() out = plugin.run(unitary, basis_gates=["h", "s"]) reference = QuantumCircuit(1, global_phase=3 * np.pi / 4) reference.h(0) reference.s(0) reference.h(0) self.assertEqual(dag_to_circuit(out), reference) def test_generating_default_approximation(self): """Test the approximation set is generated by default.""" skd = SolovayKitaev() circuit = QuantumCircuit(1) dummy = skd(circuit) self.assertIsNotNone(skd._sk.basic_approximations) def test_i_returns_empty_circuit(self): """Test that ``SolovayKitaev`` returns an empty circuit when it approximates the I-gate.""" circuit = QuantumCircuit(1) circuit.i(0) skd = SolovayKitaev(3, self.basic_approx) decomposed_circuit = skd(circuit) self.assertEqual(QuantumCircuit(1), decomposed_circuit) def test_exact_decomposition_acts_trivially(self): """Test that the a circuit that can be represented exactly is represented exactly.""" circuit = QuantumCircuit(1) circuit.t(0) circuit.h(0) circuit.tdg(0) synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) decomposed_dag = synth.run(dag) decomposed_circuit = dag_to_circuit(decomposed_dag) self.assertEqual(circuit, decomposed_circuit) def test_fails_with_no_to_matrix(self): """Test failer if gate does not have to_matrix.""" circuit = QuantumCircuit(1) circuit.initialize("0") synth = SolovayKitaev(3, self.basic_approx) dag = circuit_to_dag(circuit) with self.assertRaises(TranspilerError) as cm: _ = synth.run(dag) self.assertEqual( "SolovayKitaev does not support gate without to_matrix method: initialize", cm.exception.message, ) def test_str_basis_gates(self): """Test specifying the basis gates by string works.""" circuit = QuantumCircuit(1) circuit.rx(0.8, 0) basic_approx = generate_basic_approximations(["h", "t", "s"], 3) synth = SolovayKitaev(2, basic_approx) dag = circuit_to_dag(circuit) discretized = dag_to_circuit(synth.run(dag)) reference = QuantumCircuit(1, global_phase=7 * np.pi / 8) reference.h(0) reference.t(0) reference.h(0) self.assertEqual(discretized, reference) def test_approximation_on_qft(self): """Test the Solovay-Kitaev decomposition on the QFT circuit.""" qft = QFT(3) transpiled = transpile(qft, basis_gates=["u", "cx"], optimization_level=1) skd = SolovayKitaev(1) with self.subTest("1 recursion"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 15) skd.recursion_degree = 2 with self.subTest("2 recursions"): discretized = skd(transpiled) self.assertLess(_trace_distance(transpiled, discretized), 7) def test_u_gates_work(self): """Test SK works on Qiskit's UGate. Regression test of Qiskit/qiskit-terra#9437. """ circuit = QuantumCircuit(1) circuit.u(np.pi / 2, -np.pi, -np.pi, 0) circuit.u(np.pi / 2, np.pi / 2, -np.pi, 0) circuit.u(-np.pi / 4, 0, -np.pi / 2, 0) circuit.u(np.pi / 4, -np.pi / 16, 0, 0) circuit.u(0, 0, np.pi / 16, 0) circuit.u(0, np.pi / 4, np.pi / 4, 0) circuit.u(np.pi / 2, 0, -15 * np.pi / 16, 0) circuit.p(-np.pi / 4, 0) circuit.p(np.pi / 4, 0) circuit.u(np.pi / 2, 0, -3 * np.pi / 4, 0) circuit.u(0, 0, -np.pi / 16, 0) circuit.u(np.pi / 2, 0, 15 * np.pi / 16, 0) depth = 4 basis_gates = ["h", "t", "tdg", "s", "z"] gate_approx_library = generate_basic_approximations(basis_gates=basis_gates, depth=depth) skd = SolovayKitaev(recursion_degree=2, basic_approximations=gate_approx_library) discretized = skd(circuit) included_gates = set(discretized.count_ops().keys()) self.assertEqual(set(basis_gates), included_gates) @ddt class TestGateSequence(QiskitTestCase): """Test the ``GateSequence`` class.""" def test_append(self): """Test append.""" seq = GateSequence([IGate()]) seq.append(HGate()) ref = GateSequence([IGate(), HGate()]) self.assertEqual(seq, ref) def test_eq(self): """Test equality.""" base = GateSequence([HGate(), HGate()]) seq1 = GateSequence([HGate(), HGate()]) seq2 = GateSequence([IGate()]) seq3 = GateSequence([HGate(), HGate()]) seq3.global_phase = 0.12 seq4 = GateSequence([IGate(), HGate()]) with self.subTest("equal"): self.assertEqual(base, seq1) with self.subTest("same product, but different repr (-> false)"): self.assertNotEqual(base, seq2) with self.subTest("differing global phase (-> false)"): self.assertNotEqual(base, seq3) with self.subTest("same num gates, but different gates (-> false)"): self.assertNotEqual(base, seq4) def test_to_circuit(self): """Test converting a gate sequence to a circuit.""" seq = GateSequence([HGate(), HGate(), TGate(), SGate(), SdgGate()]) ref = QuantumCircuit(1) ref.h(0) ref.h(0) ref.t(0) ref.s(0) ref.sdg(0) # a GateSequence is SU(2), so add the right phase z = 1 / np.sqrt(np.linalg.det(Operator(ref))) ref.global_phase = np.arctan2(np.imag(z), np.real(z)) self.assertEqual(seq.to_circuit(), ref) def test_adjoint(self): """Test adjoint.""" seq = GateSequence([TGate(), SGate(), HGate(), IGate()]) inv = GateSequence([IGate(), HGate(), SdgGate(), TdgGate()]) self.assertEqual(seq.adjoint(), inv) def test_copy(self): """Test copy.""" seq = GateSequence([IGate()]) copied = seq.copy() seq.gates.append(HGate()) self.assertEqual(len(seq.gates), 2) self.assertEqual(len(copied.gates), 1) @data(0, 1, 10) def test_len(self, n): """Test __len__.""" seq = GateSequence([IGate()] * n) self.assertEqual(len(seq), n) def test_getitem(self): """Test __getitem__.""" seq = GateSequence([IGate(), HGate(), IGate()]) self.assertEqual(seq[0], IGate()) self.assertEqual(seq[1], HGate()) self.assertEqual(seq[2], IGate()) self.assertEqual(seq[-2], HGate()) def test_from_su2_matrix(self): """Test from_matrix with an SU2 matrix.""" matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) matrix /= np.sqrt(np.linalg.det(matrix)) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_so3_matrix(self): """Test from_matrix with an SO3 matrix.""" matrix = np.array([[0, 0, -1], [0, -1, 0], [-1, 0, 0]]) seq = GateSequence.from_matrix(matrix) ref = GateSequence([HGate()]) self.assertEqual(seq.gates, []) self.assertTrue(np.allclose(seq.product, ref.product)) self.assertEqual(seq.global_phase, 0) def test_from_invalid_matrix(self): """Test from_matrix with invalid matrices.""" with self.subTest("2x2 but not SU2"): matrix = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) with self.assertRaises(ValueError): _ = GateSequence.from_matrix(matrix) with self.subTest("not 2x2 or 3x3"): with self.assertRaises(ValueError): _ = GateSequence.from_matrix(np.array([[1]])) def test_dot(self): """Test dot.""" seq1 = GateSequence([HGate()]) seq2 = GateSequence([TGate(), SGate()]) composed = seq1.dot(seq2) ref = GateSequence([TGate(), SGate(), HGate()]) # check the product matches self.assertTrue(np.allclose(ref.product, composed.product)) # check the circuit & phases are equivalent self.assertTrue(Operator(ref.to_circuit()).equiv(composed.to_circuit())) @ddt class TestSolovayKitaevUtils(QiskitTestCase): """Test the public functions in the Solovay Kitaev utils.""" @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_return_type(self, u_so3: np.ndarray): """Test that ``commutator_decompose`` returns two SO(3) gate sequences.""" v, w = commutator_decompose(u_so3) self.assertTrue(is_so3_matrix(v.product)) self.assertTrue(is_so3_matrix(w.product)) self.assertIsInstance(v, GateSequence) self.assertIsInstance(w, GateSequence) @data( _generate_x_rotation(0.1), _generate_y_rotation(0.2), _generate_z_rotation(0.3), np.dot(_generate_z_rotation(0.5), _generate_y_rotation(0.4)), np.dot(_generate_y_rotation(0.5), _generate_x_rotation(0.4)), ) def test_commutator_decompose_decomposes_correctly(self, u_so3): """Test that ``commutator_decompose`` exactly decomposes the input.""" v, w = commutator_decompose(u_so3) v_so3 = v.product w_so3 = w.product actual_commutator = np.dot(v_so3, np.dot(w_so3, np.dot(np.conj(v_so3).T, np.conj(w_so3).T))) self.assertTrue(np.allclose(actual_commutator, u_so3)) def test_generate_basis_approximation_gates(self): """Test the basis approximation generation works for all supported gates. Regression test of Qiskit/qiskit-terra#9585. """ basis = ["i", "x", "y", "z", "h", "t", "tdg", "s", "sdg"] approx = generate_basic_approximations(basis, depth=2) # This mainly checks that there are no errors in the generation (like # in computing the inverse as described in #9585), so a simple check is enough. self.assertGreater(len(approx), len(basis)) if __name__ == "__main__": unittest.main()
https://github.com/1chooo/Quantum-Oracle
1chooo
# %% [markdown] # # 第5章原始程式碼 # %% #program 5.1a Define classical oracle f1 and test it def f1(x): return '1' print(f1('000'),f1('001'),f1('010'),f1('011'),f1('100'),f1('101'),f1('110'),f1('111')) # %% #program 5.1b Define classical oracle f2 and test it def f2(x): if x[0]=='0': return '0' else: return '1' print(f2('000'),f2('001'),f2('010'),f2('011'),f2('100'),f2('101'),f2('110'),f2('111')) # %% #Program 5.1c Solve constant-balanced function decision (CBFD) prob. with classical code import itertools def cbfd_test(f,n): count0=count1=0 iter = itertools.product([0,1], repeat=n) lst = [''.join(map(str, item)) for item in iter] for s in lst: if f(s)=='0': count0+=1 else: count1+=1 if count0>0 and count1>0: return True #for balanced function elif count0>2**(n-1) or count1>2**(n-1): return False #for constant function print(cbfd_test(f1,3)) print(cdfd_test(f2,3)) # %% #Program 5.2 Define a quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.x(qry) qc.draw('mpl') # %% #Program 5.3a Build quantum circuit of Deutsch-Jozsa alg. from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qrx,qry,cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) qc.draw('mpl') # %% #Program 5.3b Run Deutsch-Jozsa alg. with simulator from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 5.4 Define another quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.cx(qrx[0],qry) qc.draw('mpl') # %% #Program 5.5a Build quantum circuit of Deutsch-Jozsa alg. from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qrx,qry,cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.cx(qrx[0],qry) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) qc.draw('mpl') # %% #Program 5.5b Run Deutsch-Jozsa alg. with simulator from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) # %% #Program 5.6 Show phase kickback of CNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.h(1) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix='\\text{Statevector before CNOT gate: }')) display(plot_bloch_multivector(state1)) print('='*60) qc2 = QuantumCircuit(2) qc2.h(0) qc2.x(1) qc2.h(1) qc2.cx(0,1) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix='\\text{Statevector after CNOT gate: }')) display(plot_bloch_multivector(state2)) # %% # Program 5.7 Show phase kickback of CCNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(3) qc1.h([0,1]) qc1.x(2) qc1.h(2) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state1)) print('='*80) qc2 = QuantumCircuit(3) qc2.h([0,1]) qc2.x(2) qc2.h(2) qc2.ccx(0,1,2) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state2)) # %% #Program 5.8 Show circuit containing CZ gate and CZ gate's unitary matrix from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.cz(0,1) qc1.save_unitary() unitary1 = sim.run(qc1).result().get_unitary() print("CZ Gate (q0 as control bit, q1 as target bit):") display(qc1.draw('mpl')) display(array_to_latex(unitary1, prefix="\\text{Unitray Matrix of CZ Gate (MSB as Target): }")) print('='*60) qc2 = QuantumCircuit(2) qc2.cz(1,0) qc2.save_unitary() unitary2 = sim.run(qc2).result().get_unitary() print("CZ Gate (q1 as control bit, q0 as target bit):") display(qc2.draw('mpl')) display(array_to_latex(unitary2, prefix="\\text{Unitray Matrix of CZ Gate (LSB as Target): }")) # %% #Program 5.9 Show quantum circuit with CZ, CP, CS, CT gates from qiskit import QuantumCircuit from math import pi qc = QuantumCircuit(8) qc.cz(0,1) qc.cp(pi,2,3) qc.cp(pi/2,4,5) qc.cp(pi/4,6,7) display(qc.draw('mpl'))
https://github.com/grossiM/Qiskit_workshop1019
grossiM
a= 1 + 1 a #print(a) a = 1 b = 0.5 a + b an_integer = 42 # Just an integer a_float = 0.1 # A non-integer number, up to a fixed precision a_boolean = True # A value that can be True or False a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text none_of_the_above = None # The absence of any actual value or variable type a_list = [0,1,2,3] a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ] a_list[0] a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' ) a_tuple[0] a_list[5] = 'apple' print(a_list) a_tuple[5] = 'apple' a_list.append( 3.14 ) print(a_list) a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 } a_dict['This is the key for a value 1'] a_dict['new key'] = 'new_value' for j in range(5): print(j) for j in a_list: print(j) for key in a_dict: value = a_dict[key] print('key =',key) print('value =',value) print() if 'strawberry' in a_list: print('We have a strawberry!') elif a_list[5]=='apple': print('We have an apple!') else: print('Not much fruit here!') import numpy numpy.sin( numpy.pi/2 ) import numpy as np np.sin( np.pi/2 ) from numpy import * sin( pi/2 ) def do_some_maths ( Input1, Input2 ): the_answer = Input1 + Input2 return the_answer x = do_some_maths(1,72) print(x) def add_sausages ( input_list ): if 'sausages' not in input_list: input_list.append('sausages') print('List before the function') print(a_list) add_sausages(a_list) # function called without an output print('\nList after the function') print(a_list) import random for j in range(5): print('* Results from sample',j+1) print('\n Random number from 0 to 1:', random.random() ) print("\n Random choice from our list:", random.choice( a_list ) ) print('\n')
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# 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. """ Test circuits and reference outputs for reset instruction. """ from numpy import array, sqrt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # Deterministic output # ========================================================================== def reset_circuits_deterministic(final_measure=True): """Reset test circuits with deterministic count output""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Reset 0 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 1 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 0,1 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 0,1 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_counts_deterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |11> targets.append({'0x2': shots}) # Reset 1 from |11> targets.append({'0x1': shots}) # Reset 0,1 from |11> targets.append({'0x0': shots}) # Reset 0,1 from |++> targets.append({'0x0': shots}) else: # Reset 0 from |11> targets.append({'10': shots}) # Reset 1 from |11> targets.append({'01': shots}) # Reset 0,1 from |11> targets.append({'00': shots}) # Reset 0,1 from |++> targets.append({'00': shots}) return targets def reset_statevector_deterministic(): """Reset test circuits reference counts.""" targets = [] # Reset 0 from |11> targets.append(array([0, 0, 1, 0])) # Reset 1 from |11> targets.append(array([0, 1, 0, 0])) # Reset 0,1 from |11> targets.append(array([1, 0, 0, 0])) # Reset 0,1 from |++> targets.append(array([1, 0, 0, 0])) return targets # ========================================================================== # Non-Deterministic output # ========================================================================== def reset_circuits_nondeterministic(final_measure=True): """Reset test circuits with deterministic count output""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Reset 0 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 1 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_counts_nondeterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |++> targets.append({'0x0': shots / 2, '0x2': shots / 2}) # Reset 1 from |++> targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Reset 0 from |++> targets.append({'00': shots / 2, '10': shots / 2}) # Reset 1 from |++> targets.append({'00': shots / 2, '01': shots / 2}) return targets def reset_statevector_nondeterministic(): """Reset test circuits reference counts.""" targets = [] # Reset 0 from |++> targets.append(array([1, 0, 1, 0]) / sqrt(2)) # Reset 1 from |++> targets.append(array([1, 1, 0, 0]) / sqrt(2)) return targets # ========================================================================== # Repeated Resets # ========================================================================== def reset_circuits_repeated(): """Test circuit for repeated measure reset""" qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.x(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr[0]) qc.measure(qr[0], cr[1]) qc.reset(qr[0]) return [qc] def reset_counts_repeated(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x1': shots}] else: return [{'01': shots}] # ========================================================================== # Sampling optimization # ========================================================================== def reset_circuits_sampling_optimization(): """Test sampling optimization""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # The optimization should not be triggerred # because the reset operation performs randomizations qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset([qr[0]]) qc.measure(qr, cr) return [qc] def reset_counts_sampling_optimization(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x0': shots/2, '0x2': shots/2}] else: return [{'00': shots/2, '10': shots/2}]
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import pylab from qiskit_chemistry import QiskitChemistry # Input dictionary to configure Qiskit Chemistry for the chemistry problem. # Note: In order to allow this to run reasonably quickly it takes advantage # of the ability to freeze core orbitals and remove unoccupied virtual # orbitals to reduce the size of the problem. The result without this # will be more accurate but it takes rather longer to run. # qiskit_chemistry_dict_eigen uses classical approach to produce the reference ground state energy. qiskit_chemistry_dict_eigen = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'ExactEigensolver'}, 'operator': {'name':'hamiltonian','freeze_core': True, 'orbital_reduction': [-3, -2], 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, } # qiskit_chemistry_dict_vqe uses quantum approach to evaluate the ground state energy. qiskit_chemistry_dict_vqe = { 'driver': {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis': 'sto3g'}, 'algorithm': {'name': 'VQE', 'operator_mode': 'matrix'}, 'operator': {'name':'hamiltonian','freeze_core': True, 'orbital_reduction': [-3, -2], 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'optimizer': {'name': 'COBYLA', 'maxiter': 20000}, 'variational_form': {'name': 'RYRZ', 'depth': 10}, 'backend': {'name': 'statevector_simulator'} } # tested molecular, LiH molecule = 'Li .0 .0 -{0}; H .0 .0 {0}' # choose one of configurations above for experiments qiskit_chemistry_dict = qiskit_chemistry_dict_eigen # configure distance between two atoms pts = [x * 0.1 for x in range(6, 20)] pts += [x * 0.25 for x in range(8, 16)] pts += [4.0] distances = np.empty(len(pts)) hf_energies = np.empty(len(pts)) energies = np.empty(len(pts)) dipoles = np.empty(len(pts)) print('Processing step __', end='') for i, d in enumerate(pts): print('\b\b{:2d}'.format(i), end='', flush=True) qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) distances[i] = d hf_energies[i] = result['hf_energy'] energies[i] = result['energy'] dipoles[i] = result['total_dipole_moment'] / 0.393430307 print(' --- complete') print('Distances: ', distances) print('HF Energies:', hf_energies) print('Energies:', energies) print('Dipole moments:', dipoles) pylab.plot(distances, hf_energies, label='HF') pylab.plot(distances, energies, label='Computed') pylab.xlabel('Interatomic distance') pylab.ylabel('Energy') pylab.title('LiH Ground State Energy') pylab.legend(loc='upper right') pylab.plot(distances, dipoles) pylab.xlabel('Interatomic distance') pylab.ylabel('Moment debye') pylab.title('LiH Dipole Moment')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # parameters for considered random distribution S = 2.0 # initial spot price vol = 0.4 # volatility of 40% r = 0.05 # annual interest rate of 4% T = 40 / 365 # 40 days to maturity # resulting parameters for log-normal distribution mu = (r - 0.5 * vol**2) * T + np.log(S) sigma = vol * np.sqrt(T) mean = np.exp(mu + sigma**2 / 2) variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2) stddev = np.sqrt(variance) # lowest and highest value considered for the spot price; in between, an equidistant discretization is considered. low = np.maximum(0, mean - 3 * stddev) high = mean + 3 * stddev # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/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 import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
aryashah2k
#Adding Two Numbers x=2+5 print(x) #Subtracting Two Numbers y=8-5 print(y) #Multiplying Two Numbers a=3*5 print(a) #Dividing Two Numbers b=8/4 print(b) #Calculate the Remainder r=4%3 print(r) #Exponent of a Number e=5**3 print(e) c1=1j*1j print(c1) #Initialize two complex numbers z=4+8j w=5-5j import numpy as np print("Real part of z is:", np.real(z)) print("Imaginary part of w is:", np.imag(w)) #Add two complex numbers add=z+w print(add) #Subtract two complex numbers sub=z-w print(sub) #complex conjugate of w print(w) print("Complex conjugate of w is:", np.conj(w)) #Calculating absolute values for z and w print(z) print("Norm/Absolute value of z is:", np.abs(z)) print(w) print("Norm/Absolute value of w is:", np.abs(w)) #Initialize a row vector row_vector=np.array([1, 2+2j, 3]) print(row_vector) #Initialize a column vector column_vector=np.array([[1],[2+2j],[3j]]) print(column_vector) # Define the 4x1 matrix version of a column vector A=np.array([[1],[4-5j],[5],[-3]]) # Define B as a 1x4 matrix B=np.array([1, 5, -4j, -1j]) # Compute <B|A> np.dot(B,A) M=np.array([[2-1j, -3], [-5j, 2]]) #Note how the brackets are placed! print(M) M=np.matrix([[2-1j, 3],[-5j, 2]]) print(M) #To calculate hermitian matrix simple follow: <your matrix>.H hermitian = M.H print(hermitian) #Use the np.kron method np.kron(M,M)
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/qclib/qclib
qclib
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of timeline drawer.""" from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import core, stylesheet, generators, layouts class TestCanvas(QiskitTestCase): """Test for canvas.""" def setUp(self): super().setUp() self.style = stylesheet.QiskitTimelineStyle() circ = QuantumCircuit(4) circ.h(0) circ.barrier() circ.cx(0, 2) circ.cx(1, 3) self.circ = transpile( circ, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)], optimization_level=0, ) def test_time_range(self): """Test calculating time range.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1} canvas.time_range = (0, 100) ref_range = [-10.0, 110.0] self.assertListEqual(list(canvas.time_range), ref_range) def test_load_program(self): """Test loading program.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 8) ref_coord = { self.circ.qregs[0][0]: -1.0, self.circ.qregs[0][1]: -2.0, self.circ.qregs[0][2]: -3.0, self.circ.qregs[0][3]: -4.0, } self.assertDictEqual(canvas.assigned_coordinates, ref_coord) def test_gate_link_overlap(self): """Test shifting gate link overlap.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update( { "margin.link_interval_percent": 0.01, "margin.left_percent": 0, "margin.right_percent": 0, } ) canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 2) self.assertListEqual(drawings_tested[0][1].xvals, [706.0]) self.assertListEqual(drawings_tested[1][1].xvals, [694.0]) ref_keys = list(canvas._collections.keys()) self.assertEqual(drawings_tested[0][0], ref_keys[0]) self.assertEqual(drawings_tested[1][0], ref_keys[1]) def test_object_outside_xlimit(self): """Test eliminating drawings outside the horizontal limit.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [generators.gen_bit_name, generators.gen_timeslot], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.set_time_range(t_start=400, t_end=600) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 12) def test_non_transpiled_delay_circuit(self): """Test non-transpiled circuit containing instruction which is trivial on duration.""" circ = QuantumCircuit(1) circ.delay(10, 0) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } with self.assertWarns(DeprecationWarning): canvas.load_program(circ) self.assertEqual(len(canvas._collections), 1) def test_multi_measurement_with_clbit_not_shown(self): """Test generating bit link drawings of measurements when clbits is disabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": False}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 0) def test_multi_measurement_with_clbit_shown(self): """Test generating bit link drawings of measurements when clbits is enabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": True}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 2)
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=missing-module-docstring,missing-class-docstring,missing-function-docstring # Since the import is nearly entirely delegated to an external package, most of the testing is done # there. Here we need to test our wrapping behaviour for base functionality and exceptions. We # don't want to get into a situation where updates to `qiskit_qasm3_import` breaks Terra's test # suite due to too specific tests on the Terra side. import os import tempfile import unittest from qiskit import qasm3 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestQASM3Import(QiskitTestCase): @unittest.skipUnless( optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports" ) def test_import_errors_converted(self): with self.assertRaises(qasm3.QASM3ImporterError): qasm3.loads("OPENQASM 3.0; qubit[2.5] q;") @unittest.skipUnless( optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports" ) def test_loads_can_succeed(self): program = """ OPENQASM 3.0; include "stdgates.inc"; qubit[2] qr; bit[2] cr; h qr[0]; cx qr[0], qr[1]; cr[0] = measure qr[0]; cr[1] = measure qr[1]; """ parsed = qasm3.loads(program) expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr")) expected.h(0) expected.cx(0, 1) expected.measure(0, 0) expected.measure(1, 1) self.assertEqual(parsed, expected) @unittest.skipUnless( optionals.HAS_QASM3_IMPORT, "need qiskit-qasm3-import for OpenQASM 3 imports" ) def test_load_can_succeed(self): program = """ OPENQASM 3.0; include "stdgates.inc"; qubit[2] qr; bit[2] cr; h qr[0]; cx qr[0], qr[1]; cr[0] = measure qr[0]; cr[1] = measure qr[1]; """ with tempfile.TemporaryDirectory() as tmp_dir: tmp_path = os.path.join(tmp_dir, "bell.qasm") with open(tmp_path, "w") as fptr: fptr.write(program) parsed = qasm3.load(tmp_path) expected = QuantumCircuit(QuantumRegister(2, "qr"), ClassicalRegister(2, "cr")) expected.h(0) expected.cx(0, 1) expected.measure(0, 0) expected.measure(1, 1) self.assertEqual(parsed, expected)
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import execute, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(84) # do not change this seed, otherwise you will get a different key # This is your 'random' bit string that determines your bases numqubits = 100 bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): # # if bob_bases[qubit_index] == '0': qubit_circuit.measure(0, 0) elif bob_bases[qubit_index] == '1': qubit_circuit.h(0) qubit_circuit.measure(0, 0) # # ... bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '10000000000100011111110011011001010001111101001101111110001100000110000010011000111'\ '00111010010000110' # Alice's bases bits # # key = '' for bit, alice_basis, bob_basis in zip(bits, alice_bases, bob_bases): if alice_basis == bob_basis: key += bit # # check_key(key) m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\ '1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message # # all_key_bits = key * 4 decrypted = '' for key_bit, message_bit in zip(all_key_bits, m): decrypted += str( (int(key_bit) + int(message_bit)) % 2) # # check_decrypted(decrypted) MORSE_CODE_DICT = { 'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-', 'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # # words_decoded = [] words_encoded = decrypted.split('000') for word_encoded in words_encoded: letters_encoded = word_encoded.split('00') letters_decoded = '' for letter_encoded in letters_encoded: dotordashes = letter_encoded.split('0') letter_morse = '' for dotordash in dotordashes: if dotordash == '11': letter_morse += '-' elif dotordash == '1': letter_morse += '.' letters_decoded += next(key for key, value in MORSE_CODE_DICT.items() if value == letter_morse) words_decoded.append(letters_decoded) solution = ' '.join(words_decoded) # # show_message(solution)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests PassManager.run()""" from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate from qiskit.transpiler.preset_passmanagers import level_1_pass_manager from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeMelbourne from qiskit.transpiler import Layout, PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig class TestPassManagerRun(QiskitTestCase): """Test default_pass_manager.run(circuit(s)).""" def test_bare_pass_manager_single(self): """Test that PassManager.run(circuit) returns a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) new_qc = pm.run(qc) self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(qc, new_qc) # pm has no passes def test_bare_pass_manager_single_list(self): """Test that PassManager.run([circuit]) returns a list with a single circuit.""" qc = QuantumCircuit(1) pm = PassManager([]) result = pm.run([qc]) self.assertIsInstance(result, list) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], QuantumCircuit) self.assertEqual(result[0], qc) # pm has no passes def test_bare_pass_manager_multiple(self): """Test that PassManager.run(circuits) returns a list of circuits.""" qc0 = QuantumCircuit(1) qc1 = QuantumCircuit(2) pm = PassManager([]) result = pm.run([qc0, qc1]) self.assertIsInstance(result, list) self.assertEqual(len(result), 2) for qc, new_qc in zip([qc0, qc1], result): self.assertIsInstance(new_qc, QuantumCircuit) self.assertEqual(new_qc, qc) # pm has no passes def test_default_pass_manager_single(self): """Test default_pass_manager.run(circuit). circuit: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuit = pass_manager.run(circuit) self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map) def test_default_pass_manager_two(self): """Test default_pass_manager.run(circuitS). circuit1 and circuit2: qr0:-[H]--.------------ -> 1 | qr1:-----(+)--.-------- -> 2 | qr2:---------(+)--.---- -> 3 | qr3:-------------(+)--- -> 5 device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit1 = QuantumCircuit(qr) circuit1.h(qr[0]) circuit1.cx(qr[0], qr[1]) circuit1.cx(qr[1], qr[2]) circuit1.cx(qr[2], qr[3]) circuit2 = QuantumCircuit(qr) circuit2.cx(qr[1], qr[2]) circuit2.cx(qr[0], qr[1]) circuit2.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( FakeMelbourne(), initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) ) new_circuits = pass_manager.run([circuit1, circuit2]) self.assertIsInstance(new_circuits, list) self.assertEqual(len(new_circuits), 2) for new_circuit in new_circuits: self.assertIsInstance(new_circuit, QuantumCircuit) bit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qregs[0])} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map)
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
import warnings warnings.filterwarnings("ignore") import numpy as np from matplotlib import pyplot as plt from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.mappers.second_quantization import JordanWignerMapper from qiskit_nature.converters.second_quantization import QubitConverter from qiskit import Aer import sys sys.path.append("../../") from entanglement_forging import EntanglementForgedGroundStateSolver from entanglement_forging import EntanglementForgedConfig radius_1 = 0.958 # position for the first H atom radius_2 = 0.958 # position for the second H atom thetas_in_deg = 104.478 # bond angles. H1_x = radius_1 H2_x = radius_2 * np.cos(np.pi / 180 * thetas_in_deg) H2_y = radius_2 * np.sin(np.pi / 180 * thetas_in_deg) molecule = Molecule( geometry=[ ["O", [0.0, 0.0, 0.0]], ["H", [H1_x, 0.0, 0.0]], ["H", [H2_x, H2_y, 0.0]], ], charge=0, multiplicity=1, ) driver = PySCFDriver.from_molecule(molecule=molecule, basis="sto6g") problem = ElectronicStructureProblem(driver) converter = QubitConverter(JordanWignerMapper()) from qiskit_nature.algorithms.ground_state_solvers import ( GroundStateEigensolver, NumPyMinimumEigensolverFactory, ) solver = GroundStateEigensolver( converter, NumPyMinimumEigensolverFactory(use_default_filter_criterion=False) ) result = solver.solve(problem) print("Classical energy = ", result.total_energies[0]) orbitals_to_reduce = [0, 3] from entanglement_forging import reduce_bitstrings bitstrings = [[1, 1, 1, 1, 1, 0, 0], [1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 1, 0]] reduced_bitstrings = reduce_bitstrings(bitstrings, orbitals_to_reduce) print(f"Bitstrings: {bitstrings}") print(f"Bitstrings after orbital reduction: {reduced_bitstrings}") from qiskit.circuit import Parameter, QuantumCircuit theta = Parameter("θ") hop_gate = QuantumCircuit(2, name="Hop gate") hop_gate.h(0) hop_gate.cx(1, 0) hop_gate.cx(0, 1) hop_gate.ry(-theta, 0) hop_gate.ry(-theta, 1) hop_gate.cx(0, 1) hop_gate.h(0) hop_gate.draw() theta_1, theta_2, theta_3, theta_4 = ( Parameter("θ1"), Parameter("θ2"), Parameter("θ3"), Parameter("θ4"), ) ansatz = QuantumCircuit(5) ansatz.append(hop_gate.to_gate({theta: theta_1}), [0, 1]) ansatz.append(hop_gate.to_gate({theta: theta_2}), [3, 4]) ansatz.append(hop_gate.to_gate({theta: 0}), [1, 4]) ansatz.append(hop_gate.to_gate({theta: theta_3}), [0, 2]) ansatz.append(hop_gate.to_gate({theta: theta_4}), [3, 4]) ansatz.draw("text", justify="right", fold=-1) from entanglement_forging import Log Log.VERBOSE = False backend = Aer.get_backend("statevector_simulator") config = EntanglementForgedConfig( backend=backend, maxiter=350, spsa_c0=20 * np.pi, initial_params=[0, 0, 0, 0] ) calc = EntanglementForgedGroundStateSolver( qubit_converter=converter, ansatz=ansatz, bitstrings_u=reduced_bitstrings, config=config, orbitals_to_reduce=orbitals_to_reduce, ) res = calc.solve(problem) res print("Energies (from only one paramset in each iteration):") plt.plot([e[0] for e in res.get_energies_history()]) plt.show() print("Schmidts (from only one paramset in each iteration):") plt.plot([s[0] for s in res.get_schmidts_history()]) plt.show() print("Parameters (from only one paramset in each iteration):") plt.plot([p[0] for p in res.get_parameters_history()]) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
from mirror_gates.sycamore import syc from transpile_benchy.utilities.numerical_decomp import ( Advanced2QDecomposer, BasicDecomposer, ) from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.circuit.parameter import Parameter from qiskit.circuit.library import CXGate, SwapGate, CZGate, iSwapGate decomposer = BasicDecomposer(basis_gates=[(syc, 2)]) from qiskit.transpiler.passes import Optimize1qGates from qiskit.transpiler import PassManager ansatz = QuantumCircuit(2) ansatz.u(Parameter("p000"), Parameter("p001"), Parameter("p002"), 0) ansatz.u(Parameter("q000"), Parameter("q001"), Parameter("q002"), 1) ansatz.append(iSwapGate().power(-1), [0, 1]) ansatz.append(CZGate().power(1 / 6), [0, 1]) ansatz.u(Parameter("p003"), Parameter("p004"), Parameter("p005"), 0) ansatz.u(Parameter("q003"), Parameter("q004"), Parameter("q005"), 1) ansatz.append(iSwapGate().power(-1), [0, 1]) ansatz.append(CZGate().power(1 / 6), [0, 1]) ansatz.u(Parameter("p006"), Parameter("p007"), Parameter("p008"), 0) ansatz.u(Parameter("q006"), Parameter("q007"), Parameter("q008"), 1) ret = decomposer.decompose_from_ansatz(target=CXGate(), ansatz=ansatz) pm = PassManager() pm.append(Optimize1qGates()) ret = pm.run(ret) ret.draw("mpl") ret.qasm(filename="d02_syc_cnot.qasm") ansatz = QuantumCircuit(2) ansatz.u(Parameter("p000"), Parameter("p001"), Parameter("p002"), 0) ansatz.u(Parameter("q000"), Parameter("q001"), Parameter("q002"), 1) ansatz.append(iSwapGate().power(-1), [0, 1]) ansatz.append(CZGate().power(1 / 6), [0, 1]) ansatz.u(Parameter("p003"), Parameter("p004"), Parameter("p005"), 0) ansatz.u(Parameter("q003"), Parameter("q004"), Parameter("q005"), 1) ansatz.append(iSwapGate().power(-1), [0, 1]) ansatz.append(CZGate().power(1 / 6), [0, 1]) ansatz.u(Parameter("p006"), Parameter("p007"), Parameter("p008"), 0) ansatz.u(Parameter("q006"), Parameter("q007"), Parameter("q008"), 1) ansatz.append(iSwapGate().power(-1), [0, 1]) ansatz.append(CZGate().power(1 / 6), [0, 1]) ansatz.u(Parameter("p009"), Parameter("p010"), Parameter("p011"), 0) ansatz.u(Parameter("q009"), Parameter("q010"), Parameter("q011"), 1) ret = decomposer.decompose_from_ansatz(target=SwapGate(), ansatz=ansatz) pm.append(Optimize1qGates()) ret = pm.run(ret) ret.draw("mpl") ret.qasm(filename="d02_syc_swap.qasm")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-docstring import os import configparser as cp from uuid import uuid4 from unittest import mock from qiskit import exceptions from qiskit.test import QiskitTestCase from qiskit import user_config class TestUserConfig(QiskitTestCase): def setUp(self): super().setUp() self.file_path = "test_%s.conf" % uuid4() def test_empty_file_read(self): config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({}, config.settings) def test_invalid_optimization_level(self): test_config = """ [default] transpile_optimization_level = 76 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_invalid_circuit_drawer(self): test_config = """ [default] circuit_drawer = MSPaint """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_drawer_valid(self): test_config = """ [default] circuit_drawer = latex """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_drawer": "latex"}, config.settings) def test_invalid_circuit_reverse_bits(self): test_config = """ [default] circuit_reverse_bits = Neither """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_reverse_bits_valid(self): test_config = """ [default] circuit_reverse_bits = false """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_reverse_bits": False}, config.settings) def test_optimization_level_valid(self): test_config = """ [default] transpile_optimization_level = 1 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"transpile_optimization_level": 1}, config.settings) def test_invalid_num_processes(self): test_config = """ [default] num_processes = -256 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_valid_num_processes(self): test_config = """ [default] num_processes = 31 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"num_processes": 31}, config.settings) def test_valid_parallel(self): test_config = """ [default] parallel = False """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"parallel_enabled": False}, config.settings) def test_all_options_valid(self): test_config = """ [default] circuit_drawer = latex circuit_mpl_style = default circuit_mpl_style_path = ~:~/.qiskit circuit_reverse_bits = false transpile_optimization_level = 3 suppress_packaging_warnings = true parallel = false num_processes = 15 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config.settings, ) def test_set_config_all_options_valid(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path) user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("parallel", "false", file_path=self.file_path) user_config.set_config("num_processes", "15", file_path=self.file_path) config_settings = None with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True): config_settings = user_config.get_config() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config_settings, ) def test_set_config_multiple_sections(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path) user_config.set_config("parallel", "false", section="test", file_path=self.file_path) user_config.set_config("num_processes", "15", section="test", file_path=self.file_path) config = cp.ConfigParser() config.read(self.file_path) self.assertEqual(config.sections(), ["default", "test"]) self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "transpile_optimization_level": "3", }, dict(config.items("default")), )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test for the converter dag dependency to circuit and circuit to dag dependency.""" import unittest from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagCanonical(QiskitTestCase): """Test QuantumCircuit to DAGDependency.""" def test_circuit_and_dag_canonical(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_circuit_and_dag_canonical2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in, create_preds_and_succs=False) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_calibrations(self): """Test that calibrations are properly copied over.""" circuit_in = QuantumCircuit(1) circuit_in.add_calibration("h", [0], None) self.assertEqual(len(circuit_in.calibrations), 1) dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(len(dag_dependency.calibrations), 1) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(len(circuit_out.calibrations), 1) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(dag_dependency.metadata, meta_dict) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") print(qc.qasm()) qc_qasm=qc.qasm(filename='sample.qasm') print(qc_qasm) qc1=qc.from_qasm_file("./sample.qasm") qc1.draw(output="mpl") qc2=qc.from_qasm_str(qc.qasm()) qc2.draw(output="mpl")
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. """Class for solving linear equations for Quantum Time Evolution.""" from __future__ import annotations from collections.abc import Mapping, Sequence, Callable import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator from ..variational_principles import VariationalPrinciple class VarQTELinearSolver: """Class for solving linear equations for Quantum Time Evolution.""" def __init__( self, var_principle: VariationalPrinciple, hamiltonian: BaseOperator, ansatz: QuantumCircuit, gradient_params: Sequence[Parameter] | None = None, t_param: Parameter | None = None, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None, imag_part_tol: float = 1e-7, ) -> None: """ Args: var_principle: Variational Principle to be used. hamiltonian: Operator used for Variational Quantum Time Evolution. ansatz: Quantum state in the form of a parametrized quantum circuit. gradient_params: List of parameters with respect to which gradients should be computed. If ``None`` given, gradients w.r.t. all parameters will be computed. t_param: Time parameter in case of a time-dependent Hamiltonian. lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b`` and returns ``x``. If ``None``, the default ``np.linalg.lstsq`` solver is used. imag_part_tol: Allowed value of an imaginary part that can be neglected if no imaginary part is expected. Raises: TypeError: If t_param is provided and Hamiltonian is not of type SparsePauliOp. """ self._var_principle = var_principle self._hamiltonian = hamiltonian self._ansatz = ansatz self._gradient_params = gradient_params self._bind_params = gradient_params self._time_param = t_param self.lse_solver = lse_solver self._imag_part_tol = imag_part_tol if self._time_param is not None and not isinstance(self._hamiltonian, SparsePauliOp): raise TypeError( f"A time parameter {t_param} has been specified, so a time-dependent " f"hamiltonian is expected. The operator provided is of type {type(self._hamiltonian)}, " f"which might not support parametrization. " f"Please provide the parametrized hamiltonian as a SparsePauliOp." ) @property def lse_solver(self) -> Callable[[np.ndarray, np.ndarray], np.ndarray]: """Returns an LSE solver callable.""" return self._lse_solver @lse_solver.setter def lse_solver(self, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None) -> None: """Sets an LSE solver. Uses a ``np.linalg.lstsq`` callable if ``None`` provided.""" if lse_solver is None: lse_solver = lambda a, b: np.linalg.lstsq(a, b, rcond=1e-2)[0] self._lse_solver = lse_solver def solve_lse( self, param_dict: Mapping[Parameter, float], time_value: float | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Solve the system of linear equations underlying McLachlan's variational principle for the calculation without error bounds. Args: param_dict: Dictionary which relates parameter values to the parameters in the ansatz. time_value: Time value that will be bound to ``t_param``. It is required if ``t_param`` is not ``None``. Returns: Solution to the LSE, A from Ax=b, b from Ax=b. Raises: ValueError: If no time value is provided for time dependent hamiltonians. """ param_values = list(param_dict.values()) metric_tensor_lse_lhs = self._var_principle.metric_tensor(self._ansatz, param_values) hamiltonian = self._hamiltonian if self._time_param is not None: if time_value is not None: hamiltonian = hamiltonian.assign_parameters([time_value]) else: raise ValueError( "Providing a time_value is required for time-dependent hamiltonians, " f"but got time_value = {time_value}. " "Please provide a time_value to the solve_lse method." ) evolution_grad_lse_rhs = self._var_principle.evolution_gradient( hamiltonian, self._ansatz, param_values, self._gradient_params ) x = self._lse_solver(metric_tensor_lse_lhs, evolution_grad_lse_rhs) return np.real(x), metric_tensor_lse_lhs, evolution_grad_lse_rhs
https://github.com/QuTech-Delft/quantuminspire
QuTech-Delft
"""Example usage of the Quantum Inspire backend with the Qiskit SDK. A simple example that demonstrates how to use the SDK to create a circuit to create a Bell state, and simulate the circuit on Quantum Inspire. For documentation on how to use Qiskit we refer to [https://qiskit.org/](https://qiskit.org/). Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication of the user and provides a Quantum Inspire backend that is used to execute the circuit. Copyright 2018-2022 QuTech Delft. Licensed under the Apache License, Version 2.0. """ import os from qiskit import transpile from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from quantuminspire.credentials import get_authentication from quantuminspire.qiskit import QI QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/') project_name = 'Qiskit-entangle' authentication = get_authentication() QI.set_authentication(authentication, QI_URL, project_name=project_name) qi_backend = QI.get_backend('QX single-node simulator') q = QuantumRegister(2) b = ClassicalRegister(2) circuit = QuantumCircuit(q, b) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q, b) circuit = transpile(circuit, backend=qi_backend) qi_job = qi_backend.run(circuit, shots=256) qi_result = qi_job.result() histogram = qi_result.get_counts(circuit) print('\nState\tCounts') [print('{0}\t\t{1}'.format(state, counts)) for state, counts in histogram.items()] # Print the full state probabilities histogram probabilities_histogram = qi_result.get_probabilities(circuit) print('\nState\tProbabilities') [print('{0}\t\t{1}'.format(state, val)) for state, val in probabilities_histogram.items()]
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Number of iteration import math import numpy as np def num_iter(n): res = ((np.pi/4) * (math.sqrt(n))) - (1/2) iter_list = ['N:'+str(n), 'Number of iteration:'+ str(res)] return iter_list for i in range(16): n = 2**i print(num_iter(n)) # importing Qiskit from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.aer import QasmSimulator backend = Aer.get_backend('qasm_simulator') prob_of_ans = [] for x in range(15): database = QuantumRegister(7) oracle = QuantumRegister(1) ancilla = QuantumRegister(5) cr = ClassicalRegister(7) qc = QuantumCircuit(database, oracle, ancilla, cr) qc.h(database[:]) qc.x(oracle[0]) qc.h(oracle[0]) for j in range(x): # oracle_7q # search 47: 0101111 qc.x(database[0]) qc.x(database[2]) qc.mct(database[:], oracle[0], ancilla[:], mode='basic') qc.x(database[0]) qc.x(database[2]) # diffusion_7q qc.h(database[:]) qc.x(database[:]) qc.h(database[6]) qc.mct(database[0:6], database[6], ancilla[:], mode='basic') qc.h(database[6]) qc.x(database[:]) qc.h(database[:]) qc.h(oracle[0]) qc.x(oracle[0]) qc.measure(database,cr) # Change the endian qc = qc.reverse_bits() job = execute(qc, backend=backend, shots=1000, backend_options={"fusion_enable":True}) result = job.result() count = result.get_counts() answer = count['0101111'] prob_of_ans.append(answer) import matplotlib.pyplot as plt iteration = [i for i in range(15)] plt.bar(iteration, prob_of_ans) plt.xlabel('# of iteration') plt.ylabel('# of times the solution was obtained')
https://github.com/mballarin97/mps_qnn
mballarin97
import matplotlib.pyplot as plt import numpy as np from qplotting import Qplotter from qplotting.utils import set_size_pt import seaborn as sns cmap = sns.color_palette('deep', as_cmap=True) def extract_fidelities(num_qubits): fids = {} for nq in num_qubits: path = f"data/svd_checks/{nq}/" singvals = [np.load(path+f"states_0.npy", allow_pickle=True)] for idx in range(1, 10): try: sv = np.load(path+f"states_{idx}.npy", allow_pickle=True) if sv.shape == singvals[0].shape: singvals.append( sv ) except: print(f"No file with index {idx} for {nq} qubits") break fidelities = [] for sv in singvals: fid = np.cumprod( (1-sv)**2 ) fidelities.append(fid) if len(fidelities) >1: mean_fid = np.mean(fidelities, axis=0) std_fid = np.std(fidelities, axis=0) else: mean_fid = fidelities std_fid = np.zeros_like(fidelities) fids[nq] = np.vstack((mean_fid, std_fid)) return fids num_qubits = [30, 50] fids = extract_fidelities(num_qubits) plotter = Qplotter() #plotter(nrows=1, ncols=2, figsize=set_size_pt(2*234, subplots=(1, 2)) ) plotter(figsize=set_size_pt(234)) tt_30 = fids[30].shape[1] tt_50 = fids[50].shape[1] len_layer_30 = int( tt_30/14 ) len_layer_50 = int( tt_50/14 ) fid_30_per_layer = fids[30][0, np.arange(0, tt_30, len_layer_30)] #[ np.prod( fids[30][0, :][ii*len_layer_30:(ii+1)*len_layer_30]) for ii in range(14) ] fid_50_per_layer = fids[50][0, np.arange(0, tt_50, len_layer_50)] #[ np.prod(fids[50][0, :][ii*len_layer_50:(ii+1)*len_layer_50]) for ii in range(14) ] layers = np.arange(1, 15) bonddim = [2**ii for ii in range(13)] entanglement = np.loadtxt("data/svd_checks/50/layer9_ent.npy") entanglement = np.max(entanglement, axis=1) relative_ent_err = np.abs(entanglement - entanglement[-1] )/entanglement[-1] with plotter as qplt: qplt.ax.axhline(1e-4, color="red", ls='--', alpha=0.8, label="Relaiability threshold") qplt.ax.plot(layers, 1-fid_30_per_layer+1e-12, 'o--', label="$n=30$", color=cmap[0]) qplt.ax.plot(layers, 1-fid_50_per_layer+1e-12, '*--', label="$n=50$", color=cmap[1]) qplt.ax.set_yscale("log") qplt.ax.set_xticks(np.arange(1, 15, 4)) #qplt.set_ylim(1e-13, 100) #qplt.ax[0].vlines(len_layer*13, mean_fid[len_layer*13]-0.005, mean_fid[len_layer*13]+0.005, label="layer", color="red") qplt.ax.set_xlabel("Number of layers $L$") qplt.ax.set_ylabel("Infidelity of the state $1-F(t)$") qplt.ax.legend(frameon=False, loc="center left") #qplt.ax[1].plot(bonddim, relative_ent_err[:13], 'o--', label="$L=9$", color=cmap[2]) #qplt.ax[1].set_ylabel("Relative entanglement error") #qplt.ax[1].set_xlabel("Maximum bond dimension $\chi_s$") #qplt.ax[1].set_xscale("log", base=2) #qplt.ax[1].set_yscale("log") #qplt.ax[1].legend(frameon=False) qplt.savefig("images/covergence.pdf") times_aer = np.loadtxt("data/marcos_plot/alternate_abbas16_Aer_time.npy") times_mps = np.loadtxt("data/marcos_plot/alternate_abbas16_MPS_time.npy") layers = np.arange(1, len(times_aer)+1) with Qplotter() as qplt: qplt.plot(layers, (times_aer), 'o--', label="Aer", color=cmap[0]) qplt.plot(layers, (times_mps), '*--', label="Mps", color=cmap[1]) qplt.set_xscale("log") qplt.set_yscale("log") qplt.set_ylabel("Time [s]") qplt.set_xlabel("Number of layers $L$") qplt.legend() qplt.savefig("images/Exact_MPS_comparison.pdf") from marchenko_pastur import gen_mp def kl_div(prob_p, prob_q, dp): prob_p += 1e-12 prob_q += 1e-12 return prob_p*np.log(prob_p/prob_q)*dp def get_mp_distributions(num_qub, max_num_layers, filename): bonddim = 2**(num_qub//2) bins = np.logspace(-5, -1.5, 50) num_layers = np.arange(1, max_num_layers) results = { "bins" : bins, "layers" : num_layers, "num_qubits" : num_qub, "xx" : (bins[1:]+ bins[:-1])/2, "dp" : (bins[1:]- bins[:-1]), } # Marchenko-pastur distributed l1 = num_qub//2 l2 = num_qub//2 if num_qub%2 == 0 else num_qub//2+1 sigma = np.sqrt(1.0 / 2**(max(l1, l2))) sampled_singvals = np.array([]) for _ in range(1000): s_singvals = gen_mp(2**l2, 2**l1, sigma, bonddim, bonddim) s_singvals /= np.sqrt( np.sum(s_singvals**2) ) sampled_singvals = np.append(sampled_singvals, s_singvals) mp_hist, _ = np.histogram(sampled_singvals**2, bins, density=True) results["mp"] = mp_hist results["cmp"] = np.cumsum(mp_hist)/np.sum(mp_hist) # From Haar-random state random_state_singvals = np.array([]) for _ in range(100): psi = np.random.normal(0, sigma, 2**num_qub) + 1j*np.random.normal(0, sigma, 2**num_qub) psi /= np.sqrt( np.sum( np.abs(psi)**2 ) ) rn_ss = np.linalg.svd(psi.reshape(2**l1, 2**l2), False, False) rn_ss /= np.sqrt( np.sum(rn_ss**2) ) random_state_singvals = np.hstack( (random_state_singvals, rn_ss)) rn_hist, _ = np.histogram(random_state_singvals**2, bins, density=True) results["random"] = rn_hist results["crandom"] = np.cumsum(rn_hist)/np.sum(rn_hist) # Experimental exp_hists = [] exp_cum = [] for nl in num_layers: singvals = [] for ss in np.load(filename + f"{num_qub}_{nl}.npy", allow_pickle=True): singvals = np.hstack((singvals, ss)) exp_hist, _ = np.histogram(singvals**2, bins, density=True) exp_hists.append(exp_hist) exp_cum.append( np.cumsum(exp_hist)/np.sum(exp_hist) ) results["exp"] = exp_hists results["cexp"] = exp_cum return results def plot_mp_results(fig, ax, results): mask = results["mp"] > 1e-10 ax[0].plot(results["xx"][mask], results["cmp"][mask], lw=5, label="MP") mask = results["random"] > 1e-10 ax[0].plot(results["xx"][mask], results["crandom"][mask], '--', lw=2, color="black", label="RAND") layers_to_plot = np.linspace( np.max(results["layers"])//3, np.max(results["layers"]), 4 ) layers_to_plot = np.unique( layers_to_plot.astype(int) ) kl_divergences = [] for idx, nl in enumerate(results["layers"]): exp_hist = results["exp"][idx] kl = kl_div(results["mp"], exp_hist, results["dp"]) kl_divergences.append(np.sum(kl) ) if nl in layers_to_plot: mask = exp_hist > 1e-10 ax[0].plot(results["xx"][mask], results["cexp"][idx][mask], '.-', label="$L=$"+str(nl), alpha=0.5 ) ax[0].legend() ax[0].set_yscale("log") ax[0].set_xscale("log") ax[0].set_ylabel("Cumulative probability") ax[0].set_xlabel("Singular values squared") kl_div_good = np.sum( kl_div(results["mp"], results["random"], results["dp"]) ) # Parameters of the variational ansatz + parameters of the feature map ax[1].axhline(kl_div_good, ls='--', color="black", label="Best value") #ax[1].axvline(2**num_qub, ls='--', color="red", label="Best value") ax[1].plot(results["layers"], kl_divergences, 'o', label="Experimental value") ax[1].set_yscale("log") #ax[1].set_xscale("log") ax[1].set_ylabel("KL divergence between experimental and MP distribution") ax[1].set_xlabel("Number of layers") ax[1].legend() def plot_mp_distribution(fig, ax, results): mask = results["mp"] > 1e-10 ax.plot(results["xx"][mask], results["cmp"][mask], lw=3, label="MP") mask = results["random"] > 1e-10 ax.plot(results["xx"][mask], results["crandom"][mask], '--', lw=1.5, color="black", label="Haar") layers_to_plot = [6, 10, 15] kl_divergences = [] for idx, nl in enumerate(results["layers"]): exp_hist = results["exp"][idx] kl = kl_div(results["mp"], exp_hist, results["dp"]) kl_divergences.append(np.sum(kl) ) if nl in layers_to_plot: mask = exp_hist > 1e-10 ax.plot(results["xx"][mask], results["cexp"][idx][mask], '.-', label="$L=$"+str(nl), alpha=0.8 ) ax.legend(frameon=False, handletextpad=0.4) ax.set_yscale("log") ax.set_xscale("log") ax.set_ylabel("CDF $C(\lambda^2)$") ax.set_xlabel("Singular values squared $\lambda^2$") ax.set_ylim(10**(-2.1), 1.5) filename = "data/marchenko-pastur/singvals" num_qub = 15 max_nl = 20 results15_zzc2 = get_mp_distributions(num_qub, max_nl, filename) filename = "data/marchenko-pastur/singvals_c2c2_" num_qub = 15 max_nl = 16 results15_c2c2 = get_mp_distributions(num_qub, max_nl, filename) with Qplotter() as qplt: plot_mp_distribution(qplt.fig, qplt.ax, results15_zzc2) qplt.savefig("images/mp_convergence.pdf")
https://github.com/bringthehouse/qiskit-2019-purple-qubits-server
bringthehouse
#!/usr/bin/env python3 from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute def run_qasm(qasm, backend_to_run="qasm_simulator"): qc = QuantumCircuit.from_qasm_str(qasm) backend = Aer.get_backend(backend_to_run) job_sim = execute(qc, backend) sim_result = job_sim.result() return sim_result.get_counts(qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import UnitarySynthesis circuit = QuantumCircuit(1) circuit.rx(0.8, 0) unitary = Operator(circuit).data unitary_circ = QuantumCircuit(1) unitary_circ.unitary(unitary, [0]) synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk") out = synth(unitary_circ) out.draw('mpl')
https://github.com/ka-us-tubh/quantum-computing-qiskit-
ka-us-tubh
from ibm_quantum_widgets import CircuitComposer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(4, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.x(qreg_q[3]) circuit.barrier(qreg_q[3], qreg_q[0], qreg_q[1], qreg_q[2]) circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) circuit.h(qreg_q[3]) circuit.barrier(qreg_q[3], qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[3]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.barrier(qreg_q[3], qreg_q[0], qreg_q[1], qreg_q[2]) circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) circuit.measure(qreg_q[0], creg_c[0]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[2], creg_c[2]) editor = CircuitComposer(circuit=circuit) editor
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
''' This program uses some methods from quantum chemistry (and doesn't produce anything good yet) ''' import numpy as np from matplotlib.pyplot import plot, draw, show import pylab, os from qiskit import * #from qiskit.chemistry import QiskitChemistry # does no longer exist from qiskit_nature import * os.environ["QT_QPA_PLATFORM"] = "xcb" # input dictionary to configure Qiskit Chemistry for the chemistry problem qiskit_chemistry_dict = { 'problem': {'random_seed': 750}, 'driver' : {'name': 'PYSCF'}, 'PYSCF': {'atom': '', 'basis' : 'sto3g'}, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity', 'two_qubit_reduction': True}, 'algorithm': {}, } molecule = 'H .0 .0 -{0}; H .0 .0 {0}' algorithms = [{'name': 'VQE','operator_mode': 'paulis'}, {'name': 'ExactEigensolver'} ] optimizer = {'name': 'SPSA', 'max_trials': 200} variational_form = {'name': 'RYRZ', 'depth': 3, 'entanglement': 'full'} backend = {'provider': 'qiskit.BasicAer', 'name': 'qasm_simulator', 'shots': 1024} start = 0.5 # start distance increment = 0.5 # how much to increase distance by steps = 20 # number of steps to increase by energies = np.empty([len(algorithms), steps+1]) hf_energies = np.empty(steps+1) distances = np.empty(steps+1) print('Processing step __', end='') for i in range(steps+1): print('\b\b{:2d}'.format(i), end='',flush=True) d = start + i*increment/steps qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2) for j in range(len(algorithms)): qiskit_chemistry_dict['algorithm'] = algorithms[j] if algorithms[j]['name'] == 'VQE': qiskit_chemistry_dict['optimizer'] = optimizer qiskit_chemistry_dict['variational_form'] = variational_form qiskit_chemistry_dict['backend'] = backend else: # This does no longer work as qiskit.chemistry is deprecated # The functions may be contained in qiskit_nature ''' qiskit_chemistry_dict.pop('optimizer') qiskit_chemistry_dict.pop('variational_form') qiskit_chemistry_dict.pop('backend') solver = QiskitChemistry() result = solver.run(qiskit_chemistry_dict) energies[j][i] = result['energy'] hf_energies[i] = result['hf_energy'] distances[i] = d ''' print(' --- complete') print('Distances: ', distances) print('Energies: ', energies) print('Hartree-Fock energies: ', hf_energies) pylab.plot(distances, hf_energies, label='Hartree-Fock') for j in range(len(algorithms)): pylab.plot(distances, energies[j], label=algorithms[j]) pylab.xlabel('Interatomic distance (Angstrom)') pylab.ylabel('Energy (Hartree)') pylab.title('H2 Ground State Energy') pylab.legend(loc='upper right') draw() show(block=True) pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock') pylab.plot(distances, np.subtract(energies[0], energies[1]), label=algorithms[0]) pylab.xlabel('Interatomic distance (Angstrom)') pylab.ylabel('Energy (Hartree)') pylab.title('Energy difference from ExactEigensolver') pylab.legend(loc='upper left') draw() show(block=True)
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 #!pip install pennylane #improt pennylane dependnecies import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer # load the csv files import pandas as pd # plot the historical acc and cost import matplotlib.pyplot as plt import seaborn as sns from IPython.display import clear_output clear_output(wait=False) import os data_train = pd.read_csv("dataset/fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) dev = qml.device("default.qubit", wires=4) def layer_1(W): qml.RY(W[0], wires=0) qml.RY(W[1], wires=1) qml.RY(W[2], wires=2) qml.RY(W[3], wires=3) qml.Hadamard(wires=0) qml.Hadamard(wires=1) qml.Hadamard(wires=2) qml.Hadamard(wires=3) qml.RZ(W[4], wires=0) qml.RZ(W[5], wires=1) qml.RZ(W[6], wires=2) qml.RZ(W[7], wires=3) qml.CNOT(wires=[1,0]) qml.RY(W[8], wires=1) qml.CNOT(wires=[2,0]) qml.RY(W[9], wires=2) qml.CNOT(wires=[3,0]) qml.RY(W[10], wires=3) qml.CNOT(wires=[2,1]) qml.RY(W[11], wires=2) qml.CNOT(wires=[3,1]) qml.RY(W[12], wires=3) # qml.Hadamard(wires=0) # qml.Hadamard(wires=1) # qml.Hadamard(wires=2) # qml.Hadamard(wires=3) #qml.CNOT(wires=[1,0]) #qml.CNOT(wires=[2,0]) #qml.CNOT(wires=[3,0]) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_wires = 4 n_block_wires = 2 n_params_block = 2 n_blocks = qml.MPS.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): #statepreparation(x) qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) #for i in range(4): #qml.Hadamard(wires=i) #qml.RY(x[i], wires=i) #qml.Hadamard(wires=i) #qml.RX(x[i+4], wires=i) #qml.RX(x[i+8], wires=i) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) #qml.CNOT(wires=[4,0]) #qml.CNOT(wires=[0,1]) #qml.CNOT(wires=[1,2]) #qml.CNOT(wires=[2,3]) #qml.CNOT(wires=[3,0]) for w in weights: #layer_1(w[:13]) #layer_2(w[12:21]) #layer_2(w[16:24]) #layer_3(w[21:]) qml.MPS(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(3)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 1 weights_init = 2*np.pi * np.random.randn(num_layers,3, 2, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3,4,5,6,7])(weights_init,np.asarray(X_train[0]))) for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mps_1_layers.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/AnikenC/JaxifiedQiskit
AnikenC
import copy import uuid import datetime from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit_dynamics import DynamicsBackend, Solver, Signal, RotatingFrame from qiskit_dynamics.solvers.solver_classes import ( format_final_states, validate_and_format_initial_state, ) from typing import Optional, List, Union, Callable, Tuple from qiskit_dynamics.array import wrap from qiskit import pulse from qiskit_dynamics.models import HamiltonianModel, LindbladModel from qiskit_dynamics.models.hamiltonian_model import is_hermitian from qiskit_dynamics.type_utils import to_numeric_matrix_type from qiskit import QuantumCircuit from qiskit.result import Result from qiskit.quantum_info import Statevector from qiskit.pulse import Schedule, ScheduleBlock from qiskit_dynamics.array import Array import jax import jax.numpy as jnp from jax import block_until_ready, vmap import numpy as np from scipy.integrate._ivp.ivp import OdeResult jit = wrap(jax.jit, decorator=True) qd_vmap = wrap(vmap, decorator=True) Runnable = Union[QuantumCircuit, Schedule, ScheduleBlock] class JaxSolver(Solver): """This custom Solver behaves exactly like the original Solver object except one difference, the user provides the function that can be jitted for faster simulations (should be provided to the class non-jit compiled)""" def __init__( self, static_hamiltonian: Optional[Array] = None, hamiltonian_operators: Optional[Array] = None, static_dissipators: Optional[Array] = None, dissipator_operators: Optional[Array] = None, hamiltonian_channels: Optional[List[str]] = None, dissipator_channels: Optional[List[str]] = None, channel_carrier_freqs: Optional[dict] = None, dt: Optional[float] = None, rotating_frame: Optional[Union[Array, RotatingFrame]] = None, in_frame_basis: bool = False, evaluation_mode: str = "dense", rwa_cutoff_freq: Optional[float] = None, rwa_carrier_freqs: Optional[Union[Array, Tuple[Array, Array]]] = None, validate: bool = True, schedule_func: Optional[Callable[[], Schedule]] = None, ): """Initialize solver with model information. Args: static_hamiltonian: Constant Hamiltonian term. If a ``rotating_frame`` is specified, the ``frame_operator`` will be subtracted from the static_hamiltonian. hamiltonian_operators: Hamiltonian operators. static_dissipators: Constant dissipation operators. dissipator_operators: Dissipation operators with time-dependent coefficients. hamiltonian_channels: List of channel names in pulse schedules corresponding to Hamiltonian operators. dissipator_channels: List of channel names in pulse schedules corresponding to dissipator operators. channel_carrier_freqs: Dictionary mapping channel names to floats which represent the carrier frequency of the pulse channel with the corresponding name. dt: Sample rate for simulating pulse schedules. rotating_frame: Rotating frame to transform the model into. Rotating frames which are diagonal can be supplied as a 1d array of the diagonal elements, to explicitly indicate that they are diagonal. in_frame_basis: Whether to represent the model in the basis in which the rotating frame operator is diagonalized. See class documentation for a more detailed explanation on how this argument affects object behaviour. evaluation_mode: Method for model evaluation. See documentation for ``HamiltonianModel.evaluation_mode`` or ``LindbladModel.evaluation_mode``. (if dissipators in model) for valid modes. rwa_cutoff_freq: Rotating wave approximation cutoff frequency. If ``None``, no approximation is made. rwa_carrier_freqs: Carrier frequencies to use for rotating wave approximation. If no time dependent coefficients in model leave as ``None``, if no time-dependent dissipators specify as a list of frequencies for each Hamiltonian operator, and if time-dependent dissipators present specify as a tuple of lists of frequencies, one for Hamiltonian operators and one for dissipators. validate: Whether or not to validate Hamiltonian operators as being Hermitian. jittable_func: Callable or list of Callables taking as inputs arrays such that parametrized pulse simulation can be done in an optimized manner Raises: QiskitError: If arguments concerning pulse-schedule interpretation are insufficiently specified. """ super().__init__( static_hamiltonian, hamiltonian_operators, static_dissipators, dissipator_operators, hamiltonian_channels, dissipator_channels, channel_carrier_freqs, dt, rotating_frame, in_frame_basis, evaluation_mode, rwa_cutoff_freq, rwa_carrier_freqs, validate, ) self._schedule_func = schedule_func @property def circuit_macro(self): return self._schedule_func @circuit_macro.setter def set_macro(self, func): """ This setter should be done each time one wants to switch the target circuit truncation """ self._schedule_func = func def _solve_schedule_list_jax( self, t_span_list: List[Array], y0_list: List[Union[Array, QuantumState, BaseOperator]], schedule_list: List[Schedule], convert_results: bool = True, **kwargs, ) -> List[OdeResult]: param_dicts = kwargs["parameter_dicts"] relevant_params = param_dicts[0].keys() observables_circuits = kwargs["observables"] param_values = kwargs["parameter_values"] for key in ["parameter_dicts", "parameter_values", "parameter_values"]: kwargs.pop(key) def sim_function(params, t_span, y0_input, y0_cls): parametrized_schedule = self.circuit_macro() parametrized_schedule.assign_parameters( { param_obj: param for (param_obj, param) in zip(relevant_params, params) } ) signals = self._schedule_converter.get_signals(parametrized_schedule) # Perhaps replace below by solve_lmde results = self.solve(t_span, y0_input, signals, **kwargs) results.y = format_final_states(results.y, self.model, y0_input, y0_cls) return Array(results.t).data, Array(results.y).data
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/ikemmm/qiskit-quantum-algorithms
ikemmm
# This algorithm demonstrates the creation of a Bell state. # In this state, 2 qubits are entangled to create a link between their final and intermediate states. # Let X and Y be the entangled qubits. # When qubit X collapses into the state 0, Y then must be in the state 1. # Through this concept, we create a unified final state probability distribution between # the two and proceed with the execution on the QASM simulator, a quantum virtual # machine. import qiskit as qk from qiskit import execute, BasicAer backend = BasicAer.get_backend('qasm_simulator') STATE_MEASUREMENTS = 10000 # Create the circuit registers. qr = qk.QuantumRegister(2) cr = qk.ClassicalRegister(2) # Create the quantum circuit. # Contains a single Hadamard gate and a CNOT gate qc = qk.QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Prepare the measurement. measure_z = qk.QuantumCircuit(qr, cr) measure_z.measure(qr, cr) # Execute the job and take the measurement with the specified number of shots. test_z = qc + measure_z job_1 = qk.execute([test_z], backend, shots = STATE_MEASUREMENTS) counts = job_1.result().get_counts(test_z) print(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Useful additional packages import matplotlib.pyplot as plt import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer backend = BasicAer.get_backend('unitary_simulator') q = QuantumRegister(1) qc = QuantumCircuit(q) qc.u(pi/2,pi/4,pi/8,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.p(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.id(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.x(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.y(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.z(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.h(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.s(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.sdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.t(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.tdg(q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rx(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ry(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.rz(pi/2,q) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cy(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cz(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.ch(q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.crz(pi/2,q[0],q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cp(pi/2,q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.swap(q[0], q[1]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) qc = QuantumCircuit(q) qc.cswap(q[0], q[1], q[2]) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.measure(q, c) qc.draw() backend = BasicAer.get_backend('qasm_simulator') job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.reset(q[0]) qc.measure(q, c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q,c) qc.x(q[0]).c_if(c, 0) qc.measure(q,c) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_counts(qc) # Initializing a three-qubit quantum state import math desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] q = QuantumRegister(3) qc = QuantumCircuit(q) qc.initialize(desired_vector, [q[0],q[1],q[2]]) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state state_fidelity(desired_vector,qc_state) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, execute from qiskit.providers.fake_provider import FakeVigoV2 from qiskit.visualization import plot_gate_map backend = FakeVigoV2() plot_gate_map(backend)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/noamsgl/IBMAscolaChallenge
noamsgl
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np filepath = "../datasets/universal_error/DepolOnly/U3_19.csv" df = pd.read_csv(filepath) # reorder columns df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'p0_0', 'p0_1', 'p1_0', 'p1_1']] # filter out inf values df = df[np.isfinite] df.info() df.head() sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]}) sns.distplot(df['E'], norm_hist=False, kde=False, bins=50, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count') df.hist(bins=100, figsize=(20,15), layout=(3,4)); sns.scatterplot(x=df['theta'], y=df['E']); sns.jointplot(x=df['theta'], y=df['E']); sns.scatterplot(x=df['phi'], y=df['E']); sns.scatterplot(x=df['lam'], y=df['E']); sns.scatterplot(x=df['theta'], y=df['phi']); sns.scatterplot(x=df['depol_prob'], y=df['E']); sns.jointplot(x=df['t1'], y=df['E']); sns.jointplot(x=df['t2'], y=df['E']); sns.scatterplot(x=df['t1'], y=df['E']); sns.scatterplot(x=df['t2'], y=df['E']); sns.pairplot(data=df);
https://github.com/adarshisme/QiskitBiskit
adarshisme
!pip install qiskit !pip install pylatexenc import matplotlib.pyplot as plt import math import matplotlib as mpl import numpy as np import pandas as pd import qiskit as q from qiskit import Aer, assemble, QuantumRegister, ClassicalRegister from qiskit.circuit import QuantumCircuit import pylatexenc from qiskit.quantum_info import Statevector, PTM from qiskit.visualization import array_to_latex from qiskit import transpile from qiskit.providers.aer import QasmSimulator import random from qiskit.quantum_info import partial_trace, Statevector, DensityMatrix from numpy import kron, trace backend = QasmSimulator() def visualize_one_line(x1_vals, y1_vals, axis_labels, title, label): fig, ax = plt.subplots() plt.title(title) plt.xlabel(axis_labels[0]) plt.ylabel(axis_labels[1]) ax.plot(x1_vals, y1_vals, linestyle='-', color='red', label=label) plt.legend() def stateTomography(p): I = (np.array([[1, 0],[0, 1]])* np.array(p)).trace() X = (np.array([[0, 1],[1, 0]])* np.array(p)).trace() Y = (np.array([[0, 0- 1j],[1j, 0]])* np.array(p)).trace() Z = (np.array([[1, 0],[0, -1]])* np.array(p)).trace() return np.array([I, X, Y, Z]) def normalNoise(circ, noise): circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) def randomTwirl(circ, noise): x = random.randint(0,3) if x == 1: circ.x(0) if x == 2: circ.y(0) if x == 3: circ.z(0) circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) if x == 1: circ.x(0) if x == 2: circ.y(0) if x == 3: circ.z(0) def PauliConjugation(circ, noise, gate): if gate == 'x': circ.x(0) if gate == 'y': circ.y(0) if gate == 'z': circ.z(0) circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) if gate == 'x': circ.x(0) if gate == 'y': circ.y(0) if gate == 'z': circ.z(0) def pauli_conjug_x(circ, noise): PauliConjugation(circ, noise, 'x') def pauli_conjug_y(circ, noise): PauliConjugation(circ, noise, 'y') def pauli_conjug_z(circ, noise): PauliConjugation(circ, noise, 'z') tvals = [0.7, 1, 7, 10, 70, 100, 700, 1000, 7000, 10000] funcs = [normalNoise, randomTwirl, pauli_conjug_x, pauli_conjug_y, pauli_conjug_z] strings_to_funcs = {str(noise_func).split(' ')[1]: noise_func for noise_func in funcs} funcs_to_strings = {strings_to_funcs[a]: a for a in strings_to_funcs} success_data = {noise_func: [] for noise_func in funcs} state_tomography_data = {noise_func: [] for noise_func in funcs} for noise_func in funcs: print(funcs_to_strings[noise_func]) for val in tvals: coinQ = QuantumRegister(1) coinC = ClassicalRegister(1) t = val T_1 = 10000 turn = math.pi/500 noise = 2*math.asin(math.sqrt(1-math.e**(-t/T_1))) coinCircuit = QuantumCircuit(coinQ, coinC) coinCircuit.initialize([1, 0], 0) coinCircuit.ry(math.pi/3, 0) coinCircuit.measure(0, 0) coin_compiled = transpile(coinCircuit, backend) flip_sim = backend.run(coin_compiled, shots=1000) result_sim = flip_sim.result() counts = {} counts = result_sim.get_counts(coin_compiled) distribution = [] for i in range(counts['1']): distribution.append(1) for i in range (counts['0']): distribution.append(0) random.shuffle(distribution) unfairQ = QuantumRegister(2) unfairC = ClassicalRegister(1) unfairCircuit = QuantumCircuit(unfairQ, unfairC) unfairCircuit.initialize([1, 0], 0) unfairCircuit.initialize([1, 0], 1) for i in distribution: if i == 1: unfairCircuit.ry(-turn, 0) if i == 0: unfairCircuit.ry(turn, 0) noise_func(unfairCircuit, noise) #For Pauli conjugation comment out randomTwirl and use the below with desired gate #PauliConjugation(unfairCircuit, noise, z) #For normal noise use below #normalNoise(unfairCircuit, noise) unfairCircuit.measure(0, 0) turn_compiled = transpile(unfairCircuit, backend) turn_sim = backend.run(turn_compiled, shots = 200) unfair_sim = turn_sim.result() count_totals = unfair_sim.get_counts(turn_compiled) unfairQ = QuantumRegister(2) unfairCircuit = QuantumCircuit(unfairQ) for i in distribution: if i == 1: unfairCircuit.ry(-turn, 0) if i == 0: unfairCircuit.ry(turn, 0) unfairCircuit.cry(noise, 0, 1) unfairCircuit.cnot(1, 0) unfairCircuit.reset(1) state = Statevector.from_int(0, 2**2) state = state.evolve(unfairCircuit) rho = DensityMatrix(state) qubitOut = partial_trace(rho, [1]) qubitIn = DensityMatrix([1, 0]) stateTomographyIn = stateTomography(qubitIn) stateTomographyOut = stateTomography(qubitOut) success_data[noise_func].append(count_totals['1'] / 200 if '1' in count_totals else 0) state_tomography_data[noise_func].append(stateTomographyOut[-1]) fig, axs = plt.subplots(1, 2, figsize=(13, 5)) fig.suptitle('error correction via twirling and Pauli conjugation') axs[0].set_xscale('log') axs[0].set_xlabel('t / T_1') axs[0].set_ylabel('success probability') axs[1].set_xscale('log') axs[1].set_xlabel('t / T_1') axs[1].set_ylabel('Pauli expectation out') tvals = [t / T_1 for t in tvals] for noise_func in funcs: axs[0].plot(tvals, success_data[noise_func], label=funcs_to_strings[noise_func]) axs[1].plot(tvals, state_tomography_data[noise_func], label=funcs_to_strings[noise_func]) plt.legend()
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/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### replaced x gate ### qc.x(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# If you introduce a list with less colors than bars, the color of the bars will # alternate following the sequence from the list. import numpy as np from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0, 1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) matrix = DensityMatrix(qc) plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
#!/usr/bin/env python3 # Author: Daniel Escanez-Exposito from abc import ABC, abstractmethod from qiskit import QuantumCircuit from qiskit.circuit.library import YGate, ZGate from qiskit.circuit.gate import Gate import qiskit.quantum_info as qi from numpy.random import randint import numpy as np from math import ceil ## An abstract class of a participant entity in the Six-State implementation ## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html class Participant(ABC): ## Constructor @abstractmethod def __init__(self, name='', original_bits_size=0): ## The name of the participant self.name = name ## The original size of the message self.original_bits_size = original_bits_size ## The values of the participant self.values = None ## The axes of the participant self.axes = None ## The key of the participant self.key = None ## If the key is determined safe self.is_safe_key = False ## The otp of the participant self.otp = None ## The gate measuring z and y axes self.set_hy() ## Values setter def set_values(self, values=None): if values == None: self.values = list(randint(2, size=self.original_bits_size)) else: self.values = values ## Axes setter def set_axes(self, axes=None): if axes == None: self.axes = list(randint(3, size=self.original_bits_size)) else: self.axes = axes ## Print values def show_values(self): print('\n' + self.name, 'Values:') print(self.values) ## Print axes def show_axes(self): print('\n' + self.name, 'Axes:') print(self.axes) ## Print key def show_key(self): print('\n' + self.name, 'Key:') print(self.key) ## Print otp def show_otp(self): print('\n' + self.name, 'OTP:') print(self.otp) ## Remove the values of the qubits that were measured on the wrong axis def remove_garbage(self, another_axes): self.key = [] for i in range(self.original_bits_size): if self.axes[i] == another_axes[i]: self.key.append(self.values[i]) ## Check if the shared key is equal to the current key def check_key(self, shared_key): return shared_key == self.key[:len(shared_key)] ## Use the rest of the key and validate it def confirm_key(self, shared_size): self.key = self.key[shared_size:] self.is_safe_key = True ## Generate an One-Time Pad def generate_otp(self, n_bits): self.otp = [] for i in range(ceil(len(self.key) / n_bits)): bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits])) self.otp.append(int(bits_string, 2)) ## Performs an XOR operation between the message and the One-Time Pad def xor_otp_message(self, message): final_message = '' CHR_LIMIT = 1114112 if len(self.otp) > 0: for i, char in enumerate(message): final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT) return final_message ## New gate setter def set_hy(self): hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix())) hy_gate = QuantumCircuit(1) hy_gate.unitary(hy_op, [0], label='h_y') self.hy = hy_gate.to_gate()
https://github.com/anpaschool/QC-School-Fall2020
anpaschool
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ,Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.extensions import Initialize from qiskit_textbook.tools import random_state, array_to_latex #Create a circuit qr = QuantumRegister(3) # Protocol uses 3 qubits crz = ClassicalRegister(1) # and 2 classical bits crx = ClassicalRegister(1) # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): """Creates a bell pair in qc using qubits a & b""" qc.h(a) # Put qubit a into state |+> qc.cx(a,b) # CNOT with a as control and b as target ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3,name='q') crz, crx = ClassicalRegister(1,name='crz'),ClassicalRegister(1,name='crx') teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 # In our case, Telamon entangles qubits q1 and q2 # Let's apply this to our circuit: create_bell_pair(teleportation_circuit, 1, 2) # And view the circuit so far: teleportation_circuit.draw('mpl') def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw(output='mpl') def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw('mpl') # This function takes a QuantumCircuit (qc), integer (qubit) # and ClassicalRegisters (crz & crx) to decide which gates to apply def bob_gates(qc, qubit, crz, crx): # Here we use c_if to control our gates with a classical # bit instead of a qubit qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' ## STEP 4 ## Complete Circuit Again # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw('mpl') psi=random_state(1) array_to_latex(psi, pretext="|\\psi\\rangle =") plot_bloch_multivector(psi) #Create initialization gate to create psi from |0> init_gate=Initialize(psi) init_gate.label='init' ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw('mpl') backend = BasicAer.get_backend('statevector_simulator') out_vector = execute(qc, backend).result().get_statevector() plot_bloch_multivector(out_vector) inverse_init_gate = init_gate.gates_to_uncompute() ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) ## STEP 5 # reverse the initialization process qc.append(inverse_init_gate, [2]) # Display the circuit qc.draw('mpl') # Need to add a new ClassicalRegister # to see the result cr_result = ClassicalRegister(1) qc.add_register(cr_result) qc.measure(2,2) qc.draw('mpl') backend = BasicAer.get_backend('qasm_simulator') counts = execute(qc, backend, shots=1024).result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# import SymPy and define symbols import sympy as sp sp.init_printing(use_unicode=True) wr = sp.Symbol('\omega_r') # resonator frequency wq = sp.Symbol('\omega_q') # qubit frequency g = sp.Symbol('g', real=True) # vacuum Rabi coupling Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later # import operator relations and define them from sympy.physics.quantum.boson import BosonOp a = BosonOp('a') # resonator photon annihilation operator from sympy.physics.quantum import pauli, Dagger, Commutator from sympy.physics.quantum.operatorordering import normal_ordered_form # Pauli matrices sx = pauli.SigmaX() sy = pauli.SigmaY() sz = pauli.SigmaZ() # qubit raising and lowering operators splus = pauli.SigmaPlus() sminus = pauli.SigmaMinus() # define J-C Hamiltonian in terms of diagonal and non-block diagonal terms H0 = wr*Dagger(a)*a - (1/2)*wq*sz; H1 = 0 H2 = g*(Dagger(a)*sminus + a*splus); HJC = H0 + H1 + H2; HJC # print # using the above method for finding the ansatz eta = Commutator(H0, H2); eta pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand())) A = sp.Symbol('A') B = sp.Symbol('B') eta = A * Dagger(a) * sminus - B * a * splus; pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand())) H2 S1 = eta.subs(A, g/Delta) S1 = S1.subs(B, g/Delta); S1.factor() Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff 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 kHz = 1.0e3 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.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.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") from qiskit import pulse # This is where we access all of our Pulse features! inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[qubit]) x_pulse = inst_sched_map.get('x', qubits=[qubit]) ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Create the base schedule # Start with drive pulse acting on the drive channel schedule = pulse.Schedule(name='Frequency sweep') schedule += x_pulse # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration schedule += measure << schedule.duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHz*GHz schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz] schedule.draw(label=True, scaling=0.8) from qiskit import assemble frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=schedule_frequencies) # 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('5ef3b081fbc24b001275b03b') frequency_sweep_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') sweep_values = [] for i in range(len(frequency_sweep_results.results)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[qubit]) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") 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(frequencies_GHz, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 3] # initial parameters for curve_fit ) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') plt.plot(frequencies_GHz, y_fit, color='red') plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # Create the schedules for 0 and 1 schedule_0 = pulse.Schedule(name='0') schedule_0 += measure schedule_1 = pulse.Schedule(name='1') schedule_1 += x_pulse schedule_1 += measure << schedule_1.duration schedule_0.draw() schedule_1.draw() frequency_span_Hz = 320 * kHz frequency_step_Hz = 8 * kHz center_frequency_Hz = backend_defaults.meas_freq_est[qubit] print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.") frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\ in steps of {frequency_step_Hz / MHz} MHz.") num_shots_per_frequency = 2048 frequencies_Hz = frequencies_GHz*GHz schedule_los = [{meas_chan: freq} for freq in frequencies_Hz] cavity_sweep_0 = assemble(schedule_0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) cavity_sweep_1 = assemble(schedule_1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) # RUN the job on a real device #job_0 = backend.run(cavity_sweep_0) #job_monitor(job_0) #job_0.error_message() #job_1 = backend.run(cavity_sweep_1) #job_monitor(job_1) #job_1.error_message() # OR retreive result from previous run job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c') job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4') cavity_sweep_0_results = job_0.result() cavity_sweep_1_results = job_1.result() scale_factor = 1e-14 sweep_values_0 = [] for i in range(len(cavity_sweep_0_results.results)): res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor sweep_values_0.append(res_0[qubit]) sweep_values_1 = [] for i in range(len(cavity_sweep_1_results.results)): res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor sweep_values_1.append(res_1[qubit]) plotx = frequencies_Hz/kHz ploty_0 = np.abs(sweep_values_0) ploty_1 = np.abs(sweep_values_1) plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$']) plt.grid() plt.xlabel("Frequency [kHz]") plt.ylabel("Measured signal [a.u.]") plt.yscale('log') plt.show()
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=invalid-name,missing-docstring # pylint: disable=attribute-defined-outside-init from qiskit import transpile from qiskit.circuit.library.standard_gates import XGate from qiskit.transpiler import CouplingMap from qiskit.transpiler import InstructionDurations from qiskit.transpiler.passes import ( TimeUnitConversion, ASAPSchedule, ALAPSchedule, DynamicalDecoupling, ) from qiskit.converters import circuit_to_dag from .utils import random_circuit class SchedulingPassBenchmarks: params = ([5, 10, 20], [500, 1000]) param_names = ["n_qubits", "depth"] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit( n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed, max_operands=2 ) self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"] self.cmap = [ [0, 1], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [3, 2], [3, 4], [3, 8], [4, 3], [5, 6], [5, 10], [6, 1], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 3], [8, 7], [8, 9], [9, 8], [9, 14], [10, 5], [10, 11], [11, 10], [11, 12], [11, 16], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [13, 18], [14, 9], [14, 13], [15, 16], [16, 11], [16, 15], [16, 17], [17, 16], [17, 18], [18, 13], [18, 17], [18, 19], [19, 18], ] self.coupling_map = CouplingMap(self.cmap) self.transpiled_circuit = transpile( self.circuit, basis_gates=self.basis_gates, coupling_map=self.coupling_map, optimization_level=1, ) self.dag = circuit_to_dag(self.transpiled_circuit) self.durations = InstructionDurations( [ ("rz", None, 0), ("id", None, 160), ("sx", None, 160), ("x", None, 160), ("cx", None, 800), ("measure", None, 3200), ("reset", None, 3600), ], dt=1e-9, ) self.timed_dag = TimeUnitConversion(self.durations).run(self.dag) _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" self.scheduled_dag = _pass.run(self.timed_dag) def time_time_unit_conversion_pass(self, _, __): TimeUnitConversion(self.durations).run(self.dag) def time_alap_schedule_pass(self, _, __): _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_asap_schedule_pass(self, _, __): _pass = ASAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_dynamical_decoupling_pass(self, _, __): DynamicalDecoupling(self.durations, dd_sequence=[XGate(), XGate()]).run(self.scheduled_dag)
https://github.com/apozas/qaoa-color
apozas
import time # Import the Qiskit modules(Qiskit Terra) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError from qiskit import QISKitError,execute, IBMQ, Aer import numpy as np # Set your API Token. # You can get it from https://quantumexperience.ng.bluemix.net/qx/account, # looking for "Personal Access Token" section. QX_TOKEN = "3e30646ac6c9ac8bae7e1ab0802d14f67ed3667a6aa12e2328a46043dd8102f83de09858a41b43bd0c35f8e44eb6eb46ed27046ea61363354599d8f3a79bfa02" QX_URL = "https://quantumexperience.ng.bluemix.net/api" # Authenticate with the IBM Q API in order to use online devices. # You need the API Token and the QX URL. IBMQ.enable_account(QX_TOKEN, QX_URL) # import basic plot tools from qiskit.tools.visualization import plot_histogram "Choice of the backend" # using local qasm simulator backend = Aer.get_backend('qasm_simulator') # using IBMQ qasm simulator # backend = IBMQ.get_backend('ibmq_qasm_simulator') # using real device # backend = least_busy(IBMQ.backends(simulator=False)) # backend = IBMQ.get_backend('ibmq_16_melbourne') flag_qx2 = True if backend.name() == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) def wstategenrate(W_states) : # 3-qubit W state W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) return W_states n = 3 q = QuantumRegister(n) c = ClassicalRegister(n) W_states = QuantumCircuit(q,c) wstate = wstategenrate(W_states) for i in range(3) : wstate.measure(q[i] , c[i]) shots = 8192 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('start W state 3-qubit on', backend, "N=", shots,time_exp) result = execute(wstate, backend=backend, shots=shots) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print('end W state 3-qubit on', backend, "N=", shots,time_exp) plot_histogram(result.result().get_counts(W_states)) W_states.draw(output="mpl")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the legacy Scheduling passes""" import unittest from ddt import ddt, data, unpack from qiskit import QuantumCircuit from qiskit.circuit import Delay, Parameter from qiskit.circuit.library.standard_gates import XGate, YGate, CXGate from qiskit.test import QiskitTestCase from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes import ASAPSchedule, ALAPSchedule, DynamicalDecoupling from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.target import Target, InstructionProperties @ddt class TestSchedulingPass(QiskitTestCase): """Tests the Scheduling passes""" def test_alap_agree_with_reverse_asap_reverse(self): """Test if ALAP schedule agrees with doubly-reversed ASAP schedule.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.measure_all() durations = InstructionDurations( [("h", 0, 200), ("cx", [0, 1], 700), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) alap_qc = pm.run(qc) pm = PassManager(ASAPSchedule(durations)) new_qc = pm.run(qc.reverse_ops()) new_qc = new_qc.reverse_ops() new_qc.name = new_qc.name self.assertEqual(alap_qc, new_qc) @data(ALAPSchedule, ASAPSchedule) def test_classically_controlled_gate_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌─┐ q_0: ┤M├─────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├─── ║ └─╥─┘ ║ ┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞ 0 └─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├ ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├─────── └─────────────────┘ ║ └─╥─┘ ║ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════ 0 └─────────┘ """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) # x.c_if starts after measure expected.x(1).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with measure after measure with a common clbit. See: https://github.com/Qiskit/qiskit-terra/issues/7654 (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── └───┘└╥┘┌─┐ q_1: ──────╫─┤M├ ║ └╥┘ c: 1/══════╩══╩═ 0 0 (scheduled) ┌───┐ ┌─┐┌─────────────────┐ q_0: ───────┤ X ├───────┤M├┤ Delay(1000[dt]) ├ ┌──────┴───┴──────┐└╥┘└───────┬─┬───────┘ q_1: ┤ Delay(1200[dt]) ├─╫─────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩══════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.x(0) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.x(0) expected.measure(0, 0) expected.delay(1200, 1) expected.measure(1, 0) expected.delay(1000, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_c_if_on_different_qubits(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with `c_if`s on different qubits. (input) ┌─┐ q_0: ┤M├────────────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────────────── ║ └─╥─┘ ┌───┐ q_2: ─╫──────╫────────┤ X ├─── ║ ║ └─╥─┘ ║ ┌────╨────┐┌────╨────┐ c: 1/═╩═╡ c_0 = T ╞╡ c_0 = T ╞ 0 └─────────┘└─────────┘ (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────────────── ├─────────────────┤ ║ └─╥─┘ ┌───┐ q_2: ┤ Delay(1000[dt]) ├─╫─────────╫────────────┤ X ├─── └─────────────────┘ ║ ║ └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/════════════════════╩════╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ 0 └─────────┘ └─────────┘ """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, True) qc.x(2).c_if(0, True) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.delay(1000, 2) expected.x(1).c_if(0, True) expected.x(2).c_if(0, True) expected.delay(200, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_shorter_measure_after_measure(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with shorter measure after measure with a common clbit. (input) ┌─┐ q_0: ┤M├─── └╥┘┌─┐ q_1: ─╫─┤M├ ║ └╥┘ c: 1/═╩══╩═ 0 0 (scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(700[dt]) ├ ┌─────────────────┐└╥┘└──────┬─┬───────┘ q_1: ┤ Delay(1000[dt]) ├─╫────────┤M├──────── └─────────────────┘ ║ └╥┘ c: 1/════════════════════╩═════════╩═════════ 0 0 """ qc = QuantumCircuit(2, 1) qc.measure(0, 0) qc.measure(1, 0) durations = InstructionDurations([("measure", [0], 1000), ("measure", [1], 700)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.measure(0, 0) expected.delay(1000, 1) expected.measure(1, 0) expected.delay(700, 0) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_measure_after_c_if(self, schedule_pass): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (scheduled) ┌─┐┌─────────────────┐ q_0: ───────────────────┤M├┤ Delay(1000[dt]) ├────────────────── ┌─────────────────┐└╥┘└──────┬───┬──────┘┌────────────────┐ q_1: ┤ Delay(1000[dt]) ├─╫────────┤ X ├───────┤ Delay(800[dt]) ├ ├─────────────────┤ ║ └─╥─┘ └──────┬─┬───────┘ q_2: ┤ Delay(1000[dt]) ├─╫──────────╫────────────────┤M├──────── └─────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩═════╡ c_0=0x1 ╞════════════╩═════════ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) pm = PassManager(schedule_pass(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(3, 1) expected.delay(1000, 1) expected.delay(1000, 2) expected.measure(0, 0) expected.x(1).c_if(0, 1) expected.measure(2, 0) expected.delay(1000, 0) expected.delay(800, 1) self.assertEqual(expected, scheduled) def test_parallel_gate_different_length(self): """Test circuit having two parallel instruction with different length. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├┤M├ └─────┬───┬──────┘└┬─┬┘└╥┘ q_1: ──────┤ X ├────────┤M├──╫─ └───┘ └╥┘ ║ c: 2/════════════════════╩═══╩═ 1 0 (expected, ASAP) ┌───┐┌─┐┌────────────────┐ q_0: ┤ X ├┤M├┤ Delay(200[dt]) ├ ├───┤└╥┘└──────┬─┬───────┘ q_1: ┤ X ├─╫────────┤M├──────── └───┘ ║ └╥┘ c: 2/══════╩═════════╩═════════ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager(ASAPSchedule(durations)) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.x(1) asap_expected.measure(0, 0) # immediately start after X gate asap_expected.measure(1, 1) asap_expected.delay(200, 0) self.assertEqual(qc_asap, asap_expected) def test_parallel_gate_different_length_with_barrier(self): """Test circuit having two parallel instruction with different length with barrier. (input) ┌───┐┌─┐ q_0: ┤ X ├┤M├─── ├───┤└╥┘┌─┐ q_1: ┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/══════╩══╩═ 0 1 (expected, ALAP) ┌────────────────┐┌───┐ ░ ┌─┐ q_0: ┤ Delay(200[dt]) ├┤ X ├─░─┤M├─── └─────┬───┬──────┘└───┘ ░ └╥┘┌─┐ q_1: ──────┤ X ├─────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 (expected, ASAP) ┌───┐┌────────────────┐ ░ ┌─┐ q_0: ┤ X ├┤ Delay(200[dt]) ├─░─┤M├─── ├───┤└────────────────┘ ░ └╥┘┌─┐ q_1: ┤ X ├───────────────────░──╫─┤M├ └───┘ ░ ║ └╥┘ c: 2/═══════════════════════════╩══╩═ 0 1 """ qc = QuantumCircuit(2, 2) qc.x(0) qc.x(1) qc.barrier() qc.measure(0, 0) qc.measure(1, 1) durations = InstructionDurations( [("x", [0], 200), ("x", [1], 400), ("measure", None, 1000)] ) pm = PassManager(ALAPSchedule(durations)) qc_alap = pm.run(qc) alap_expected = QuantumCircuit(2, 2) alap_expected.delay(200, 0) alap_expected.x(0) alap_expected.x(1) alap_expected.barrier() alap_expected.measure(0, 0) alap_expected.measure(1, 1) self.assertEqual(qc_alap, alap_expected) pm = PassManager(ASAPSchedule(durations)) qc_asap = pm.run(qc) asap_expected = QuantumCircuit(2, 2) asap_expected.x(0) asap_expected.delay(200, 0) asap_expected.x(1) asap_expected.barrier() asap_expected.measure(0, 0) asap_expected.measure(1, 1) self.assertEqual(qc_asap, asap_expected) def test_measure_after_c_if_on_edge_locking(self): """Test if ALAP/ASAP schedules circuits with c_if after measure with a common clbit. The scheduler is configured to reproduce behavior of the 0.20.0, in which clbit lock is applied to the end-edge of measure instruction. See https://github.com/Qiskit/qiskit-terra/pull/7655 (input) ┌─┐ q_0: ┤M├────────────── └╥┘ ┌───┐ q_1: ─╫────┤ X ├────── ║ └─╥─┘ ┌─┐ q_2: ─╫──────╫─────┤M├ ║ ┌────╨────┐└╥┘ c: 1/═╩═╡ c_0 = T ╞═╩═ 0 └─────────┘ 0 (ASAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├───────────────────── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├──────────────────────────── └─────────────────┘ ║ └─╥─┘ ┌─┐┌────────────────┐ q_2: ────────────────────╫─────────╫─────────┤M├┤ Delay(200[dt]) ├ ║ ┌────╨────┐ └╥┘└────────────────┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═══════════════════ 0 └─────────┘ 0 (ALAP scheduled) ┌─┐┌────────────────┐ q_0: ───────────────────┤M├┤ Delay(200[dt]) ├─── ┌─────────────────┐└╥┘└─────┬───┬──────┘ q_1: ┤ Delay(1000[dt]) ├─╫───────┤ X ├────────── └┬────────────────┤ ║ └─╥─┘ ┌─┐ q_2: ─┤ Delay(200[dt]) ├─╫─────────╫─────────┤M├ └────────────────┘ ║ ┌────╨────┐ └╥┘ c: 1/════════════════════╩════╡ c_0=0x1 ╞═════╩═ 0 └─────────┘ 0 """ qc = QuantumCircuit(3, 1) qc.measure(0, 0) qc.x(1).c_if(0, 1) qc.measure(2, 0) durations = InstructionDurations([("x", None, 200), ("measure", None, 1000)]) # lock at the end edge actual_asap = PassManager(ASAPSchedule(durations, clbit_write_latency=1000)).run(qc) actual_alap = PassManager(ALAPSchedule(durations, clbit_write_latency=1000)).run(qc) # start times of 2nd measure depends on ASAP/ALAP expected_asap = QuantumCircuit(3, 1) expected_asap.measure(0, 0) expected_asap.delay(1000, 1) expected_asap.x(1).c_if(0, 1) expected_asap.measure(2, 0) expected_asap.delay(200, 0) expected_asap.delay(200, 2) self.assertEqual(expected_asap, actual_asap) expected_alap = QuantumCircuit(3, 1) expected_alap.measure(0, 0) expected_alap.delay(1000, 1) expected_alap.x(1).c_if(0, 1) expected_alap.delay(200, 2) expected_alap.measure(2, 0) expected_alap.delay(200, 0) self.assertEqual(expected_alap, actual_alap) @data([100, 200], [500, 0], [1000, 200]) @unpack def test_active_reset_circuit(self, write_lat, cond_lat): """Test practical example of reset circuit. Because of the stimulus pulse overlap with the previous XGate on the q register, measure instruction is always triggered after XGate regardless of write latency. Thus only conditional latency matters in the scheduling. (input) ┌─┐ ┌───┐ ┌─┐ ┌───┐ ┌─┐ ┌───┐ q: ┤M├───┤ X ├───┤M├───┤ X ├───┤M├───┤ X ├─── └╥┘ └─╥─┘ └╥┘ └─╥─┘ └╥┘ └─╥─┘ ║ ┌────╨────┐ ║ ┌────╨────┐ ║ ┌────╨────┐ c: 1/═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞═╩═╡ c_0=0x1 ╞ 0 └─────────┘ 0 └─────────┘ 0 └─────────┘ """ qc = QuantumCircuit(1, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) qc.measure(0, 0) qc.x(0).c_if(0, 1) durations = InstructionDurations([("x", None, 100), ("measure", None, 1000)]) actual_asap = PassManager( ASAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat) ).run(qc) actual_alap = PassManager( ALAPSchedule(durations, clbit_write_latency=write_lat, conditional_latency=cond_lat) ).run(qc) expected = QuantumCircuit(1, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) expected.measure(0, 0) if cond_lat > 0: expected.delay(cond_lat, 0) expected.x(0).c_if(0, 1) self.assertEqual(expected, actual_asap) self.assertEqual(expected, actual_alap) def test_random_complicated_circuit(self): """Test scheduling complicated circuit with control flow. (input) ┌────────────────┐ ┌───┐ ░ ┌───┐ » q_0: ┤ Delay(100[dt]) ├───┤ X ├────░──────────────────┤ X ├───» └────────────────┘ └─╥─┘ ░ ┌───┐ └─╥─┘ » q_1: ───────────────────────╫──────░───────┤ X ├────────╫─────» ║ ░ ┌─┐ └─╥─┘ ║ » q_2: ───────────────────────╫──────░─┤M├─────╫──────────╫─────» ┌────╨────┐ ░ └╥┘┌────╨────┐┌────╨────┐» c: 1/══════════════════╡ c_0=0x1 ╞════╩═╡ c_0=0x0 ╞╡ c_0=0x0 ╞» └─────────┘ 0 └─────────┘└─────────┘» « ┌────────────────┐┌───┐ «q_0: ┤ Delay(300[dt]) ├┤ X ├─────■───── « └────────────────┘└───┘ ┌─┴─┐ «q_1: ────────■─────────────────┤ X ├─── « ┌─┴─┐ ┌─┐ └─╥─┘ «q_2: ──────┤ X ├────────┤M├──────╫───── « └───┘ └╥┘ ┌────╨────┐ «c: 1/════════════════════╩══╡ c_0=0x0 ╞ « 0 └─────────┘ (ASAP scheduled) duration = 2800 dt ┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐» q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├» ├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤» q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├» ├────────────────┤ ║ ░ └───────┬─┬───────┘» q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────» └────────────────┘ ┌────╨────┐ ░ └╥┘ » c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════» └─────────┘ 0 » « ┌───┐ ┌────────────────┐» «q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├» « ┌───┐ └─╥─┘ └────────────────┘» «q_1: ───┤ X ├──────────────────────────╫─────────────■─────────» « └─╥─┘ ┌────────────────┐ ║ ┌─┴─┐ » «q_2: ─────╫─────┤ Delay(300[dt]) ├─────╫───────────┤ X ├───────» « ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ » «c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════» « └─────────┘ └─────────┘ » « ┌───┐ ┌────────────────┐ «q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├ « ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤ «q_1: ┤ Delay(400[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├ « ├────────────────┤ └─╥─┘ └──────┬─┬───────┘ «q_2: ┤ Delay(300[dt]) ├─────╫────────────┤M├──────── « └────────────────┘┌────╨────┐ └╥┘ «c: 1/══════════════════╡ c_0=0x0 ╞════════╩═════════ « └─────────┘ 0 (ALAP scheduled) duration = 3100 ┌────────────────┐┌────────────────┐ ┌───┐ ░ ┌─────────────────┐» q_0: ┤ Delay(100[dt]) ├┤ Delay(100[dt]) ├───┤ X ├────░─┤ Delay(1400[dt]) ├» ├────────────────┤└────────────────┘ └─╥─┘ ░ ├─────────────────┤» q_1: ┤ Delay(300[dt]) ├───────────────────────╫──────░─┤ Delay(1200[dt]) ├» ├────────────────┤ ║ ░ └───────┬─┬───────┘» q_2: ┤ Delay(300[dt]) ├───────────────────────╫──────░─────────┤M├────────» └────────────────┘ ┌────╨────┐ ░ └╥┘ » c: 1/════════════════════════════════════╡ c_0=0x1 ╞════════════╩═════════» └─────────┘ 0 » « ┌───┐ ┌────────────────┐» «q_0: ────────────────────────────────┤ X ├───┤ Delay(300[dt]) ├» « ┌───┐ ┌────────────────┐ └─╥─┘ └────────────────┘» «q_1: ───┤ X ├───┤ Delay(300[dt]) ├─────╫─────────────■─────────» « └─╥─┘ ├────────────────┤ ║ ┌─┴─┐ » «q_2: ─────╫─────┤ Delay(600[dt]) ├─────╫───────────┤ X ├───────» « ┌────╨────┐└────────────────┘┌────╨────┐ └───┘ » «c: 1/╡ c_0=0x0 ╞══════════════════╡ c_0=0x0 ╞══════════════════» « └─────────┘ └─────────┘ » « ┌───┐ ┌────────────────┐ «q_0: ──────┤ X ├────────────■─────┤ Delay(700[dt]) ├ « ┌─────┴───┴──────┐ ┌─┴─┐ ├────────────────┤ «q_1: ┤ Delay(100[dt]) ├───┤ X ├───┤ Delay(700[dt]) ├ « └──────┬─┬───────┘ └─╥─┘ └────────────────┘ «q_2: ───────┤M├─────────────╫─────────────────────── « └╥┘ ┌────╨────┐ «c: 1/════════╩═════════╡ c_0=0x0 ╞══════════════════ « 0 └─────────┘ """ qc = QuantumCircuit(3, 1) qc.delay(100, 0) qc.x(0).c_if(0, 1) qc.barrier() qc.measure(2, 0) qc.x(1).c_if(0, 0) qc.x(0).c_if(0, 0) qc.delay(300, 0) qc.cx(1, 2) qc.x(0) qc.cx(0, 1).c_if(0, 0) qc.measure(2, 0) durations = InstructionDurations( [("x", None, 100), ("measure", None, 1000), ("cx", None, 200)] ) actual_asap = PassManager( ASAPSchedule(durations, clbit_write_latency=100, conditional_latency=200) ).run(qc) actual_alap = PassManager( ALAPSchedule(durations, clbit_write_latency=100, conditional_latency=200) ).run(qc) expected_asap = QuantumCircuit(3, 1) expected_asap.delay(100, 0) expected_asap.delay(100, 0) # due to conditional latency of 200dt expected_asap.delay(300, 1) expected_asap.delay(300, 2) expected_asap.x(0).c_if(0, 1) expected_asap.barrier() expected_asap.delay(1400, 0) expected_asap.delay(1200, 1) expected_asap.measure(2, 0) expected_asap.x(1).c_if(0, 0) expected_asap.x(0).c_if(0, 0) expected_asap.delay(300, 0) expected_asap.x(0) expected_asap.delay(300, 2) expected_asap.cx(1, 2) expected_asap.delay(400, 1) expected_asap.cx(0, 1).c_if(0, 0) expected_asap.delay(700, 0) # creg is released at t0 of cx(0,1).c_if(0,0) expected_asap.delay( 700, 1 ) # no creg write until 100dt. thus measure can move left by 300dt. expected_asap.delay(300, 2) expected_asap.measure(2, 0) self.assertEqual(expected_asap, actual_asap) self.assertEqual(actual_asap.duration, 3100) expected_alap = QuantumCircuit(3, 1) expected_alap.delay(100, 0) expected_alap.delay(100, 0) # due to conditional latency of 200dt expected_alap.delay(300, 1) expected_alap.delay(300, 2) expected_alap.x(0).c_if(0, 1) expected_alap.barrier() expected_alap.delay(1400, 0) expected_alap.delay(1200, 1) expected_alap.measure(2, 0) expected_alap.x(1).c_if(0, 0) expected_alap.x(0).c_if(0, 0) expected_alap.delay(300, 0) expected_alap.x(0) expected_alap.delay(300, 1) expected_alap.delay(600, 2) expected_alap.cx(1, 2) expected_alap.delay(100, 1) expected_alap.cx(0, 1).c_if(0, 0) expected_alap.measure(2, 0) expected_alap.delay(700, 0) expected_alap.delay(700, 1) self.assertEqual(expected_alap, actual_alap) self.assertEqual(actual_alap.duration, 3100) def test_dag_introduces_extra_dependency_between_conditionals(self): """Test dependency between conditional operations in the scheduling. In the below example circuit, the conditional x on q1 could start at time 0, however it must be scheduled after the conditional x on q0 in ASAP scheduling. That is because circuit model used in the transpiler passes (DAGCircuit) interprets instructions acting on common clbits must be run in the order given by the original circuit (QuantumCircuit). (input) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├─── └─────┬───┬──────┘ └─╥─┘ q_1: ──────┤ X ├────────────╫───── └─╥─┘ ║ ┌────╨────┐ ┌────╨────┐ c: 1/═══╡ c_0=0x1 ╞════╡ c_0=0x1 ╞ └─────────┘ └─────────┘ (ASAP scheduled) ┌────────────────┐ ┌───┐ q_0: ┤ Delay(100[dt]) ├───┤ X ├────────────── ├────────────────┤ └─╥─┘ ┌───┐ q_1: ┤ Delay(100[dt]) ├─────╫────────┤ X ├─── └────────────────┘ ║ └─╥─┘ ┌────╨────┐┌────╨────┐ c: 1/══════════════════╡ c_0=0x1 ╞╡ c_0=0x1 ╞ └─────────┘└─────────┘ """ qc = QuantumCircuit(2, 1) qc.delay(100, 0) qc.x(0).c_if(0, True) qc.x(1).c_if(0, True) durations = InstructionDurations([("x", None, 160)]) pm = PassManager(ASAPSchedule(durations)) scheduled = pm.run(qc) expected = QuantumCircuit(2, 1) expected.delay(100, 0) expected.delay(100, 1) # due to extra dependency on clbits expected.x(0).c_if(0, True) expected.x(1).c_if(0, True) self.assertEqual(expected, scheduled) @data(ALAPSchedule, ASAPSchedule) def test_respect_target_instruction_constraints(self, schedule_pass): """Test if ALAP/ASAP does not pad delays for qubits that do not support delay instructions. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ target = Target(dt=1) target.add_instruction(XGate(), {(1,): InstructionProperties(duration=200)}) # delays are not supported qc = QuantumCircuit(2) qc.x(1) pm = PassManager(schedule_pass(target=target)) scheduled = pm.run(qc) expected = QuantumCircuit(2) expected.x(1) # no delay on qubit 0 self.assertEqual(expected, scheduled) def test_dd_respect_target_instruction_constraints(self): """Test if DD pass does not pad delays for qubits that do not support delay instructions and does not insert DD gates for qubits that do not support necessary gates. See: https://github.com/Qiskit/qiskit-terra/issues/9993 """ qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) target = Target(dt=1) # Y is partially supported (not supported on qubit 2) target.add_instruction( XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)} ) target.add_instruction( CXGate(), { (0, 1): InstructionProperties(duration=1000), (1, 2): InstructionProperties(duration=1000), }, ) # delays are not supported # No DD instructions nor delays are padded due to no delay support in the target pm_xx = PassManager( [ ALAPSchedule(target=target), DynamicalDecoupling(durations=None, dd_sequence=[XGate(), XGate()], target=target), ] ) scheduled = pm_xx.run(qc) self.assertEqual(qc, scheduled) # Fails since Y is not supported in the target with self.assertRaises(TranspilerError): PassManager( [ ALAPSchedule(target=target), DynamicalDecoupling( durations=None, dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target, ), ] ) # Add delay support to the target target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)}) # No error but no DD on qubit 2 (just delay is padded) since X is not supported on it scheduled = pm_xx.run(qc) expected = QuantumCircuit(3) expected.delay(1000, [2]) expected.cx(0, 1) expected.cx(1, 2) expected.delay(200, [0]) expected.x([0]) expected.delay(400, [0]) expected.x([0]) expected.delay(200, [0]) self.assertEqual(expected, scheduled) if __name__ == "__main__": unittest.main()
https://github.com/primaryobjects/oracle
primaryobjects
from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates.z import ZGate def oracle(i, n): ''' Returns a quantum circuit that recognizes a single number i. Upon starting, all qubits are assumed to have a value of 1. Parameters: i: the target value to be recognized, an integer between 0 and 2^n-1. n: the number of qubits in the circuit. ''' # We use a circuit of size n+1 to include an output qubit. qc = QuantumCircuit(n+1) # Convert i to a binary string. bin_str = bin(i)[2:] # Pad the binary string with zeros to the length of the qubits. bin_str = bin_str.zfill(n) print('Encoding ' + bin_str) # Reverse the bits since qiskit represents the qubits from right to left. bin_str = bin_str[::-1] # Flip each qubit to zero to match the bits in the target number i. for j in range(len(bin_str)): if bin_str[j] == '0': qc.x(j) # Apply a controlled Z-gate on all qubits, setting the phase. qc.append(ZGate().control(n), range(n+1)) # Undo each inverted qubit. for j in range(len(bin_str)): if bin_str[j] == '0': qc.x(j) print(qc.draw()) # Convert the oracle to a gate. gate = qc.to_gate() gate.name = "oracle" return gate
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,QuantumCircuit from qiskit.aqua.operators import StateFn from qiskit.aqua.operators import I from qiskit_code.quantumMethod import add,ini from qiskit_code.classicalMethod import Dec2Bi def DeutschJozsa(l,method): # Deutsch, D. and Jozsa, R., 1992. Rapid solution of problems by quantum computation. # Proceedings of the Royal Society of London. Series A: Mathematical and Physical Sciences, # 439(1907), pp.553-558. # The input 'l' is the equivalent to the 'N' in the original paper of # David Deutsch and Richard Jozsa, and 'method' denotes the 'unknown' # function, if you input 'balanced' then it will be balanced and otherwise # it will be constant. qr0=QuantumRegister(l) qr1=QuantumRegister(l+1) # One qubit larger to carry. ac=QuantumRegister(l) # Ancilla. t0=QuantumRegister(1) circ=QuantumCircuit(qr0,qr1,ac,t0) circ.h(qr0) if method=='balanced': print('balanced oracle') ini(circ,qr1,Dec2Bi(2**(l-1))) else: print('constant oracle') ini(circ,qr1,Dec2Bi(0)) lst=range(l) QIN1=[qr0[i] for i in lst]+[qr1[i] for i in range(l+1)]+[ac[i] for i in lst] ADD=add(qr0,qr1,ac,l) circ.append(ADD,QIN1)# Role of the U unitary circ.cx(qr1[l],t0)# Role of the U unitary circ.z(t0)# The S unitary. circ.cx(qr1[l],t0)# Role of the U unitary circ.append(ADD.inverse(),QIN1)# Role of the U unitary psi=StateFn(circ) phiReg0=QuantumRegister(l) phiReg1=QuantumRegister(l+1) phiReg2=QuantumRegister(l) t1=QuantumRegister(1) phiCirc=QuantumCircuit(phiReg0,phiReg1,phiReg2,t1) phiCirc.h(phiReg0) if method=='balanced': ini(circ,qr1,Dec2Bi(2**(l-1))) else: ini(circ,qr1,Dec2Bi(0)) phi=StateFn(phiCirc) operator=I.tensorpower(3*l+2) expectation_value=(~psi@operator@phi).eval() print(expectation_value) #DeutschJozsa('constant') #DeutschJozsa('balanced')
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # 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.providers.aer import QasmSimulator 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 # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt, to_instruction = True): qc = QuantumCircuit(2) qc.rx(2 * dt, 0) qc.rz(2 * dt, 1) qc.h(1) qc.cx(1, 0) qc.rz(-2 * dt, 0) qc.rx(-2 * dt, 1) qc.rz(2 * dt, 1) qc.cx(1, 0) qc.h(1) qc.rz(2 * dt, 0) return qc.to_instruction() if to_instruction else qc trotter_gate(np.pi / 6, to_instruction=False).draw("mpl") def make_initial_state(qc, initial_state): """ logical qubit index little endian """ for i, state in enumerate(initial_state): if state == "1": qc.x(i) qc = QuantumCircuit(3) make_initial_state(qc, "101") qc.draw("mpl") def subspace_encoder(qc, targets): """ naive method, can be optimized for init state |110> little endian """ n = qc.num_qubits qc.cx(targets[2],targets[1]) qc.cx(targets[1],targets[0]) qc.cx(targets[0],targets[2]) def subspace_encoder_init110(qc, targets): """ optimized encoder for init state |110> endian: |q_0, q_1, q_2> (little endian) encode |110> to |0>|10> """ n = qc.num_qubits qc.x(targets[0]) def subspace_decoder(qc, targets): """ naive method little endian """ n = qc.num_qubits qc.cx(targets[0], targets[2]) qc.cx(targets[1], targets[0]) qc.cx(targets[2], targets[1]) qc = QuantumCircuit(3) make_initial_state(qc, "110") subspace_encoder_init110(qc, targets=[0,1,2]) qc.draw("mpl") def trotterize(qc, trot_gate, num_steps, targets): for _ in range(num_steps): qc.append(trot_gate, qargs = targets) qc = QuantumCircuit(3) make_initial_state(qc, "110") subspace_encoder_init110(qc, targets=[0,1,2]) qc.barrier() trotterize(qc, trotter_gate(np.pi / 6), 1, targets=[1, 2]) qc = transpile(qc, optimization_level = 3, basis_gates=["sx", "rz", "cx"]) qc.draw("mpl") # 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] qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) qc.h([1,2]) qc.cx(0,2) qc.barrier() subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, 10, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / 2}) t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t3_qc.draw("mpl") st_qcs_list = [] # Number of trotter steps max_trotter_step = 50 ### CAN BE >= 4 trotter_steps = list(range(1, max_trotter_step + 1, 3)) for num_steps in trotter_steps: 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, "101") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) st_qcs_list.append(t3_st_qcs) st_qcs_list[-1][-1].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") jobs = [] shots = 1 << 13 # Number of trotter steps for i, num_steps in enumerate(trotter_steps): print("trotter step: ", num_steps) # execute: reps = 1 job = execute(st_qcs_list[i], backend, shots=shots) print('Job ID', job.job_id()) jobs.append(job) print() # 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()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') results = [] for job in jobs: results.append( job.result() ) mit_results = [] for job in jobs: mit_results.append( meas_fitter.filter.apply(job.result()) ) print(len(results), len(mit_results)) # Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits def state_tomo(result, st_qcs): # The expected final state; necessary to determine state tomography fidelity target_state = (One^Zero^One).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Fit state tomography results tomo_fitter = StateTomographyFitter(result, st_qcs) rho_fit = tomo_fitter.fit(method='lstsq') # Compute fidelity fid = state_fidelity(rho_fit, target_state) return fid # Compute tomography fidelities for each repetition raw_fids = [] for result in results: fid = state_tomo(result, st_qcs) raw_fids.append(fid) # print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) # print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) plt.clf() plt.style.use('ggplot') plt.figure(dpi=200) plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps)) plt.plot(trotter_steps, raw_fids, label="raw fidelity") plt.plot(trotter_steps, fids, label="fidelity after QREM") plt.xlabel("number of trotter steps") plt.ylabel("fidelity") plt.grid(linestyle='dotted') for step, fid in zip(trotter_steps, raw_fids): print(step, fid) for step, fid in zip(trotter_steps, fids): print(step, fid)
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
VedDharkar
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 import * # Loading your IBM Q account(s) #provider = IBMQ.load_account() q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.measure(q, c) sim = Aer.get_backend('qasm_simulator') job = execute(qc, sim, shots=1024) result = job.result() counts = result.get_counts() counts #THERE ARE 3 WAYS TO CHECK MONITOR YOUR JOB #MONITOR JOB STATUS:- job.status() from qiskit.tools import * job_monitor(job) import qiskit.tools.jupyter %qiskit_job_watcher
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
from qiskit_chemistry import FermionicOperator, QMolecule from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit_chemistry import QMolecule as qm from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua import Operator from qiskit_aqua.algorithms import VQE, ExactEigensolver from qiskit import Aer from scipy import linalg as la import numpy as np import yaml as yml from yaml import SafeLoader as Loader import os import Load_Hamiltonians as lh ##Carefully upgrade terra to see if qasm/state-vector simulator perform quicker.## #################### WALK ROOT DIR ############################ #root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS' root_dir = 'IntegralData/H2_MEKENA' data_file_list = [] for dirName, subdirList, fileList in os.walk(root_dir): print('Found directory: %s' % dirName) for fname in sorted(fileList): if fname.endswith('.yaml'): data_file_list.append(fname) #This 'del' is four the 4-orbital case since the OEs are missing for the distance 13... #This should be resolved for the future #del data_file_list[-1] # print(data_file_list) # print(data_file_list_oe) #I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1 #If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name ############################################################### ############# Output Files to Plot stuff ############### print(data_file_list) Fout = open('H2_VQEEnergies_noMP2_4-orbitals_071519.dat',"w") Fout_op = open('H2_OptimalParams_noMP2_4-orbitals_071519.dat',"w") #Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w") ########################################################### #Variables that can be assigned outside of Loop map_type = str('jordan_wigner') truncation_threshold = 0.01 ################# IBM BACKEND ##################### backend1 = Aer.get_backend('statevector_simulator') backend2 = Aer.get_backend('qasm_simulator') ################################################### output_data = [] #Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact ind = 0 for key, file in enumerate(data_file_list): NW_data_file = str(os.path.join(root_dir,file)) print('First File', NW_data_file) try: doc = open(NW_data_file, 'r') data = yml.load(doc, Loader) finally: doc.close() #Import all the data from a yaml file print('Getting data') n_spatial_orbitals = data['integral_sets'][0]['n_orbitals'] print('{} spatial orbitals'.format(n_spatial_orbitals)) nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value'] print('{} Coloumb repulsion'.format(nuclear_repulsion_energy)) n_orbitals = 2 * n_spatial_orbitals n_particles = data['integral_sets'][0]['n_electrons'] print('{} particles'.format(n_particles)) dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2] print('Bond distance is {}'.format(dist)) if map_type == 'parity': # For two-qubit reduction n_qubits = n_orbitals - 2 else: n_qubits = n_orbitals # Populating the QMolecule class with the data to make calculations easier qm.num_orbitals = n_spatial_orbitals qm.num_alpha = n_particles // 2 qm.num_beta = n_particles // 2 qm.core_orbitals = 0 qm.nuclear_repulsion_energy = nuclear_repulsion_energy qm.hf_energy = data['integral_sets'][0]['scf_energy']['value'] #Importing the integrals one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values'] two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values'] #Getting spatial integrals and spin integrals to construct Hamiltonian one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import, two_electron_import, n_spatial_orbitals) one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals( one_electron_spatial_integrals, two_electron_spatial_integrals, .001) h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals, n_spatial_orbitals, truncation_threshold) #For the MP2 Calculation qm.mo_eri_ints = two_electron_spatial_integrals #Constructing the fermion operator and qubit operator from integrals data fop = FermionicOperator(h1, h2) qop_paulis = fop.mapping(map_type) print(qop_paulis) qop = Operator(paulis=qop_paulis.paulis) #Get Variational form and intial state # init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False) # var_op = UCCSD(n_qubits, 1, n_orbitals, n_particles, active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=map_type, mp2_reduction=False) # # ######################## VQE RESULT ############################### # # setup a classical optimizer for VQE # max_eval = 200 # optimizer = COBYLA(maxiter=max_eval, disp=True, tol=1e-2) # # #Choosing initial params based on previous iteration # if ind == 0: # # initial_params = var_op._mp2_coeff # initial_params = None # ind += 1 # elif len(vqe_params) == var_op.num_parameters: # initial_params = vqe_params # else: # initial_params = None # # # print('Doing VQE') # algorithm = VQE(qop_paulis,var_op,optimizer,'paulis', initial_point=initial_params, ) # #VQE_Circ = algorithm.construct_circuit(dumpy_params, backend1) # #print('The VQE circuit:\n',VQE_Circ) # result = algorithm.run(backend1) # vqe_energy = result['energy'] + nuclear_repulsion_energy # vqe_params = result['opt_params'] # # print('The VQE energy is: ',vqe_energy) # # print('The optimized params are {}.'.format(vqe_params)) # ################################################################### # # ################### EXACT RESULT ################################## # exact_eigensolver = ExactEigensolver(qop, k=2) # ret = exact_eigensolver.run() # print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real)) # print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy)) # exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy # exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy # qop.to_matrix() # #print(qop) # # eigval, eigvec = np.linalg.eigh(qop.matrix.toarray()) # # exact_energy = eigval[0].real + nuclear_repulsion_energy # # exact_energy_fe = eigval[1].real + nuclear_repulsion_energy # # print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real)) # # print('Groundstate: \n', eigv[:,0]) # # print('First excited state: \n', eigv[:, 0]) # ################################################################### # # The outputs to plot # my_info = [dist,exact_energy,vqe_energy] # param_info = [dist,vqe_params] # # my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\ # # + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \ # # eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \ # # eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy] # output_data.append(my_info) # my_info_to_str = " ".join(str(e) for e in my_info) # params_to_str = " ".join(str(e) for e in param_info) # Fout.write(my_info_to_str + "\n") # Fout_op.write(params_to_str + "\n") print(output_data) Fout.close() Fout_op.close() # output_data[:,0] = np.sort(output_data[:,0],axis=0) # print(output_data)
https://github.com/rigetti/qiskit-rigetti
rigetti
############################################################################## # Copyright 2021 Rigetti Computing # # 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. ############################################################################## from qiskit import QuantumRegister from qiskit.circuit import Qubit from qiskit_rigetti.gates import ( CanonicalGate, CPhase00Gate, CPhase01Gate, CPhase10Gate, PSwapGate, XYGate, ) from qiskit_rigetti import QuilCircuit def test_xy(): circuit = QuilCircuit(2, 2) circuit.xy(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( XYGate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_piswap(): circuit = QuilCircuit(2, 2) circuit.piswap(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( XYGate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_pswap(): circuit = QuilCircuit(2, 2) circuit.pswap(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( PSwapGate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_cphase00(): circuit = QuilCircuit(2, 2) circuit.cphase00(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( CPhase00Gate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_cphase01(): circuit = QuilCircuit(2, 2) circuit.cphase01(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( CPhase01Gate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_cphase10(): circuit = QuilCircuit(2, 2) circuit.cphase10(3.14, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( CPhase10Gate(3.14), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], ) def test_can(): circuit = QuilCircuit(2, 2) circuit.can(3.14, 42.0, 1.62, 0, 1) assert len(circuit.data) == 1 assert circuit.data[0] == ( CanonicalGate(3.14, 42.0, 1.62), [Qubit(QuantumRegister(2, "q"), 0), Qubit(QuantumRegister(2, "q"), 1)], [], )
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. 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) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import GaussianForcesDriver # if you ran Gaussian elsewhere and already have the output file driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") # if you want to run the Gaussian job from Qiskit # driver = GaussianForcesDriver( # ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight', # '', # 'CO2 geometry optimization B3LYP/6-31g', # '', # '0 1', # 'C -0.848629 2.067624 0.160992', # 'O 0.098816 2.655801 -0.159738', # 'O -1.796073 1.479446 0.481721', # '', # '' from qiskit_nature.second_q.problems import HarmonicBasis basis = HarmonicBasis([2, 2, 2, 2]) from qiskit_nature.second_q.problems import VibrationalStructureProblem from qiskit_nature.second_q.mappers import DirectMapper vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() print(main_op) qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) basis = HarmonicBasis([3, 3, 3, 3]) vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) # for simplicity, we will use the smaller basis again vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2])) vibrational_problem.hamiltonian.truncation_order = 2 from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver solver = GroundStateEigensolver( qubit_mapper, NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()), ) result = solver.solve(vibrational_problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) plot_circuit_layout(new_circ_lv0, backend)
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit,execute,Aer from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.operators import Operator from math import log,cos,sin,sqrt,pi,exp import matplotlib.pyplot as plt from numpy import kron,matmul,transpose,conjugate,zeros,trace,complex128,array,inf,linspace,abs from time import time from scipy.linalg import expm from random import random from scipy.fft import fft from scipy import integrate import xlsxwriter from tqdm import tqdm H=[[1/sqrt(2),1/sqrt(2)],[1/sqrt(2),-1/sqrt(2)]] X=[[0,1],[1,0]] ID=[[1,0],[0,1]] DM0=[[1,0],[0,0]] DM1=[[0,0],[0,1]] Y=[[0,-1j],[1j,0]] Z=[[1,0],[0,-1]] CX=[[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]] ket=[[[1],[0]],[[0],[1]],ID] CH=[[1,0,0,0],[0,1/sqrt(2),0,1/sqrt(2)],[0,0,1,0],[0,1/sqrt(2),0,-1/sqrt(2)]] def RX(t): return [[cos(t),-1j*sin(t)],[-1j*sin(t),cos(t)]] def twoQubitState(t):# Parametrized two qubit state # twoQubitState(t)|00>=cost|00>-isint|11> #CH=kron(DM0,ID)+kron(DM1,H) #return [[cos(t)],[0],[0],[-1j*sin(t)]] #return matmul(CH,kron(RX(t),ID)) return matmul(CX,kron(RX(t),ID)) def WState(t):# Parametrized three qubit W State # cos(theta)|100>+sin(theta)/sqrt(2)|010>+sin(theta)/sqrt(2)|001> XNCNC=kron(ID,kron(DM1,DM1))+kron(ID,kron(DM0,DM1))+kron(ID,kron(DM1,DM0))+kron(X,kron(DM0,DM0)) U=matmul(kron(kron(DM0,ID)+kron(DM1,Y),ID),kron(RX(t),kron(ID,ID))) U=matmul(kron(ID,kron(DM0,ID)+kron(DM1,H)),U) U=matmul(kron(kron(ID,DM0)+kron(X,DM1),ID),U) U=matmul(kron(ID,kron(ID,DM0)+kron(X,DM1)),U) U=matmul(XNCNC,U) return U def M(p,q):# function for nQubitWState return [[sqrt(p)/sqrt(p+q),sqrt(q)/sqrt(p+q)],[-sqrt(q)/sqrt(p+q),sqrt(p)/sqrt(p+q)]] def spaceExpansion(mat,n,idx):# function for nQubitWState if idx[0]>0: for _ in range(idx[0]): mat=kron(ID,mat) if idx[-1]<n-1: for _ in range(idx[-1]+1,n): mat=kron(mat,ID) return mat def nQubitWState(n): m=M(1,n-1) m=spaceExpansion(m,n,[0]) for i in range(1,n-1): mat=kron(DM0,ID)+kron(DM1,M(1,n-1-i)) mat=spaceExpansion(mat,n,[i-1,i]) m=matmul(mat,m) for i in range(n-1,0,-1): mat=spaceExpansion(CX,n,[i-1,i]) m=matmul(mat,m) m=matmul(spaceExpansion(X,n,[0]),m) return m def nQubitGHZState(n):# of course n must be at least 2, otherwise what do you want? U=matmul(CX,kron(H,ID)) newCX=kron(ID,CX) while n>2: U=kron(U,ID) U=matmul(newCX,U) newCX=kron(ID,newCX) n-=1 return U def D2B(n,N): # n current number # N maximum # to make sure the output have the same length l=int(log(N,2)) opt=[] for i in range(l): if n <2**(l-i-1):opt.append(0) else: opt.append(1) n-=2**(l-i-1) return opt def B2D(li): l=len(li) res=0 for i in range(l):res+=li[i]*2**(l-i-1) return res def D2Q(num,length):# convert decimal number to quaternary number res=[0 for _ in range(length)] for i in range(length-1,-1,-1): if num>=4**i: res[length-i-1]=int((num-num%(4**i))/4**i) num=num%(4**i) return res def mulKron(ops): res=ops[0] for i in range(1,len(ops)):res=kron(res,ops[i]) return res def listStringSum(li): text=li[0] for i in range(1,len(li)):text+=li[i] return text def PauliDecomposition(Ham): n=int(log(len(Ham),2)) set=[ID,X,Y,Z] dic={0:'I',1:'X',2:'Y',3:'Z'} nQubitPauli=[] remaindOps=[] coes=[] for i in range(4**n): idx=D2Q(i,n) ops=mulKron([set[idx[i]] for i in range(n)]) temp=trace(matmul(ops,Ham))/(2**n) if temp!=0: coes.append(temp) nQubitPauli.append([dic[idx[i]] for i in range(n)]) remaindOps.append(ops) print(f'number of nonzero term(s): {len(coes)}') for i in range(len(coes)):print(f'operator: {listStringSum(nQubitPauli[i])}, coefficient: {coes[i]}') def quad(li):# hamiltonian companian function to avoid shallow copy res=[]# there are specific deep copy, from copy import deepcopy for j in range(len(li)): for _ in range(4):res.append([li[j][0],li[j][1]]) return res def hamiltonian(num_qubit,idle): # this Hamiltonian calculates Tr(rho^2_gamma) # the variable num_qubit is actually half the number of qubit required loc=idle if isinstance(idle,int):loc=[idle] dim=2**(2*num_qubit) Har=[[0 for _ in range(dim)] for _ in range(dim)] # the list jk denotes the jk part of |ijk ijk> initially, # and finally it turns to |ijk i'jk> jk=[[D2B(i,2**(num_qubit-len(loc)))*2,D2B(j,2**(num_qubit-len(loc)))*2] for i in range(2**(num_qubit-1)) for j in range(2**(num_qubit-1))] for i in range(len(loc)): jk=quad(jk) for j in range(len(jk)): c=j%4 jk[j][0]=jk[j][0][:loc[i]]+[int(c/2)]+jk[j][0][loc[i]:loc[i]+num_qubit-1]+[c%2]+jk[j][0][loc[i]+num_qubit-1:] jk[j][1]=jk[j][1][:loc[i]]+[int(c/2)]+jk[j][1][loc[i]:loc[i]+num_qubit-1]+[c%2]+jk[j][1][loc[i]+num_qubit-1:] for i in range(len(jk)):Har[B2D(jk[i][0])][B2D(jk[i][1])]=1 return Har def densityMatrix(state): dm=[] for i in range(len(state)): dm.append([]) for j in range(len(state)): dm[i].append(complex(state[i]*conjugate(state[j]))) return dm def partialTrace(state,idle): # idle here refers to those traced qubits. n=int(log(len(state),2)) traceList=[i for i in range(n) if i not in idle] li=[] for i in range(n): if i in traceList:li.append(0) else:li.append(1) N=2**sum(li) # number of basis rho=densityMatrix(state) res=complex128(zeros([2**len(traceList),2**len(traceList)])) for i in range(N): li=D2B(i,N) for j in traceList: li.insert(j,2) basis=ket[li[-1]] for k in range(n-2,-1,-1): basis=kron(ket[li[k]],basis) res+=matmul(transpose(basis),matmul(rho,basis)) return res def swapTestRes(ipt,rep): trrho2=2*ipt['0']/rep-1 # the try sentence isn't required here, p0>=0.5 return sqrt(2*(1-trrho2)) def swapTest(u0,idle,rep=10**6): n=int(log(len(u0),2)) u0=Operator(u0) ctrl=QuantumRegister(1) d0Reg=QuantumRegister(n) d1Reg=QuantumRegister(n) c2Reg=ClassicalRegister(1) qc=QuantumCircuit(ctrl,d0Reg,d1Reg,c2Reg) qc.append(u0,[d0Reg[i] for i in range(n)]) qc.append(u0,[d1Reg[i] for i in range(n)]) qc.h(ctrl) for i in range(n): if i not in idle: qc.cswap(ctrl,d0Reg[i],d1Reg[i]) qc.h(ctrl) qc.barrier() qc.measure(ctrl,c2Reg) simulator=Aer.get_backend('qasm_simulator') res=execute(qc,simulator,shots=rep).result().get_counts() return swapTestRes(res,rep) def WStateConcurrence(N,k): # the GME concurrence has a simple formula, # it only depends on the number of qubits N # and the number of idle qubits k return sqrt(2*(1-(N**2-2*N*k+2*k**2)/N/N)) def completes(ele,otherPart,N):# to check whether a term should be added to idle for i in range(len(otherPart)): if len(ele)+len(otherPart[i])==N: temp=ele+otherPart[i] count=0 for j in range(N): if j in temp:count+=1 if count>=N:return False if len(ele)==len(otherPart[i]): count1=0 for j in range(len(ele)): if ele[j] in otherPart[i]:count1+=1 if count1==len(ele):return False return True def genPartition(N):# for n qubits, 2^(n-1)-1 terms for n>2 n=int(N/2) li=[[i] for i in range(N)] idles=[[i] for i in range(N)] for i in range(1,n+1): temp=[[j] for j in range(N)] for j in range(i-1): for k in range(len(temp)): if len(temp[k])==j+1: for l in range(N): if li[l][0] not in temp[k]:temp.append(temp[k]+li[l]) for j in range(N,len(temp)): if completes(temp[j],idles,N) and temp[j] not in idles: idles.append(temp[j]) return idles def expectation(state,ham,time,rep): eiht=expm(time*1j*array(ham)) dm=densityMatrix(kron(state,state)) return trace(matmul(eiht,dm))*(1+(1-2*random())/sqrt(rep)) def h(x): if x**2>=1:return 0 else:return exp(-1/(1-x**2)) def window(x): if x>=0 and x<1:return 1 else:return 0 def fUnint(xp): return 5*h(2*xp-point)*window(xp)#/4.05 def F(x,num_sample): coes=[] xs=[x-2*(num_sample-m)/num_sample for m in range(num_sample)]+[x+2*m/num_sample for m in range(num_sample)] #xs=[-x/2+x*i/num_sample for i in range(len(num_sample))] #print(f'xs:{xs}') global point for i in range(len(xs)): point=xs[i] coes.append(integrate.quad(fUnint,-inf,inf)[0]) coes=fft(coes) return coes def timeSeries(theta,num_qubit=3,num_sample=50,rep=10**5): exp_TS=[] coes=F(0.75,num_sample) for i in range(len(theta)): if num_qubit==3:unitary=WState(theta[i]) else:unitary=twoQubitState(theta[i]) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) exp=[] for j in range(-num_sample,num_sample): exp.append(coes[j]*expectation(state,array(hamiltonian(num_qubit,0)),j,rep)) exp_TS.append(sum(exp)) #norm=exp_TS[0] norm=max(exp_TS) for i in range(len(exp_TS)):exp_TS[i]/=norm#sqrt(2*(1-exp_TS[i]/norm)) return exp_TS def varyingTheta(num_points=100,num_qubit=3,rep=10**4): #theta=[i*pi/(num_points-1) for i in range(num_points-1)]+[pi] theta=linspace(0,pi/2,num_points) idle=genPartition(num_qubit) GME_Classical=[] GME_Quantum=[] for i in range(num_points): if num_qubit==3:unitary=WState(theta[i]) else:unitary=twoQubitState(theta[i]) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) #print(state) iGME=[] qGME=[] for j in range(len(idle)): pdm=partialTrace(state,idle[j]) #print(pdm) temp=2*(1-trace(matmul(pdm,pdm))) #print(temp) #temp=trace(matmul(pdm,pdm)) if abs(temp.imag)>1e-7:print('imaginary part might exist') iGME.append(sqrt(abs(temp))) swap_test_res=swapTest(unitary,idle[j],rep) qGME.append(swap_test_res) GME_Classical.append(min(iGME)) GME_Quantum.append(min(qGME)) #GME_Har.append(min(hGME)) x=[theta[i]/pi for i in range(num_points)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') GME_TS=timeSeries(theta,num_qubit,10**2,rep) for i in range(len(GME_TS)):GME_TS[i]=sqrt(2*(1-GME_TS[i])) plt.plot(x,GME_TS,'g*',label='time series') plt.xlabel(r'$\theta/\pi$') plt.ylabel('GME Concurrence') #plt.ylabel('purity') plt.legend(loc='best') plt.savefig('with time series.png') plt.savefig('with time series.eps',format='eps') plt.show() varyingTheta(101,2,10**4) def varyingQubit(rep=10**4): start=2 end=5 GME_Classical=[] GME_Quantum=[] for num_qubit in range(start,end): print(f'{num_qubit}-qubit GME concurrence') idle=genPartition(num_qubit) unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) iGME=[] qGME=[] t0=0 print(len(idle)) for j in tqdm(range(len(idle))): pdm=partialTrace(state,idle[j]) temp=2*(1-trace(matmul(pdm,pdm))) if abs(temp.imag)>1e-5: print('imag part goes high') iGME.append(sqrt(temp.real)) t1=time() qGME.append(swapTest(unitary,idle[j],rep)) t2=time() t0+=t2-t1 print(f'{num_qubit}-qubit GME concurrence requires time: {t0}') GME_Classical.append(min(iGME)) GME_Quantum.append(min(qGME)) x=[i for i in range(start,end)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') plt.xlabel('number of qubits') plt.ylabel('GME Concurrence') plt.legend(loc='best') plt.show() #plt.savefig('n qubit w state.png') #plt.savefig('n qubit w state.eps',format='eps') #varyingQubit(10**4) def unnecessaryBipartitions(rep=10**4): # for W state and GHZ state, they are highly symmetrical, it is reasonable to # assume that a lot of bipartitions give the same result. start=2 end=13 y1=[] y2=[] for num_qubit in range(start,end): idle=genPartition(num_qubit) unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) for j in range(len(idle)-1): if len(idle[j])!=len(idle[j+1]): print(f'idle qubits:{idle[j]}') pdm=partialTrace(state,idle[j]) temp=2*(1-trace(matmul(pdm,pdm))) y1.append(temp) if abs(temp.imag)>1e-5: print('imag part goes high') print(f'partial trace result: {sqrt(temp.real)}') print(f'formula result: {WStateConcurrence(num_qubit,len(idle[j]))}') y2.append(WStateConcurrence(num_qubit,len(idle[j]))) x=[i for i in range(len(y1))] plt.plot(x,y1,'r') plt.plot(x,y2,'bo') plt.show() #unnecessaryBipartitions() def varyingQubitWithFewerBipartition(rep=10**4): start=2 end=16 GME_Classical=[] GME_Quantum=[] idle=[0] t0=time() for num_qubit in range(start,end): unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) pdm=partialTrace(state,idle) temp=2*(1-trace(matmul(pdm,pdm))) if abs(temp.imag)>1e-5: print('imag part goes high') GME_Classical.append(sqrt(temp.real)) print(f'current precise result: {GME_Classical[-1]}') t2=time() GME_Quantum.append(swapTest(unitary,idle,rep)) t3=time() print(f'current C-Swap result: {GME_Quantum[-1]}') print(f'time spent for {2*num_qubit} swap test: {t3-t2}s') t1=time() print(f'time spent: {t1-t0}s') print(f'current precise result: {GME_Classical}') print(f'current approximate result: {GME_Quantum}') x=[i for i in range(start,end)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') plt.xlabel('number of qubits') plt.ylabel('GME Concurrence') plt.legend(loc='best') plt.savefig('n qubit w state with one bipartition.png') plt.savefig('n qubit w state with one bipartition.eps',format='eps') plt.show() #varyingQubitWithFewerBipartition(10**5)
https://github.com/ShabaniLab/qiskit-hackaton-2019
ShabaniLab
import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from ising_kitaev import initialize_chain, trotter, rotate_to_measurement_basis, add_measurement, initialize_coupler zeeman_ferro = 0.01 zeeman_para = 10 initial_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro]) qreg = QuantumRegister(5) creg = ClassicalRegister(3) qcirc = QuantumCircuit(qreg, creg) initialize_chain(qcirc, qreg, initial_config, 'logical_one') initialize_coupler(qcirc, qreg) qcirc.draw() trotter(qcirc, qreg, initial_config, 1.4, 0.1, 1) qcirc.draw() trotter(qcirc, qreg, initial_config, 0.0, 0.1, 1) rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3]) add_measurement(qcirc, qreg, creg, [1, 2, 3]) qcirc.draw() from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') job = execute(qcirc, backend, shots=2000) job.status() result = job.result() print(result.get_counts())
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name,missing-docstring # pylint: disable=attribute-defined-outside-init from qiskit import transpile from qiskit.circuit.library.standard_gates import XGate from qiskit.transpiler import CouplingMap from qiskit.transpiler import InstructionDurations from qiskit.transpiler.passes import ( TimeUnitConversion, ASAPSchedule, ALAPSchedule, DynamicalDecoupling, ) from qiskit.converters import circuit_to_dag from .utils import random_circuit class SchedulingPassBenchmarks: params = ([5, 10, 20], [500, 1000]) param_names = ["n_qubits", "depth"] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit( n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed, max_operands=2 ) self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"] self.cmap = [ [0, 1], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [3, 2], [3, 4], [3, 8], [4, 3], [5, 6], [5, 10], [6, 1], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 3], [8, 7], [8, 9], [9, 8], [9, 14], [10, 5], [10, 11], [11, 10], [11, 12], [11, 16], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [13, 18], [14, 9], [14, 13], [15, 16], [16, 11], [16, 15], [16, 17], [17, 16], [17, 18], [18, 13], [18, 17], [18, 19], [19, 18], ] self.coupling_map = CouplingMap(self.cmap) self.transpiled_circuit = transpile( self.circuit, basis_gates=self.basis_gates, coupling_map=self.coupling_map, optimization_level=1, ) self.dag = circuit_to_dag(self.transpiled_circuit) self.durations = InstructionDurations( [ ("rz", None, 0), ("id", None, 160), ("sx", None, 160), ("x", None, 160), ("cx", None, 800), ("measure", None, 3200), ("reset", None, 3600), ], dt=1e-9, ) self.timed_dag = TimeUnitConversion(self.durations).run(self.dag) _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" self.scheduled_dag = _pass.run(self.timed_dag) def time_time_unit_conversion_pass(self, _, __): TimeUnitConversion(self.durations).run(self.dag) def time_alap_schedule_pass(self, _, __): _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_asap_schedule_pass(self, _, __): _pass = ASAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_dynamical_decoupling_pass(self, _, __): DynamicalDecoupling(self.durations, dd_sequence=[XGate(), XGate()]).run(self.scheduled_dag)