repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/darkn3to/dinner-problem
|
darkn3to
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/Subhamdg/QAOA_qiskit_MAXCUT
|
Subhamdg
|
%%capture
!pip install qiskit
from qiskit import *
import numpy as nm
import math
import matplotlib.pyplot as plt
import networkx as nx
v=nm.arange(0,8,1)
e=[(0,1,1),(1,3,4),(1,3,1),(0,5,2),(2,4,7),(3,4,6),(4,5,3),(4,6,4),(2,6,3),(3,6,1),(4,7,5),(6,7,1),(1,7,2)]
g=nx.Graph()
g.add_nodes_from(v)
g.add_weighted_edges_from(e)
nx.draw_networkx(g)
step=0.05
g=b=nm.arange(0,math.pi,step)
g,b=nm.meshgrid(g,b)
k=3-((nm.sin(2*b)**2)*(nm.sin(2*g)**2)-(0.5*nm.sin(4*b))*(nm.sin(4*g)))*(1+nm.cos(4*g)**2)
res=nm.where(k==nm.amax(k))
a=list(zip(res[0],res[1]))[0]
gam=a[0]*step;
bet=a[1]*step;
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(g,b,k,cmap=cm.coolwarm,linewidth=0,antialiased=True)
plt.show()
pi=math.pi
q=QuantumRegister(len(v))
c=ClassicalRegister(len(v))
qc=QuantumCircuit(q,c)
for i in range(len(v)):
qc.u3(pi/2,0,pi,q[i])
qc.barrier()
for i in e:
k = i[0]
l = i[1]
qc.u3(0,0,-gam,q[l])
qc.cx(q[l],q[k])
qc.u3(0,0,gam,q[k])
qc.cx(q[l],q[k])
qc.u3(0,0,-gam,q[k])
qc.u3(0,0,gam, k)
qc.u3(0,0,gam, l)
qc.barrier()
for i in range(len(v)):
qc.u3(2*bet,3*pi/2,pi/2,q[i])
qc.barrier()
for i in range(len(v)):
qc.measure(q[i],c[i])
qc.draw(output="mpl")
sim = Aer.get_backend('qasm_simulator')
res=execute(qc, backend=sim).result()
from qiskit.visualization import plot_histogram as ph
ph(res.get_counts(qc),figsize=(150,50))
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
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
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=1, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
from qiskit import *
from qiskit import Aer
from qiskit.aqua.operators import StateFn
from qiskit.circuit import Parameter, QuantumCircuit
from qiskit.quantum_info import Operator
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
######## パラメータ #############
nqubit = 3 ## qubitの数
c_depth = 3 ## circuitの深さ
# 横磁場イジングモデルのパラメーター
time_step = 0.77 ## ランダムハミルトニアンによる時間発展の経過時間
h = 3 # 外部磁場
#### 教師データを準備
## [x_min, x_max]でランダムにnum_x_train個の点を生成
x_min = - 1.; x_max = 1.;
num_x_train = 50
## 学習したい1変数関数
func_to_learn = lambda x: np.sin(x*np.pi)
random_seed = 0 ## 乱数のシード
np.random.seed(random_seed) ## 乱数発生器の初期化
x_train = x_min + (x_max - x_min) * np.random.rand(num_x_train)
y_train = func_to_learn(x_train)
# 現実のデータを用いる場合を想定しノイズを付加
mag_noise = 0.05
y_train = y_train + mag_noise * np.random.randn(num_x_train)
plt.plot(x_train, y_train, "o"); plt.show()
# 初期状態の準備
q = QuantumCircuit(nqubit)
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
# xをエンコード
def U_in(x):
U = QuantumCircuit(nqubit)
angle_y = np.arcsin(x)
angle_z = np.arccos(x**2)
for i in range(nqubit):
U.ry(angle_y, i)
U.rz(angle_z, i)
return U
## 基本ゲート
backend = Aer.get_backend('unitary_simulator')
I_mat = np.eye(2, dtype=complex)
q = QuantumCircuit(1)
q.x(0)
job = execute(q, backend)
X_mat = job.result().get_unitary(q, decimals=3)
q = QuantumCircuit(1)
q.z(0)
job = execute(q, backend)
Z_mat = job.result().get_unitary(q, decimals=3)
##### quantum native dojoから引用 #####
## fullsizeのgateをつくる関数.
def make_fullgate(list_SiteAndOperator, nqubit):
'''
list_SiteAndOperator = [ [i_0, O_0], [i_1, O_1], ...] を受け取り,
関係ないqubitにIdentityを挿入して
I(0) * ... * O_0(i_0) * ... * O_1(i_1) ...
という(2**nqubit, 2**nqubit)行列をつくる.
'''
list_Site = [SiteAndOperator[0] for SiteAndOperator in list_SiteAndOperator]
list_SingleGates = [] ## 1-qubit gateを並べてnp.kronでreduceする
cnt = 0
for i in range(nqubit):
if (i in list_Site):
list_SingleGates.append( list_SiteAndOperator[cnt][1] )
cnt += 1
else: ## 何もないsiteはidentity
list_SingleGates.append(I_mat)
return reduce(np.kron, list_SingleGates)
##### quantum native dojoから引用 #####
ham = np.zeros((2**nqubit,2**nqubit), dtype = complex)
for i in range(nqubit): ## i runs 0 to nqubit-1
Jx = -1. + 2.*np.random.rand() ## -1~1の乱数
ham += Jx * make_fullgate( [ [i, X_mat] ], nqubit)
for j in range(i+1, nqubit):
J_ij = -1. + 2.*np.random.rand()
ham += J_ij * make_fullgate ([ [i, Z_mat], [j, Z_mat]], nqubit)
## 対角化して時間発展演算子をつくる. H*P = P*D <-> H = P*D*P^dagger
diag, eigen_vecs = np.linalg.eigh(ham)
time_evol_op = np.dot(np.dot(eigen_vecs, np.diag(np.exp(-1j*time_step*diag))), eigen_vecs.T.conj()) # e^-iHT
## 時間発展演算子が2**3=8次の行列であることを確認
time_evol_op.shape
## 変分量子回路U(\theta)の構築
def U_out(param_list):
qc = QuantumCircuit(nqubit)
for d in range(c_depth):
# 時間発展演算子を回路に組み込む
qc.unitary(Operator(time_evol_op), range(nqubit), label="time_evol")
# パラメーター回転ゲートを導入
for i in range(nqubit):
qc.rx(-2*param_list[3*i], i)
qc.rz(-2*param_list[3*i+1], i)
qc.rx(-2*param_list[3*i+2], i)
return qc
# モデルの出力
# 出力状態において最初の量子ビットのZでの期待値を計算
from qiskit.aqua.operators import Z, I
def qcl_pred(x, param_list):
# 回路を一つにまとめる
qcl_cirq = U_in(x) + U_out(param_list)
obs = Z ^ I ^ I
psi = StateFn(qcl_cirq)
expectation_value = (~psi @ obs @ psi).eval()
return expectation_value.real
# コスト関数Lを計算
def cost_func(theta):
# num_x_train個のデータについて計算
y_pred = [qcl_pred(x, theta) for x in x_train]
# quadratic loss
L = ((y_pred - y_train)**2).mean()
return L
# パラメータthetaの初期値theta_initにおけるコスト関数の値
# theta: 長さc_depth * nqubit * 3のndarray
theta_init = [2.0 * np.pi * np.random.rand() for i in range(c_depth*nqubit*3)]
cost_func(theta_init)
# パラメータthetaの初期値のもとでのグラフ
xlist = np.arange(x_min, x_max, 0.02)
y_init = [qcl_pred(x, theta_init) for x in xlist]
plt.plot(xlist, y_init)
from scipy.optimize import minimize
# 学習(注意:数時間かかりました)
result = minimize(cost_func, theta_init, method='Nelder-Mead')
theta_opt = result.x
print(theta_opt)
# プロット
plt.figure(figsize=(10, 6))
xlist = np.arange(x_min, x_max, 0.02)
# 教師データ
plt.plot(x_train, y_train, "o", label='Teacher')
# パラメータθの初期値のもとでのグラフ
plt.plot(xlist, y_init, '--', label='Initial Model Prediction', c='gray')
# モデルの予測値
y_pred = np.array([qcl_pred(x, theta_opt) for x in xlist])
plt.plot(xlist, y_pred, label='Final Model Prediction')
plt.legend()
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import matplotlib
import networkx
import numpy
import sklearn
import scipy
import dwave_networkx
import dimod
import minorminer
import qiskit
import qiskit_aqua
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
import sys
sys.path.append('../../')
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import I, X, Y, Z
import matplotlib.pyplot as plt
from volta.observables import sample_hamiltonian
from volta.hamiltonians import BCS_hamiltonian
EPSILONS = [3, 3, 3, 3]
V = -2
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) #BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix())
print(f"Eigenvalues: {eigenvalues}")
def create_circuit(n: int) -> list:
return [QuantumCircuit(n) for _ in range(2)]
n = hamiltonian.num_qubits
init_states = create_circuit(n)
def copy_unitary(list_states: list) -> list:
out_states = []
for state in list_states:
out_states.append(state.copy())
return out_states
import textwrap
def apply_initialization(list_states: list) -> None:
for ind, state in enumerate(list_states):
b = bin(ind)[2:]
if len(b) != n:
b = '0'*(n - len(b)) + b
spl = textwrap.wrap(b, 1)
for qubit, val in enumerate(spl):
if val == '1':
state.x(qubit)
apply_initialization(init_states)
initialization = copy_unitary(init_states)
from qiskit.circuit.library import TwoLocal
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None:
for states in list_states:
states.append(ansatz, range(n))
apply_ansatz(ansatz, init_states)
init_states[-1].draw('mpl')
def _apply_varform_params(ansatz, params: list):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = ansatz
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(params), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
def cost_function(params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
w = np.arange(len(init_states), 0, -1)
for i, state in enumerate(init_states):
qc = _apply_varform_params(state, params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += w[i] * hamiltonian_eval
return cost
from qiskit.aqua.components.optimizers import COBYLA
optimizer = COBYLA()
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost_function,
initial_point=params)
mean_energy, sum(eigenvalues[:2])
# Optimized first ansatz
ansatz_1 = _apply_varform_params(ansatz, optimal_params)
ansatz_1.name = 'U(θ)'
def cost_function_ind(ind: int, params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
qc = _apply_varform_params(init_states[ind], params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += hamiltonian_eval
return cost
energies = []
for i in range(len(init_states)):
energies.append(cost_function_ind(ind=i, params=optimal_params))
energies = np.array(energies)
for i in range(len(init_states)):
print(f"Value for the {i} state: {energies[i]}\t expected energy {eigenvalues[i]}")
|
https://github.com/drobiu/quantum-project
|
drobiu
|
"""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 demonstrate conditional gate execution.
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-19 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os
from qiskit import BasicAer, execute
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/')
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="conditional")
qc.h(q[0])
qc.h(q[1]).c_if(c0, 0) # h-gate on q[1] is executed
qc.h(q[2]).c_if(c1, 1) # h-gate on q[2] is not executed
qc.measure(q[0], c0)
qc.measure(q[1], c1)
qc.measure(q[2], c2)
qi_job = execute(qc, backend=qi_backend, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts(qc))
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""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/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, BasicAer
from qiskit.circuit.library import QFT
from IPython.core.display import Image, display
#INITIALISE THE QUANTUM AND CLASSICAL REGISTERS
q = QuantumRegister(4,'q')
c = ClassicalRegister(3,'c')
circuit1 = QuantumCircuit(q,c)
#PUT THE COUNTING QUBITS IN TO SUPERPOSITION
circuit1.h(q[0])
circuit1.h(q[1])
circuit1.h(q[2])
circuit1.x(q[3]) # Flips Q[3] to 1
circuit1.draw('mpl')
pi= np.pi
angle = 2*pi/3 #The phase angle we wish to encode
actual_phase = angle/(2*pi) # This is the actual phase rotation ie 0.5 would be half a rotation.
#Our expected rotation will be 0.33.
circuit1.cu1(angle, q[0], q[3]);#where angle is the rotation amount, q[0] is the control qubit and q[3] is the target qubit
circuit1.cu1(angle, q[1], q[3]);
circuit1.cu1(angle, q[1], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.barrier()
circuit1.draw('mpl')
circuit1.swap(q[0],q[2])
circuit1.h(q[0])
circuit1.cu1(-pi/2, q[0], q[1]);
circuit1.h(q[1])
circuit1.cu1(-pi/4, q[0], q[2]);
circuit1.cu1(-pi/2, q[1], q[2]);
circuit1.h(q[2])
circuit1.barrier()
circuit1.draw('mpl')
#### Measuring counting qubits ####
circuit1.measure(q[0],0)
circuit1.measure(q[1],1)
circuit1.measure(q[2],2)
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend('qasm_simulator')
counts = execute(circuit1, backend=simulator, shots=1000).result().get_counts(circuit1)
plot_histogram(counts)
maxcounts = max(counts, key=counts.get) # take the most often obtaned result
print(maxcounts)
a=int(maxcounts, 2)#convert to decimal
print(a)
print('Most frequent measurement: ',a,'\n')
n=3
phase = a/(2**n)# The calculation used to estimate the phase
print('Actual phase is: ',actual_phase)
print('Estimated phase is: ',phase)
|
https://github.com/davidedellagiustina/qasp-solver
|
davidedellagiustina
|
'''Utility functions for simulating quantum circuits.
'''
from qiskit import QuantumCircuit, transpile
from qiskit.synthesis import generate_basic_approximations
from qiskit.transpiler.passes.synthesis import SolovayKitaev
from qiskit_aer import Aer, AerJob
def exec_circuit(circ: QuantumCircuit, shots: int = 1) -> AerJob:
'''Execute a quantum circuit and retrieve the execution result.
#### Arguments
circ (QuantumCircuit): Circuit to simulate.
shots (int): Number of experiment repetitions to simulate. Defaults to 1.
#### Return
AerJob: Result of the simulation.
'''
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
result = simulator.run(circ, shots=shots).result()
return result
def transpile_into_clifford_t_basis(
circ: QuantumCircuit,
approx_depth: int = 3,
sk_rec: int = 2,
opt_lv: int = 3,
) -> QuantumCircuit:
'''Transpile and decompose a given circuit into the Clifford+T basis.
#### Arguments
circ (QuantumCircuit): Quantum circuit to be transpiled.
approx_depth (int): Gates approximation depth. Defaults to 3.
sk_rec (int): Recursion degree for the Solovay-Kitaev decomposition algorithm. Defaults to
2.
opt_lv (int): Optimization level for the transpiling process. Defaults to 3.
#### Return
QuantumCircuit: Transpiled circuit.
'''
universal_basis = ['u1', 'u2', 'u3', 'cx']
clifford_t_basis = ['h', 's', 't']
basis = generate_basic_approximations(clifford_t_basis, depth=approx_depth)
skd = SolovayKitaev(recursion_degree=sk_rec, basic_approximations=basis)
transpiled = transpile(
circ, basis_gates=universal_basis, optimization_level=opt_lv)
decomposed = skd(transpiled)
return decomposed
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
%run ../version.ipynb
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
qiskit.__qiskit_version__
grover11=QuantumCircuit(2,2)
grover11.draw(output='mpl')
# 問題-1 上の回路図を作ってください。
grover11.draw(output='mpl')
# 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。
grover11.draw(output='mpl')
#問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。
grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。
grover11.draw(output='mpl')
grover11.measure(0,0)
grover11.measure(1,1)
grover11.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator') # 実行環境の定義
job = execute(grover11, backend) # 処理の実行
result = job.result() # 実行結果
counts = result.get_counts(grover11) # 実行結果の詳細を取り出し
print(counts)
from qiskit.visualization import *
plot_histogram(counts) # ヒストグラムで表示
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, QuantumRegister
qrx = QuantumRegister(3, 'x')
qry = QuantumRegister(1, 'y')
qc = QuantumCircuit(qrx, qry)
qc.x(qry)
qc.draw("mpl")
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
import numpy as np
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
from circuit_knitting.cutting import (
partition_problem,
generate_cutting_experiments,
)
circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose()
circuit.assign_parameters([0.8] * len(circuit.parameters), inplace=True)
observable = SparsePauliOp(["ZZZZ"])
circuit.draw("mpl", scale=0.8)
partitioned_problem = partition_problem(
circuit=circuit, partition_labels="AABB", observables=observable.paulis
)
subcircuits = partitioned_problem.subcircuits
bases = partitioned_problem.bases
subobservables = partitioned_problem.subobservables
subcircuits["A"].draw("mpl", scale=0.6)
subcircuits["B"].draw("mpl", scale=0.6)
subexperiments, coefficients = generate_cutting_experiments(
circuits=subcircuits,
observables=subobservables,
num_samples=np.inf,
)
coefficients
print(f"Mapping probabilities for a CNOT decomposition: {bases[0].probabilities}")
from circuit_knitting.cutting.qpd import QPDBasis
from qiskit.circuit.library.standard_gates import CXGate
qpd_basis_cx = QPDBasis.from_instruction(CXGate())
def _min_nonzero(seq, /):
"""Return the minimum value in a sequence, ignoring values near zero."""
return min(x for x in seq if not np.isclose(x, 0))
num_cx_cuts = 2
print(
f"Number of samples needed to retrieve exact weights: {1 / _min_nonzero(qpd_basis_cx.probabilities)**num_cx_cuts}"
)
subexperiments, coefficients = generate_cutting_experiments(
circuits=subcircuits,
observables=subobservables,
num_samples=36,
)
coefficients
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(2, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.id(q[0])
qc.h(q[1])
qc.z(q[1])
print('_______statevector______________')
print(oq.execute(qc, S_simulator).result().get_statevector())
print('\n__________wavefunction____________')
oq.Wavefunction(qc);
oq.Wavefunction(qc, precision = 8);
q = QuantumRegister(4, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.z(q[1])
qc.rx(m.pi/3,q[1])
qc.h(q[2])
qc.ry(m.pi/5,q[2])
qc.h(q[3])
oq.Wavefunction(qc)
print('\n__________column____________')
oq.Wavefunction(qc, column = True);
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.h(q[2])
oq.Wavefunction(qc, systems=[2,1]);
q = QuantumRegister(6, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.h(q[2])
oq.Wavefunction(qc, systems=[2,1,3]);
print('\n________show_systems______')
oq.Wavefunction(qc, systems=[2,1,3], show_systems=[True,True,False]);
q = QuantumRegister(4, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.h(q[3])
oq.Wavefunction(qc, systems=[3,1]);
print('\n________show_systems______')
oq.Wavefunction(qc, systems=[3,1], show_systems=[True,False]);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc, shots = 100);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc, print_M=False);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
M = oq.Measurement(qc, shots = 20, print_M=False, return_M = True)
print(M)
q = QuantumRegister(7, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.id(q[4])
qc.id(q[5])
qc.id(q[6])
print('___________Initial state____________')
oq.Wavefunction(qc, systems=[4,3], column=True)
qc.ccx(q[0],q[1],q[4])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[4],q[5],q[6])
qc.cz(q[6],q[0])
print('\n____After CCCZ_______')
oq.Wavefunction(qc, systems=[4,3], column=True);
q = QuantumRegister(7, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.id(q[4])
qc.id(q[5])
qc.id(q[6])
print('___________Initial state____________')
oq.Wavefunction(qc, systems=[4,3])
qc.ccx(q[0],q[1],q[4])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[4],q[5],q[6])
qc.cz(q[6],q[0])
print('\n____After CCCZ_______')
oq.Wavefunction(qc, systems=[4,3])
qc.ccx(q[4],q[5],q[6])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[0],q[1],q[4])
print('\n____Reverse all CCNOTs______')
oq.Wavefunction(qc, systems=[4,3], column=True);
q = QuantumRegister(5, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.id(q[3])
qc.id(q[4])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,1],show_systems=[True,True,False])
oq.n_NOT(qc, [q[0], q[1], q[2]], q[3], [q[4]])
print('\n___________________n_NOT___________________')
oq.Wavefunction(qc,systems=[3,1,1],show_systems=[True,True,False]);
q = QuantumRegister(6, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.x(q[3])
qc.id(q[4])
qc.id(q[5])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False])
oq.n_Control_U(qc, [q[0], q[1], q[2]], [q[4],q[5]], [('Z',q[3]),('X',q[3])])
print('\n___________________n_Control_U___________________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
tgt = QuantumRegister(1,name='t')
anc = QuantumRegister(2, name = 'a')
qc = QuantumCircuit(q, tgt, anc, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.x(tgt[0])
qc.id(anc[0])
qc.id(anc[1])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False])
oq.n_Control_U(qc, q, anc, [('Z',tgt[0]),('X',tgt[0])])
print('\n___________________n_Control_U___________________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False]);
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from utils import load_image
DEFAULT_NUM_SHOTS = 100
class MeasurementsHistogram(pygame.sprite.Sprite):
"""Displays a histogram with measurements"""
def __init__(self, circuit, num_shots=DEFAULT_NUM_SHOTS):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit, num_shots)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit, num_shots=DEFAULT_NUM_SHOTS):
backend_sim = BasicAer.get_backend('qasm_simulator')
qr = QuantumRegister(circuit.width(), 'q')
cr = ClassicalRegister(circuit.width(), 'c')
meas_circ = QuantumCircuit(qr, cr)
meas_circ.barrier(qr)
meas_circ.measure(qr, cr)
complete_circuit = circuit + meas_circ
job_sim = execute(complete_circuit, backend_sim, shots=num_shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(complete_circuit)
print(counts)
histogram = plot_histogram(counts)
histogram.savefig("utils/data/bell_histogram.png")
self.image, self.rect = load_image('bell_histogram.png', -1)
self.image.convert()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/mickahell/quantum_pokemon-fight
|
mickahell
|
from src.main import team, battle
from stats.data import stats, team_stats
from src.class_custom.attacks import Attack
from src.class_custom.player import Player
from src.class_custom.pokemon import Pokemon
from src.class_custom.type import Type
from qiskit import Aer, QuantumCircuit, QuantumRegister
import warnings
class Game:
def __init__(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Init Qasm simulator backend
qasm = Aer.get_backend("qasm_simulator")
backend_sim = qasm # Choose your backend : <quantum_computer> or <qasm>
# Types creation --> Sources : https://boutique-pokemon.com/blogs/blog-pokemon/table-types-pokemon
fire = Type("Fire")
normal = Type("Normal")
water = Type("Water")
grass = Type("Grass")
electric = Type("Electric")
fly = Type("Fly")
poison = Type("Poison")
bug = Type("Bug")
ghost = Type("Ghost")
ground = Type("Ground")
dark = Type("Dark")
ice = Type("Ice")
steel = Type("Steel")
resistance = [bug, grass, fire, ice, steel]
weakness = [water, ground]
imunite = ["None"]
fire.add_info(resistance, weakness, imunite)
resistance = ["None"]
weakness = ["None"]
imunite = [ghost]
normal.add_info(resistance, weakness, imunite)
resistance = [grass, ground]
weakness = [fire, fly]
imunite = ["None"]
bug.add_info(resistance, weakness, imunite)
resistance = [water, fire, steel]
weakness = [grass, electric]
imunite = ["None"]
water.add_info(resistance, weakness, imunite)
resistance = [water, electric, grass, ground]
weakness = [fire, bug, poison, fly, ice]
imunite = ["None"]
grass.add_info(resistance, weakness, imunite)
resistance = [electric, fly, steel]
weakness = [ground]
imunite = ["None"]
electric.add_info(resistance, weakness, imunite)
resistance = [bug, grass]
weakness = [electric, ice]
imunite = [ground]
fly.add_info(resistance, weakness, imunite)
resistance = [ghost, dark]
weakness = [bug]
imunite = ["None"]
dark.add_info(resistance, weakness, imunite)
resistance = [bug, poison]
weakness = [ghost, dark]
imunite = [normal]
ghost.add_info(resistance, weakness, imunite)
resistance = [bug, grass, poison]
weakness = [ground]
imunite = ["None"]
poison.add_info(resistance, weakness, imunite)
resistance = [poison]
weakness = [water, grass, ice]
imunite = [electric]
ground.add_info(resistance, weakness, imunite)
resistance = [ice]
weakness = [fire, steel]
imunite = ["None"]
ice.add_info(resistance, weakness, imunite)
resistance = [steel, ice, bug, normal, grass, fly]
weakness = [fire, ground]
imunite = [poison]
steel.add_info(resistance, weakness, imunite)
# type qubits creation
fire.qubit = QuantumRegister(1, "fire")
normal.qubit = QuantumRegister(1, "normal")
water.qubit = QuantumRegister(1, "water")
grass.qubit = QuantumRegister(1, "grass")
electric.qubit = QuantumRegister(1, "electric")
fly.qubit = QuantumRegister(1, "fly")
poison.qubit = QuantumRegister(1, "poison")
bug.qubit = QuantumRegister(1, "bug")
ghost.qubit = QuantumRegister(1, "ghost")
ground.qubit = QuantumRegister(1, "ground")
dark.qubit = QuantumRegister(1, "dark")
ice.qubit = QuantumRegister(1, "ice")
steel.qubit = QuantumRegister(1, "steel")
qc_type = QuantumCircuit(
steel.qubit,
fire.qubit,
normal.qubit,
water.qubit,
grass.qubit,
electric.qubit,
fly.qubit,
poison.qubit,
bug.qubit,
ghost.qubit,
ground.qubit,
dark.qubit,
ice.qubit,
)
# Attacks creation
fire_blast = Attack("Fire Blast", fire, 110, 0.85, "special")
hurricane = Attack("Hurricane", fly, 110, 0.70, "special")
earthquake = Attack("Earthquake", ground, 100, 1, "physical")
leaf_storm = Attack("Leaf Storm", grass, 90, 1, "special")
shadow_ball = Attack("Shadow Ball", ghost, 80, 1, "special")
sludge_bomb = Attack("Sludge Bomb", poison, 90, 1, "special")
thunder = Attack("Thunder", electric, 110, 0.70, "special")
dark_pulse = Attack("Dark Pulse", dark, 80, 1, "special")
ice_beam = Attack("Ice Beam", ice, 90, 1, "special")
hydroblast = Attack("Hydroblast", water, 110, 0.8, "special")
iron_tail = Attack("Iron Tail", steel, 100, 0.75, "physical")
slam = Attack("Slam", normal, 80, 0.75, "physical")
grass_knot = Attack("Grass Knot", grass, 80, 1, "special")
flash_cannon = Attack("Flash Cannon", steel, 80, 1, "special")
giga_impact = Attack("Giga-Impact", normal, 150, 0.9, "physical")
bite = Attack("Bite", dark, 60, 1, "physical")
tri_attack = Attack("Triplattaque", normal, 80, 1, "special")
#hyper_beam = Attack("Hyper Beam", normal, 150, 0.9, "special")
throat_chop = Attack("Throat Chop", dark, 80, 1, "physical")
fire_punch = Attack("Fire Punch", fire, 75, 1, "physical")
# Pokémon creation --> Sources : https://www.pokepedia.fr/Pikachu#Statistiques-remarques1
charizard = Pokemon("Charizard", [fire, fly], 360, 267, 255, 317, 269, 299)
gengar = Pokemon("Gengar", [ghost, poison], 324, 229, 219, 359, 249, 319)
blastoise = Pokemon("Blastoise", [water], 362, 265, 299, 269, 309, 255)
pikachu = Pokemon("Pikachu", [electric], 294, 259, 199, 249, 219, 339)
glaceon = Pokemon("Glaceon", [ice], 334, 219, 319, 359, 289, 229)
porygonz = Pokemon("Porygon-Z", [normal], 374, 259, 239, 369, 249, 279)
abomasnow = Pokemon("Abomasnow", [grass, ice], 384, 283, 249, 283, 269, 219)
toxtricity = Pokemon(
"Toxtricity", [electric, poison], 354, 295, 239, 327, 239, 249
)
# Attacks learning
charizard.learn_attacks([fire_blast, hurricane, earthquake, leaf_storm])
gengar.learn_attacks([sludge_bomb, dark_pulse, shadow_ball, thunder])
blastoise.learn_attacks([ice_beam, hydroblast, flash_cannon, giga_impact])
pikachu.learn_attacks([thunder, iron_tail, slam, grass_knot])
glaceon.learn_attacks([ice_beam, slam, iron_tail, bite])
porygonz.learn_attacks([thunder, ice_beam, tri_attack, dark_pulse])
abomasnow.learn_attacks([ice_beam, leaf_storm, earthquake, giga_impact])
toxtricity.learn_attacks([sludge_bomb, thunder, throat_chop, fire_punch])
# Player creation
me = Player("Oak", "j1", "human")
him = Player("Agatha", "j2", "robot")
##############################################################
# GAME
print(
"""
###################################################
# Welcome in the Quantum Pokémon fight - CLI
# Will you succeed to win against the Quantum AI ?
#
# Good Luck !!!
###################################################
"""
)
team(me, him, nb_team=3)
winner, looser = battle(me, him, qc_type, backend_sim)
stats(winner.being)
team_stats(winner=winner.register_team, looser=looser.register_team)
print("The fight is over !")
str(input("Push enter to auto F5 the page") or "42")
|
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/JavaFXpert/qiskit-plotting-app
|
JavaFXpert
|
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell+meas
result = execute(circ, backend, shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Weyl decomposition of two-qubit gates in terms of echoed cross-resonance
gates."""
import cmath
import numpy as np
import scipy.linalg as la
from qiskit import QuantumCircuit
from qiskit.circuit.library import IGate, RXGate, RYGate, RZGate
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.quantum_info.synthesis.two_qubit_decompose import *
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from clonk.utils.qiskit_patch.two_qubit_decompose import TwoQubitBasisDecomposer
from clonk.utils.riswap_gates.equivalence_library import SessionEquivalenceLibrary
# from qiskit.circuit.library.standard_gates import *
from clonk.utils.riswap_gates.riswap import RiSwapGate, fSim
_sel = SessionEquivalenceLibrary
class RootiSwapWeylDecomposition(TransformationPass):
"""Rewrite two-qubit gates using the Weyl decomposition.
This transpiler pass rewrites two-qubit gates in terms of root iswap
gates according to the Weyl decomposition. A two-qubit gate will be
replaced with at most 3 root i swap gates.
"""
def __init__(self, basis_gate=False):
"""RootiSwapWeylDecomposition pass.
Args:
instruction_schedule_map (InstructionScheduleMap): the mapping from circuit
:class:`~.circuit.Instruction` names and arguments to :class:`.Schedule`\\ s.
"""
super().__init__()
# self.requires = [
# BasisTranslator(_sel, ["u3", "cu3", "cp", "swap", "riswap", "id"])
# ]
# self.decompose_swaps = decompose_swaps
self.basis_gate = basis_gate
# @staticmethod
# def _improper_orthogonal_decomp(x, y, z):
# alpha = np.arccos(
# np.cos(2 * z) - np.cos(2 * y) + np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2)
# )
# beta = np.arccos(
# np.cos(2 * z) - np.cos(2 * y) - np.sqrt((np.cos(4 * z) + np.cos(4 * y)) / 2)
# )
# gamma = 0
# psi = -np.arccos(np.sqrt((1 + np.tan(y - z)) / 2))
# phi = np.arccos(np.sqrt((1 + np.tan(y + z)) / 2))
# def_Lxyz = QuantumCircuit(2)
# # ISwap
# if np.isclose(x, y) and np.isclose(z, 0):
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rz(2 * x, 0)
# def_Lxyz.rz(-2 * x + np.pi, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rz(-np.pi, 1)
# return def_Lxyz
# # CPhase
# if np.isclose(y, 0) and np.isclose(z, 0):
# def_Lxyz.rz(np.arcsin(np.tan(x)), 1)
# def_Lxyz.rx(-np.pi / 2, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.z(1)
# def_Lxyz.ry(2 * np.arcsin(np.sqrt(2) * np.sin(x)), 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(-np.pi / 2, 1)
# def_Lxyz.rz(np.arcsin(np.tan(x)) - np.pi, 1)
# return def_Lxyz
# # Canonicalized SWAP
# elif np.isclose(x, np.pi / 4) and y + np.abs(z) <= np.pi / 4:
# def_Lxyz.rx(phi + psi, 0)
# def_Lxyz.rz(np.pi / 2, 1)
# def_Lxyz.rx(phi - psi, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(alpha, 0)
# def_Lxyz.rx(beta, 1)
# def_Lxyz.append(RiSwapGate(0.5), [0, 1])
# def_Lxyz.rx(phi + psi, 0)
# def_Lxyz.rx(phi - psi, 1)
# def_Lxyz.rz(-np.pi / 2, 1)
# return def_Lxyz
# else:
# raise NotImplementedError
# @staticmethod
# def cphase_decomp(unitary):
# # assuming unitary is a CPhase, is true per self.requires pass
# # TODO function structure needs to be reoganized to use canonicalize function
# x, y, z = weyl_coordinates(Operator(unitary).data)
# def_CPhase = RootiSwapWeylDecomposition._improper_orthogonal_decomp(x, y, z)
# return def_CPhase
# # Note this is the way suggested by alibaba paper, but google has a swap->riswap(1/2) decomp rule that uses less 1Q gates
# @staticmethod
# def swap_decomp(unitary):
# # FIXME: green, blue, maroon rules
# def_swap = QuantumCircuit(2)
# def_swap.z(0)
# def_swap.rx(np.pi / 2, 0)
# def_swap.z(0)
# def_swap.rx(-np.pi / 2, 1)
# x, y, z = weyl_coordinates(Operator(unitary).data)
# def_swap += RootiSwapWeylDecomposition._improper_orthogonal_decomp(
# x, y - np.pi / 4, z - np.pi / 4
# )
# def_swap.z(0)
# def_swap.rx(-np.pi / 2, 0)
# def_swap.rz(np.pi / 2, 0)
# def_swap.ry(-np.pi / 2, 0)
# def_swap.z(0)
# def_swap.rx(np.pi / 2, 1)
# def_swap.rz(-np.pi / 2, 1)
# def_swap.ry(np.pi / 2, 1)
# def_swap.append(RiSwapGate(0.5), [0, 1])
# def_swap.z(0)
# def_swap.ry(np.pi / 2, 0)
# def_swap.rz(-np.pi / 2, 0)
# def_swap.z(0)
# def_swap.ry(-np.pi / 2, 1)
# def_swap.rz(np.pi / 2, 1)
# return def_swap
# reference: https://arxiv.org/pdf/2105.06074.pdf
# from Qiskits two_qubit_decomp #FIXME moving functions around still this won't need to be copied once SQiSwap inside of that same pass
def KAKDecomp(self, unitary_matrix, *, fidelity=(1.0 - 1.0e-9)):
_ipx = np.array([[0, 1j], [1j, 0]], dtype=complex)
_ipy = np.array([[0, 1], [-1, 0]], dtype=complex)
_ipz = np.array([[1j, 0], [0, -1j]], dtype=complex)
_id = np.array([[1, 0], [0, 1]], dtype=complex)
"""Perform the Weyl chamber decomposition, and optionally choose a
specialized subclass.
The flip into the Weyl Chamber is described in B. Kraus and J. I. Cirac, Phys. Rev. A 63,
062309 (2001).
FIXME: There's a cleaner-seeming method based on choosing branch cuts carefully, in Andrew
M. Childs, Henry L. Haselgrove, and Michael A. Nielsen, Phys. Rev. A 68, 052311, but I
wasn't able to get that to work.
The overall decomposition scheme is taken from Drury and Love, arXiv:0806.4015 [quant-ph].
"""
pi = np.pi
pi2 = np.pi / 2
pi4 = np.pi / 4
# Make U be in SU(4)
U = np.array(unitary_matrix, dtype=complex, copy=True)
detU = la.det(U)
U *= detU ** (-0.25)
global_phase = cmath.phase(detU) / 4
Up = transform_to_magic_basis(U, reverse=True)
M2 = Up.T.dot(Up)
# M2 is a symmetric complex matrix. We need to decompose it as M2 = P D P^T where
# P ∈ SO(4), D is diagonal with unit-magnitude elements.
#
# We can't use raw `eig` directly because it isn't guaranteed to give us real or othogonal
# eigenvectors. Instead, since `M2` is complex-symmetric,
# M2 = A + iB
# for real-symmetric `A` and `B`, and as
# M2^+ @ M2 = A^2 + B^2 + i [A, B] = 1
# we must have `A` and `B` commute, and consequently they are simultaneously diagonalizable.
# Mixing them together _should_ account for any degeneracy problems, but it's not
# guaranteed, so we repeat it a little bit. The fixed seed is to make failures
# deterministic; the value is not important.
state = np.random.default_rng(2020)
for _ in range(100): # FIXME: this randomized algorithm is horrendous
M2real = state.normal() * M2.real + state.normal() * M2.imag
_, P = np.linalg.eigh(M2real)
D = P.T.dot(M2).dot(P).diagonal()
if np.allclose(P.dot(np.diag(D)).dot(P.T), M2, rtol=0, atol=1.0e-13):
break
else:
raise ValueError
d = -np.angle(D) / 2
d[3] = -d[0] - d[1] - d[2]
cs = np.mod((d[:3] + d[3]) / 2, 2 * np.pi)
# Reorder the eigenvalues to get in the Weyl chamber
cstemp = np.mod(cs, pi2)
np.minimum(cstemp, pi2 - cstemp, cstemp)
order = np.argsort(cstemp)[[1, 2, 0]]
cs = cs[order]
d[:3] = d[order]
P[:, :3] = P[:, order]
# Fix the sign of P to be in SO(4)
if np.real(la.det(P)) < 0:
P[:, -1] = -P[:, -1]
# Find K1, K2 so that U = K1.A.K2, with K being product of single-qubit unitaries
K1 = transform_to_magic_basis(Up @ P @ np.diag(np.exp(1j * d)))
K2 = transform_to_magic_basis(P.T)
K1l, K1r, phase_l = decompose_two_qubit_product_gate(K1)
K2l, K2r, phase_r = decompose_two_qubit_product_gate(K2)
global_phase += phase_l + phase_r
K1l = K1l.copy()
# Flip into Weyl chamber
if cs[0] > pi2:
cs[0] -= 3 * pi2
K1l = K1l.dot(_ipy)
K1r = K1r.dot(_ipy)
global_phase += pi2
if cs[1] > pi2:
cs[1] -= 3 * pi2
K1l = K1l.dot(_ipx)
K1r = K1r.dot(_ipx)
global_phase += pi2
conjs = 0
if cs[0] > pi4:
cs[0] = pi2 - cs[0]
K1l = K1l.dot(_ipy)
K2r = _ipy.dot(K2r)
conjs += 1
global_phase -= pi2
if cs[1] > pi4:
cs[1] = pi2 - cs[1]
K1l = K1l.dot(_ipx)
K2r = _ipx.dot(K2r)
conjs += 1
global_phase += pi2
if conjs == 1:
global_phase -= pi
if cs[2] > pi2:
cs[2] -= 3 * pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase += pi2
if conjs == 1:
global_phase -= pi
if conjs == 1:
cs[2] = pi2 - cs[2]
K1l = K1l.dot(_ipz)
K2r = _ipz.dot(K2r)
global_phase += pi2
if cs[2] > pi4:
cs[2] -= pi2
K1l = K1l.dot(_ipz)
K1r = K1r.dot(_ipz)
global_phase -= pi2
a, b, c = cs[1], cs[0], cs[2]
return global_phase, (a, b, c), K1l, K1r, K2l, K2r
# Reference: https://quantumai.google/reference/python/cirq/transformers/decompose_two_qubit_interaction_into_four_fsim_gates
def SYCDecomposer(self, U):
qc = QuantumCircuit(2)
# totally ignorning 1Q gates because we are just using this method for counting 2Q gate durations
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
qc.append(fSim(np.pi / 2, np.pi / 6), [0, 1])
return qc
# Reference: https://arxiv.org/pdf/2105.06074.pdf
def riswapWeylDecomp(self, U):
"""Decompose U into single qubit gates and the SQiSW gates."""
qc = QuantumCircuit(2)
_, (x, y, z), A1, A2, B1, B2 = self.KAKDecomp(U)
if np.abs(z) <= x - y:
C1, C2 = self.interleavingSingleQubitRotations(x, y, z)
V = (
RiSwapGate(0.5).to_matrix()
@ np.kron(C1, C2)
@ RiSwapGate(0.5).to_matrix()
)
_, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V)
qc.append(UnitaryGate(np.matrix(E1).H @ B1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ np.matrix(D2).H), [0])
else:
(x, y, z), F1, F2, G1, G2, H1, H2 = self.canonicalize(x, y, z)
C1, C2 = self.interleavingSingleQubitRotations(x, y, z)
V = (
RiSwapGate(0.5).to_matrix()
@ np.kron(C1, C2)
@ RiSwapGate(0.5).to_matrix()
)
_, (x, y, z), D1, D2, E1, E2 = self.KAKDecomp(V)
qc.append(UnitaryGate(H1 @ B1), [1])
qc.append(UnitaryGate(H2 @ B2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(np.matrix(E1).H @ G1), [1])
qc.append(UnitaryGate(np.matrix(E2).H @ G2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(C1), [1])
qc.append(UnitaryGate(C2), [0])
qc.append(RiSwapGate(0.5), [0, 1])
qc.append(UnitaryGate(A1 @ F1 @ np.matrix(D1).H), [1])
qc.append(UnitaryGate(A2 @ F2 @ np.matrix(D2).H), [0])
return qc.decompose()
def interleavingSingleQubitRotations(self, x, y, z):
"""Output the single qubit rotations given the interaction coefficients
(x,y,z) \in W' when sandiwched by two SQiSW gates."""
C = (
np.sin(x + y - z)
* np.sin(x - y + z)
* np.sin(-x - y - z)
* np.sin(-x + y + z)
)
alpha = np.arccos(
np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) + 2 * np.sqrt(C)
)
beta = np.arccos(np.cos(2 * x) - np.cos(2 * y) + np.cos(2 * z) - 2 * np.sqrt(C))
_num = 4 * (np.cos(x) ** 2) * (np.cos(z) ** 2) * (np.cos(y) ** 2)
_den = _num + np.cos(2 * x) + np.cos(2 * y) * np.cos(2 * z)
gamma = np.arccos(np.sign(z) * np.sqrt(_num / _den))
return (
RZGate(gamma).to_matrix()
@ RXGate(alpha).to_matrix()
@ RZGate(gamma).to_matrix(),
RXGate(beta).to_matrix(),
)
def canonicalize(self, x, y, z):
"""Decompose an arbitrary gate into one SQISW and one L(x,y',z) where
(x',y',z') \in W' and output the coefficients (x',y',z') and the
interleaving single qubit rotations."""
A1 = IGate().to_matrix()
A2 = IGate().to_matrix()
B1 = RYGate(-np.pi / 2).to_matrix()
B2 = RYGate(np.pi / 2).to_matrix()
C1 = RYGate(np.pi / 2).to_matrix()
C2 = RYGate(-np.pi / 2).to_matrix()
s = np.sign(z)
z = np.abs(z)
if x > np.pi / 8:
y = y - np.pi / 8
z = z - np.pi / 8
B1 = RZGate(np.pi / 2).to_matrix() @ B1
B2 = RZGate(-np.pi / 2).to_matrix() @ B2
C1 = C1 @ RZGate(-np.pi / 2).to_matrix()
C2 = C2 @ RZGate(np.pi / 2).to_matrix()
else:
x = x + np.pi / 8
z = z - np.pi / 8
if np.abs(y) < np.abs(z):
# XXX typo in alibaba here (?)
z = -z
A1 = RXGate(np.pi / 2).to_matrix()
A2 = RXGate(-np.pi / 2).to_matrix()
B1 = RXGate(-np.pi / 2).to_matrix() @ B1
B2 = RXGate(np.pi / 2).to_matrix() @ B2
if s < 0:
z = -z
A1 = RZGate(np.pi).to_matrix() @ A1 @ RZGate(np.pi).to_matrix()
B1 = RZGate(np.pi).to_matrix() @ B1 @ RZGate(np.pi).to_matrix()
C1 = RZGate(np.pi).to_matrix() @ C1 @ RZGate(np.pi).to_matrix()
return (x, y, z), A1, A2, B1, B2, C1, C2
def run(self, dag: DAGCircuit):
"""Run the RootiSwapWeylDecomposition pass on `dag`.
Rewrites two-qubit gates in an arbitrary circuit in terms of echoed cross-resonance
gates by computing the Weyl decomposition of the corresponding unitary. Modifies the
input dag.
Args:
dag (DAGCircuit): DAG to rewrite.
Returns:
DAGCircuit: The modified dag.
Raises:
TranspilerError: If the circuit cannot be rewritten.
"""
# pylint: disable=cyclic-import
from qiskit.quantum_info import Operator
if len(dag.qregs) > 1:
raise TranspilerError(
"RootiSwapWeylDecomposition expects a single qreg input DAG,"
f"but input DAG had qregs: {dag.qregs}."
)
# trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if isinstance(self.basis_gate, RiSwapGate):
self.decomposer = self.riswapWeylDecomp
elif isinstance(self.basis_gate, fSim):
self.decomposer = self.SYCDecomposer
else:
self.decomposer = TwoQubitBasisDecomposer(self.basis_gate)
# add something which caches the result to SWAP so we don't have to do it every time
swap_sub = None
cnot_sub = None
for node in dag.two_qubit_ops():
# denote 2 different decomp rules, either for swap gates, or for U gates in CPhase basis
# if node.name == "riswap":
# continue
# FIXME need to convert unitary to a special unitary first to preserve 1Qs?
unitary = Operator(node.op).data
if node.name == "swap":
if swap_sub is None:
swap_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, swap_sub)
continue
if node.name == "cx":
if cnot_sub is None:
cnot_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, cnot_sub)
continue
# special_unitary = unitary
dag_sub = circuit_to_dag(self.decomposer(unitary))
dag.substitute_node_with_dag(node, dag_sub)
# if node.name == "swap":
# if self.decompose_swaps:
# dag_weyl = circuit_to_dag(self.swap_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
# elif node.name == "cp":
# dag_weyl = circuit_to_dag(self.cphase_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
# # FIXME
# # FIXME
# # FIXME
# # I need to double check the x,y,z coordinates -> why is CX and CPhase both (np.pi/4 ,0 ,0)
# # that tells me I need to write CX in CPhase basis first to preverse 1Q gates
# # but CU is 2 CPhase gates and yet still a (np.pi/4, 0, 0)- how do I preserve 1Q gates?
# elif node.name == "cu3":
# dag_weyl = circuit_to_dag(self.cphase_decomp(unitary))
# dag.substitute_node_with_dag(node, dag_weyl)
return dag
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import os
from qiskit import QuantumCircuit, execute
from qiskit.compiler import transpile
from qiskit.providers.aer import Aer
from qiskit.circuit.random import random_circuit
from rustworkx.visualization import mpl_draw
from qiskit_iqm import IQMProvider
qc_1 = random_circuit(5, 5, measure=True)
qc_2 = random_circuit(5, 5, measure=True)
backend = Aer.get_backend('qasm_simulator')
job = execute([qc_1, qc_2], backend, shots=1000)
result = job.result()
from qiskit_iqm import IQMProvider
provider = IQMProvider(os.environ['IQM_SERVER_URL'])
from qiskit.providers.provider import Provider
isinstance(provider, Provider)
backend = provider.get_backend()
from qiskit.providers import BackendV2
isinstance(backend, BackendV2)
backend.num_qubits
backend.target.qargs
backend.index_to_qubit_name(3)
mpl_draw(backend.coupling_map.graph)
backend.operation_names
qc = random_circuit(5, 5, measure=True, seed=321)
qc.draw(output='mpl')
qc_transpiled = transpile(qc, backend=backend, optimization_level=3)
qc_transpiled.draw(output='mpl')
qc_1 = random_circuit(5, 5, measure=True, seed=123)
qc_2 = random_circuit(5, 5, measure=True, seed=456)
job = execute([qc_1, qc_2], backend, shots=1000)
from qiskit.providers import JobV1
isinstance(job, JobV1)
job.status()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
|
Spintronic6889
|
!python --version
!pip install qiskit
!pip install pylatexenc
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
from qiskit.visualization import plot_state_city
%matplotlib inline
import matplotlib as mpl
from random import randrange
import numpy as np
import networkx as nx
import random
import math
from qiskit.tools.monitor import job_monitor
from random import randrange
pose=[]
for i in range(400):
pose.append([])
#print(pose)
#pose[-1]=1
#print(pose[-1])
pose[0]=200
for k in range(200):
rand = randrange(0,2)
if rand==0:
#print(rand)
pose[k+1]=pose[k]+1
if rand==1:
pose[k+1]=pose[k]-1
#print(pose)
yc=[]
for e in range(400):
yc.append([])
for q in range(400):
yc[q]=0
for h in range(400):
if pose[h]==q:
yc[q]=yc[q]+1
#print((yc))
#print(len(yc))
xc = np.arange(0, 400, 1)
plt.plot(yc)
plt.xlim(150, 250)
class quantom_walk:
def __init__(self):
self.__n=2
self.__steps=1
self.__theta=0
self.__phi=0
self.__qtype=1
self.__shot=5000
def main_qw(self,n,steps,qtype,theta,phi):
self.__qpos = QuantumRegister(n,'qpos')
self.__qcoin = QuantumRegister(1,'qcoin')
self.__cpos = ClassicalRegister(n,'cr')
self.__QC = QuantumCircuit(self.__qpos, self.__qcoin)
if qtype==2: self.__QC.x(self.__qcoin[0])
if qtype==3: self.__QC.u(theta, phi, 0, self.__qcoin[0])
for i in range(steps):
self.__QC.h(self.__qcoin[0])
self.__QC.barrier()
for i in range(n):
self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla')
self.__QC.barrier()
self.__QC.x(self.__qcoin[0])
for i in range(n):
if i+1 < n: self.__QC.x(self.__qpos[i+1:])
self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla')
if i+1 < n: self.__QC.x(self.__qpos[i+1:])
self.__QC.barrier()
a=n/2
p=math.floor(a)
for k in range(n):
if(k<p):
self.__QC.swap(self.__qpos[n-1-k],self.__qpos[k])
def displayh(self):
display(self.__QC.draw(output="mpl"))
def histagramh(self,shot):
self.__QC.measure_all()
job = execute(self.__QC,Aer.get_backend('aer_simulator'),shots=5000)
counts = job.result().get_counts(self.__QC)
return counts
def spacevectorh(self):
backend = Aer.get_backend('statevector_simulator')
job = execute(self.__QC, backend)
result = job.result()
outputstate = result.get_statevector(self.__QC, decimals=3)
print(outputstate)
def plotcityh(self):
backend = Aer.get_backend('statevector_simulator')
job = execute(self.__QC, backend)
result = job.result()
outputstate = result.get_statevector(self.__QC, decimals=3)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
return outputstate
def unitaryh(self):
backend = Aer.get_backend('unitary_simulator')
job = execute(self.__QC, backend)
result = job.result()
yy=result.get_unitary(self.__QC, decimals=3)
print(yy)
def IBMQh(self):
from qiskit import IBMQ
IBMQ.save_account('d1441affe8622903745ae099f50bce72c21036f85b14600d18195c977b9efcdee621dd4a981b92d8028c03c4dc1860c82d70f501d345023471402f4f8dad0181',overwrite=True)
provider = IBMQ.load_account()
device = provider.get_backend('ibmq_quito') #we use ibmq_16_melbourne quantum device
job = execute(self.__QC, backend = device) #we pass our circuit and backend as usual
from qiskit.tools.monitor import job_monitor
job_monitor(job) #to see our status in queue
result = job.result()
counts= result.get_counts(self.__QC)
return counts
def instructionset(self):
print(self.__QC.qasm())
qw = quantom_walk()
qw.main_qw(4,4,1,1.5,4)
#qw.instructionset()
#qw.displayh()
#plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
#qw.histagramh(3000)
#qw.spacevectorh()
#qw.unitaryh()
#qw.plotcityh()
#plot_state_city(qw.plotcityh(), figsize=(20, 10))
#plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None)
#qw.IBMQh()
qw = quantom_walk()
qw.main_qw(2,2,1,1.5,4)
qw.displayh()
qw.main_qw(6,25,1,1.5,4)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
qw.main_qw(3,4,1,1.5,4)
qw.spacevectorh()
qw.main_qw(3,15,1,1.5,4)
plot_state_city(qw.plotcityh(), figsize=(20, 10))
qw.main_qw(2,3,1,1.5,4)
qw.unitaryh()
qw.main_qw(3,2,1,1.5,4)
qw.instructionset()
qw.main_qw(2,1,1,1.5,4)
plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None)
#hadamrad...qtype=1
qw = quantom_walk()
qw.main_qw(3,13,1,0,0)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
#optimized ugate applied...qtype=3
qw = quantom_walk()
qw.main_qw(3,13,3,1.57,1.57)
plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
|
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/liyaochong/quantum-algorithm-learning-and-implementation
|
liyaochong
|
# 导入相应的运算库
import numpy as np
from math import pi
from qiskit import BasicAer, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit import Aer
# 定义相应的量子寄存器,并添加至电路当中去
# q0寄存器表示地址寄存器
q0 = QuantumRegister(5,'q0')
c0 = ClassicalRegister(5,'c0')
# 定义一个量子电路对象
Circuit = QuantumCircuit()
# 往寄存器中添加4个量子寄存器
Circuit.add_register(q0,c0)
# 添加量子门操作,注意这里的命名方式为最低有效位
# 执行H门操作,将地址寄存器q0张开,分叉存储,由于两个数据只需要用1个量子比特进行表示
Circuit.h(q0[4])
Circuit.barrier()
Circuit.h(q0[3])
Circuit.barrier()
Circuit.h(q0[2])
Circuit.barrier()
Circuit.h(q0[1])
Circuit.barrier()
Circuit.swap(q0[1], q0[0])
Circuit.barrier()
Circuit.swap(q0[2], q0[1])
Circuit.swap(q0[1], q0[0])
Circuit.barrier()
Circuit.swap(q0[3], q0[2])
Circuit.swap(q0[2], q0[1])
Circuit.swap(q0[1], q0[0])
Circuit.barrier()
Circuit.swap(q0[4], q0[3])
Circuit.swap(q0[3], q0[2])
Circuit.swap(q0[2], q0[1])
Circuit.swap(q0[1], q0[0])
# 绘制整个量子电路图
Circuit.draw(output='mpl')
# 在单一模拟器后端运行量子电路
backend = Aer.get_backend('unitary_simulator')
job = execute(Circuit, backend)
result = job.result()
# 显示结果
print(result.get_unitary(Circuit, decimals=3))
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
"""
Creates and simulates multiple circuits with batch submission.
Example Output:
job has successfully run
[{'00': 44, '11': 56}, {'000': 57, '111': 43}]
{'000': 57, '111': 43}
"""
import qiskit
import qiskit_superstaq as qss
# SuperstaQ token retrieved through API
token = "insert api token"
# Create provider using authorization token
superstaq = qss.superstaq_provider.SuperstaQProvider(token)
# Retrieve backend from superstaq provider
backend = superstaq.get_backend("ibmq_qasm_simulator")
# Standard bell circuit
qc1 = qiskit.QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
# 3-qubit GHZ state
qc2 = qiskit.QuantumCircuit(3, 3)
qc2.h(0)
qc2.cx(0, 1)
qc2.cx(0, 2)
qc2.measure([0, 1, 2], [0, 1, 2])
# Submit list of jobs to backend. Circuits submitted simultaneously
# will run with the same backend and the same number of shots.
job = backend.run([qc1, qc2], shots=100)
# The status of the circuit furthest behind in the queue.
print(job.status().value)
# List of result counts
print(job.result().get_counts())
# ith result counts (0-indexed)
print(job.result().get_counts(1))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/swe-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.
"""
AST (abstract syntax tree) to DAG (directed acyclic graph) converter.
Acts as an OpenQASM interpreter.
"""
from collections import OrderedDict
from qiskit.dagcircuit import DAGCircuit
from qiskit.exceptions import QiskitError
from qiskit.circuit import QuantumRegister, ClassicalRegister, Gate, QuantumCircuit
from qiskit.qasm.node.real import Real
from qiskit.circuit.measure import Measure
from qiskit.circuit.reset import Reset
from qiskit.circuit.barrier import Barrier
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import standard_gates as std
def ast_to_dag(ast):
"""Build a ``DAGCircuit`` object from an AST ``Node`` object.
Args:
ast (Program): a Program Node of an AST (parser's output)
Return:
DAGCircuit: the DAG representing an OpenQASM's AST
Raises:
QiskitError: if the AST is malformed.
Example:
.. code-block::
from qiskit.converters import ast_to_dag
from qiskit import qasm, QuantumCircuit, ClassicalRegister, QuantumRegister
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)
qasm_str = circ.qasm()
ast = qasm.Qasm(data=qasm_str).parse()
dag = ast_to_dag(ast)
"""
dag = DAGCircuit()
AstInterpreter(dag)._process_node(ast)
return dag
class AstInterpreter:
"""Interprets an OpenQASM by expanding subroutines and unrolling loops."""
standard_extension = {
"u1": std.U1Gate,
"u2": std.U2Gate,
"u3": std.U3Gate,
"u": std.UGate,
"p": std.PhaseGate,
"x": std.XGate,
"y": std.YGate,
"z": std.ZGate,
"t": std.TGate,
"tdg": std.TdgGate,
"s": std.SGate,
"sdg": std.SdgGate,
"sx": std.SXGate,
"sxdg": std.SXdgGate,
"swap": std.SwapGate,
"rx": std.RXGate,
"rxx": std.RXXGate,
"ry": std.RYGate,
"rz": std.RZGate,
"rzz": std.RZZGate,
"id": std.IGate,
"h": std.HGate,
"cx": std.CXGate,
"cy": std.CYGate,
"cz": std.CZGate,
"ch": std.CHGate,
"crx": std.CRXGate,
"cry": std.CRYGate,
"crz": std.CRZGate,
"csx": std.CSXGate,
"cu1": std.CU1Gate,
"cp": std.CPhaseGate,
"cu": std.CUGate,
"cu3": std.CU3Gate,
"ccx": std.CCXGate,
"cswap": std.CSwapGate,
"delay": Delay,
"rccx": std.RCCXGate,
"rc3x": std.RC3XGate,
"c3x": std.C3XGate,
"c3sqrtx": std.C3SXGate,
"c4x": std.C4XGate,
}
def __init__(self, dag):
"""Initialize interpreter's data."""
# DAG object to populate
self.dag = dag
# OPENQASM version number (ignored for now)
self.version = 0.0
# Dict of gates names and properties
self.gates = OrderedDict()
# Keeping track of conditional gates
self.condition = None
# List of dictionaries mapping local parameter ids to expression Nodes
self.arg_stack = [{}]
# List of dictionaries mapping local bit ids to global ids (name, idx)
self.bit_stack = [{}]
def _process_bit_id(self, node):
"""Process an Id or IndexedId node as a bit or register type.
Return a list of tuples (Register,index).
"""
reg = None
if node.name in self.dag.qregs:
reg = self.dag.qregs[node.name]
elif node.name in self.dag.cregs:
reg = self.dag.cregs[node.name]
else:
raise QiskitError(
"expected qreg or creg name:", "line=%s" % node.line, "file=%s" % node.file
)
if node.type == "indexed_id":
# An indexed bit or qubit
return [reg[node.index]]
elif node.type == "id":
# A qubit or qreg or creg
if not self.bit_stack[-1]:
# Global scope
return list(reg)
else:
# local scope
if node.name in self.bit_stack[-1]:
return [self.bit_stack[-1][node.name]]
raise QiskitError(
"expected local bit name:", "line=%s" % node.line, "file=%s" % node.file
)
return None
def _process_custom_unitary(self, node):
"""Process a custom unitary node."""
name = node.name
if node.arguments is not None:
args = self._process_node(node.arguments)
else:
args = []
bits = [self._process_bit_id(node_element) for node_element in node.bitlist.children]
if name in self.gates:
self._arguments(name, bits, args)
else:
raise QiskitError(
"internal error undefined gate:", "line=%s" % node.line, "file=%s" % node.file
)
def _process_u(self, node):
"""Process a U gate node."""
args = self._process_node(node.arguments)
bits = [self._process_bit_id(node.bitlist)]
self._arguments("u", bits, args)
def _arguments(self, name, bits, args):
gargs = self.gates[name]["args"]
gbits = self.gates[name]["bits"]
maxidx = max(map(len, bits))
for idx in range(maxidx):
self.arg_stack.append({gargs[j]: args[j] for j in range(len(gargs))})
# Only index into register arguments.
element = [idx * x for x in [len(bits[j]) > 1 for j in range(len(bits))]]
self.bit_stack.append({gbits[j]: bits[j][element[j]] for j in range(len(gbits))})
self._create_dag_op(
name,
[self.arg_stack[-1][s].sym() for s in gargs],
[self.bit_stack[-1][s] for s in gbits],
)
self.arg_stack.pop()
self.bit_stack.pop()
def _process_gate(self, node, opaque=False):
"""Process a gate node.
If opaque is True, process the node as an opaque gate node.
"""
self.gates[node.name] = {}
de_gate = self.gates[node.name]
de_gate["print"] = True # default
de_gate["opaque"] = opaque
de_gate["n_args"] = node.n_args()
de_gate["n_bits"] = node.n_bits()
if node.n_args() > 0:
de_gate["args"] = [element.name for element in node.arguments.children]
else:
de_gate["args"] = []
de_gate["bits"] = [c.name for c in node.bitlist.children]
if node.name in self.standard_extension:
return
if opaque:
de_gate["body"] = None
else:
de_gate["body"] = node.body
def _process_cnot(self, node):
"""Process a CNOT gate node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if not (len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1):
raise QiskitError(
"internal error: qreg size mismatch", "line=%s" % node.line, "file=%s" % node.file
)
maxidx = max([len(id0), len(id1)])
for idx in range(maxidx):
cx_gate = std.CXGate()
cx_gate.condition = self.condition
if len(id0) > 1 and len(id1) > 1:
self.dag.apply_operation_back(cx_gate, [id0[idx], id1[idx]], [])
elif len(id0) > 1:
self.dag.apply_operation_back(cx_gate, [id0[idx], id1[0]], [])
else:
self.dag.apply_operation_back(cx_gate, [id0[0], id1[idx]], [])
def _process_measure(self, node):
"""Process a measurement node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if len(id0) != len(id1):
raise QiskitError(
"internal error: reg size mismatch", "line=%s" % node.line, "file=%s" % node.file
)
for idx, idy in zip(id0, id1):
meas_gate = Measure()
meas_gate.condition = self.condition
self.dag.apply_operation_back(meas_gate, [idx], [idy])
def _process_if(self, node):
"""Process an if node."""
creg_name = node.children[0].name
creg = self.dag.cregs[creg_name]
cval = node.children[1].value
self.condition = (creg, cval)
self._process_node(node.children[2])
self.condition = None
def _process_children(self, node):
"""Call process_node for all children of node."""
for kid in node.children:
self._process_node(kid)
def _process_node(self, node):
"""Carry out the action associated with a node."""
if node.type == "program":
self._process_children(node)
elif node.type == "qreg":
qreg = QuantumRegister(node.index, node.name)
self.dag.add_qreg(qreg)
elif node.type == "creg":
creg = ClassicalRegister(node.index, node.name)
self.dag.add_creg(creg)
elif node.type == "id":
raise QiskitError("internal error: _process_node on id")
elif node.type == "int":
raise QiskitError("internal error: _process_node on int")
elif node.type == "real":
raise QiskitError("internal error: _process_node on real")
elif node.type == "indexed_id":
raise QiskitError("internal error: _process_node on indexed_id")
elif node.type == "id_list":
# We process id_list nodes when they are leaves of barriers.
return [self._process_bit_id(node_children) for node_children in node.children]
elif node.type == "primary_list":
# We should only be called for a barrier.
return [self._process_bit_id(m) for m in node.children]
elif node.type == "gate":
self._process_gate(node)
elif node.type == "custom_unitary":
self._process_custom_unitary(node)
elif node.type == "universal_unitary":
self._process_u(node)
elif node.type == "cnot":
self._process_cnot(node)
elif node.type == "expression_list":
return node.children
elif node.type == "binop":
raise QiskitError("internal error: _process_node on binop")
elif node.type == "prefix":
raise QiskitError("internal error: _process_node on prefix")
elif node.type == "measure":
self._process_measure(node)
elif node.type == "format":
self.version = node.version()
elif node.type == "barrier":
ids = self._process_node(node.children[0])
qubits = []
for qubit in ids:
for j, _ in enumerate(qubit):
qubits.append(qubit[j])
self.dag.apply_operation_back(Barrier(len(qubits)), qubits, [])
elif node.type == "reset":
id0 = self._process_bit_id(node.children[0])
for i, _ in enumerate(id0):
reset = Reset()
reset.condition = self.condition
self.dag.apply_operation_back(reset, [id0[i]], [])
elif node.type == "if":
self._process_if(node)
elif node.type == "opaque":
self._process_gate(node, opaque=True)
elif node.type == "external":
raise QiskitError("internal error: _process_node on external")
else:
raise QiskitError(
"internal error: undefined node type",
node.type,
"line=%s" % node.line,
"file=%s" % node.file,
)
return None
def _gate_rules_to_qiskit_circuit(self, node, params):
"""From a gate definition in qasm, to a QuantumCircuit format."""
rules = []
qreg = QuantumRegister(node["n_bits"])
bit_args = {node["bits"][i]: q for i, q in enumerate(qreg)}
exp_args = {node["args"][i]: Real(q) for i, q in enumerate(params)}
for child_op in node["body"].children:
qparams = []
eparams = []
for param_list in child_op.children[1:]:
if param_list.type == "id_list":
qparams = [bit_args[param.name] for param in param_list.children]
elif param_list.type == "expression_list":
for param in param_list.children:
eparams.append(param.sym(nested_scope=[exp_args]))
op = self._create_op(child_op.name, params=eparams)
rules.append((op, qparams, []))
circ = QuantumCircuit(qreg)
for instr, qargs, cargs in rules:
circ._append(instr, qargs, cargs)
return circ
def _create_dag_op(self, name, params, qargs):
"""
Create a DAG node out of a parsed AST op node.
Args:
name (str): operation name to apply to the DAG
params (list): op parameters
qargs (list(Qubit)): qubits to attach to
Raises:
QiskitError: if encountering a non-basis opaque gate
"""
op = self._create_op(name, params)
op.condition = self.condition
self.dag.apply_operation_back(op, qargs, [])
def _create_op(self, name, params):
if name in self.standard_extension:
op = self.standard_extension[name](*params)
elif name in self.gates:
op = Gate(name=name, num_qubits=self.gates[name]["n_bits"], params=params)
if not self.gates[name]["opaque"]:
# call a custom gate (otherwise, opaque)
op.definition = self._gate_rules_to_qiskit_circuit(self.gates[name], params=params)
else:
raise QiskitError("unknown operation for ast node name %s" % name)
return op
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Run various circuits on an offline simulator controlled by an AQTResource.
This tests whether the circuit pre-conditioning and results formatting works as
expected.
"""
import re
import typing
from collections import Counter
from math import pi
from typing import Union
import pytest
import qiskit
from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister, quantum_info
from qiskit.providers import BackendV2
from qiskit.providers.jobstatus import JobStatus
from qiskit.transpiler import TranspilerError
from qiskit_aer import AerProvider, AerSimulator
from qiskit_aqt_provider import AQTProvider
from qiskit_aqt_provider.aqt_resource import AQTResource
from qiskit_aqt_provider.test.circuits import assert_circuits_equivalent
from qiskit_aqt_provider.test.fixtures import MockSimulator
from qiskit_aqt_provider.test.resources import TestResource
from qiskit_aqt_provider.test.timeout import timeout
@pytest.mark.parametrize("shots", [200])
def test_empty_circuit(shots: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Run an empty circuit."""
qc = QuantumCircuit(1)
qc.measure_all()
job = any_offline_simulator_no_noise.run(qc, shots=shots)
assert job.result().get_counts() == {"0": shots}
def test_circuit_success_lifecycle() -> None:
"""Go through the lifecycle of a successful single-circuit job.
Check that the job status visits the states QUEUED, RUNNING, and DONE.
"""
backend = TestResource(min_queued_duration=0.5, min_running_duration=0.5)
backend.options.update_options(query_period_seconds=0.1)
qc = QuantumCircuit(1)
qc.measure_all()
job = backend.run(qc)
assert job.status() is JobStatus.QUEUED
with timeout(2.0):
while job.status() is JobStatus.QUEUED:
continue
assert job.status() is JobStatus.RUNNING
with timeout(2.0):
while job.status() is JobStatus.RUNNING:
continue
assert job.status() is JobStatus.DONE
def test_error_circuit() -> None:
"""Check that errors in circuits are reported in the `errors` field of the Qiskit
result metadata, where the keys are the circuit job ids.
"""
backend = TestResource(always_error=True)
backend.options.update_options(query_period_seconds=0.1)
qc = QuantumCircuit(1)
qc.measure_all()
result = backend.run(qc).result()
assert result.success is False
assert backend.error_message == result._metadata["error"]
def test_cancelled_circuit() -> None:
"""Check that cancelled jobs return success = false."""
backend = TestResource(always_cancel=True)
qc = QuantumCircuit(1)
qc.measure_all()
result = backend.run(qc).result()
assert result.success is False
@pytest.mark.parametrize("shots", [1, 100, 200])
def test_simple_backend_run(shots: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Run a simple circuit with `backend.run`."""
qc = QuantumCircuit(1)
qc.rx(pi, 0)
qc.measure_all()
trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise)
job = any_offline_simulator_no_noise.run(trans_qc, shots=shots)
assert job.result().get_counts() == {"1": shots}
@pytest.mark.parametrize("resource", [MockSimulator(noisy=False), MockSimulator(noisy=True)])
def test_simple_backend_execute_noisy(resource: MockSimulator) -> None:
"""Execute a simple circuit on a noisy and noiseless backend. Check that the noisy backend
is indeed noisy.
"""
qc = QuantumCircuit(1)
qc.rx(pi, 0)
qc.measure_all()
# the single qubit error is around 0.1% so to see at least one error, we need to do more than
# 1000 shots.
total_shots = 4000 # take some margin
shots = 200 # maximum shots per submission
assert total_shots % shots == 0
counts: typing.Counter[str] = Counter()
for _ in range(total_shots // shots):
job = resource.run(qiskit.transpile(qc, backend=resource), shots=shots)
counts += Counter(job.result().get_counts())
assert sum(counts.values()) == total_shots
if resource.with_noise_model:
assert set(counts.keys()) == {"0", "1"}
assert counts["0"] < 0.1 * counts["1"] # very crude
else:
assert set(counts.keys()) == {"1"}
@pytest.mark.parametrize("shots", [100])
def test_ancilla_qubits_mapping(shots: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Run a circuit with two quantum registers, with only one mapped to the classical memory."""
qr = QuantumRegister(2)
qr_aux = QuantumRegister(3)
memory = ClassicalRegister(2)
qc = QuantumCircuit(qr, qr_aux, memory)
qc.rx(pi, qr[0])
qc.ry(pi, qr[1])
qc.rxx(pi / 2, qr_aux[0], qr_aux[1])
qc.measure(qr, memory)
trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise)
job = any_offline_simulator_no_noise.run(trans_qc, shots=shots)
# only two bits in the counts dict because memory has two bits width
assert job.result().get_counts() == {"11": shots}
@pytest.mark.parametrize("shots", [100])
def test_multiple_classical_registers(
shots: int, any_offline_simulator_no_noise: BackendV2
) -> None:
"""Run a circuit with the final state mapped to multiple classical registers."""
qr = QuantumRegister(5)
memory_a = ClassicalRegister(2)
memory_b = ClassicalRegister(3)
qc = QuantumCircuit(qr, memory_a, memory_b)
qc.rx(pi, qr[0])
qc.rx(pi, qr[3])
qc.measure(qr[:2], memory_a)
qc.measure(qr[2:], memory_b)
trans_qc = qiskit.transpile(qc, any_offline_simulator_no_noise)
job = any_offline_simulator_no_noise.run(trans_qc, shots=shots)
# counts are returned as "memory_b memory_a", msb first
assert job.result().get_counts() == {"010 01": shots}
@pytest.mark.parametrize("shots", [123])
@pytest.mark.parametrize("memory_opt", [True, False])
def test_get_memory_simple(
shots: int, memory_opt: bool, any_offline_simulator_no_noise: BackendV2
) -> None:
"""Check that the raw bitstrings can be accessed for each shot via the
get_memory() method in Qiskit's Result.
The memory is only accessible if the `memory` option is set.
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
result = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=memory_opt
).result()
if memory_opt:
memory = result.get_memory()
assert set(memory) == {"11", "00"}
assert len(memory) == shots
else:
with pytest.raises(QiskitError, match=re.compile("no memory", re.IGNORECASE)):
result.get_memory()
@pytest.mark.parametrize("shots", [123])
def test_get_memory_ancilla_qubits(shots: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Check that the raw bistrings returned by get_memory() in Qiskit's Result only
contain the mapped classical bits.
"""
qr = QuantumRegister(2)
qr_aux = QuantumRegister(3)
memory = ClassicalRegister(2)
qc = QuantumCircuit(qr, qr_aux, memory)
qc.rx(pi, qr[0])
qc.ry(pi, qr[1])
qc.rxx(pi / 2, qr_aux[0], qr_aux[1])
qc.measure(qr, memory)
job = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=True
)
memory = job.result().get_memory()
assert set(memory) == {"11"}
assert len(memory) == shots
@pytest.mark.parametrize("shots", [123])
def test_get_memory_bit_ordering(shots: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Check that the bitstrings returned by the results produced by AQT jobs have the same
bit order as the Qiskit Aer simulators.
"""
sim = AerSimulator(method="statevector")
qc = QuantumCircuit(3)
qc.rx(pi, 0)
qc.rx(pi, 1)
qc.measure_all()
aqt_memory = (
any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots, memory=True
)
.result()
.get_memory()
)
sim_memory = sim.run(qiskit.transpile(qc, sim), shots=shots, memory=True).result().get_memory()
assert set(sim_memory) == set(aqt_memory)
# sanity check: bitstrings are no palindromes
assert not any(bitstring == bitstring[::-1] for bitstring in sim_memory)
@pytest.mark.parametrize(
"backend",
[
pytest.param(
AQTProvider("token").get_backend("offline_simulator_no_noise"), id="offline-simulator"
),
pytest.param(AerProvider().get_backend("aer_simulator"), id="aer-simulator"),
],
)
def test_regression_issue_85(backend: BackendV2) -> None:
"""Check that qubit and clbit permutations are properly handled by the offline simulators.
This is a regression test for #85. Check that executing circuits with qubit/clbit
permutations outputs the same bitstrings on noiseless offline simulators from this
package and straight from Aer.
"""
empty_3 = QuantumCircuit(3)
base = QuantumCircuit(3)
base.h(0)
base.cx(0, 2)
base.measure_all()
perm_qubits = empty_3.compose(base, qubits=[0, 2, 1])
perm_all = empty_3.compose(base, qubits=[0, 2, 1], clbits=[0, 2, 1])
base_bitstrings = set(backend.run(qiskit.transpile(base, backend)).result().get_counts())
assert base_bitstrings == {"000", "101"}
perm_qubits_bitstrings = set(
backend.run(qiskit.transpile(perm_qubits, backend)).result().get_counts()
)
assert perm_qubits_bitstrings == {"000", "101"}
perm_all_bitstrings = set(
backend.run(qiskit.transpile(perm_all, backend)).result().get_counts()
)
assert perm_all_bitstrings == {"000", "011"}
@pytest.mark.parametrize(("shots", "qubits"), [(100, 5), (100, 8)])
def test_bell_states(shots: int, qubits: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Create a N qubits Bell state."""
qc = QuantumCircuit(qubits)
qc.h(0)
for qubit in range(1, qubits):
qc.cx(0, qubit)
qc.measure_all()
job = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise), shots=shots
)
counts = job.result().get_counts()
assert set(counts.keys()) == {"0" * qubits, "1" * qubits}
assert sum(counts.values()) == shots
@pytest.mark.parametrize(
"target_state",
[
quantum_info.Statevector.from_label("01"),
"01",
1,
[0, 1, 0, 0],
],
)
@pytest.mark.parametrize("optimization_level", range(4))
def test_state_preparation(
target_state: Union[int, str, quantum_info.Statevector, list[complex]],
optimization_level: int,
any_offline_simulator_no_noise: BackendV2,
) -> None:
"""Test the state preparation unitary factory.
Prepare the state |01> using the different formats accepted by
`QuantumCircuit.prepare_state`.
"""
qc = QuantumCircuit(2)
qc.prepare_state(target_state)
qc.measure_all()
shots = 100
job = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level),
shots=shots,
)
counts = job.result().get_counts()
assert counts == {"01": shots}
@pytest.mark.parametrize("optimization_level", range(4))
def test_state_preparation_single_qubit(
optimization_level: int, any_offline_simulator_no_noise: BackendV2
) -> None:
"""Test the state preparation unitary factory, targeting a single qubit in the register."""
qreg = QuantumRegister(4)
qc = QuantumCircuit(qreg)
qc.prepare_state(1, qreg[2])
qc.measure_all()
shots = 100
job = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level),
shots=shots,
)
counts = job.result().get_counts()
assert counts == {"0100": shots}
def test_initialize_not_supported(offline_simulator_no_noise: AQTResource) -> None:
"""Verify that `QuantumCircuit.initialize` is not supported.
#112 adds a note to the user guide indicating that `QuantumCircuit.initialize`
is not supported. Remove the note if this test fails.
"""
qc = QuantumCircuit(2)
qc.x(0)
qc.initialize("01")
qc.measure_all()
with pytest.raises(
TranspilerError,
match=re.compile(
r"high\s?level\s?synthesis was unable to synthesize instruction", re.IGNORECASE
),
):
qiskit.transpile(qc, offline_simulator_no_noise)
@pytest.mark.parametrize("optimization_level", range(4))
def test_cswap(optimization_level: int, any_offline_simulator_no_noise: BackendV2) -> None:
"""Verify that CSWAP (Fredkin) gates can be transpiled and executed (in a trivial case)."""
qc = QuantumCircuit(3)
qc.prepare_state("101")
qc.cswap(0, 1, 2)
trans_qc = qiskit.transpile(
qc, any_offline_simulator_no_noise, optimization_level=optimization_level
)
assert_circuits_equivalent(qc, trans_qc)
qc.measure_all()
shots = 200
job = any_offline_simulator_no_noise.run(
qiskit.transpile(qc, any_offline_simulator_no_noise, optimization_level=optimization_level),
shots=shots,
)
counts = job.result().get_counts()
assert counts == {"011": shots}
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import QuantumCircuit
alice_key = '11100100010001001001001000001111111110100100100100010010010001010100010100100100101011111110001010100010010001001010010010110010'
alice_bases = '11000110011000100001100101110000111010011001111111110100010111010100000100011001101010100001010010101011010001011001110011111111'
def alice_prepare_qubit(qubit_index):
## WRITE YOUR CODE HERE
qc = QuantumCircuit(1, 1)
if alice_key[qubit_index] == '1':
qc.x(0)
if alice_bases[qubit_index] == '1':
qc.h(0)
return qc
## WRITE YOUR CODE HERE
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
import sys
sys.path[1:1] = ["_common", "_common/qiskit"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit"]
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import time
import math
import os
import numpy as np
np.random.seed(0)
import execute as ex
import metrics as metrics
from collections import defaultdict
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.circuit.library import HartreeFock as HF
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers import ActiveSpaceTransformer
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
'''
Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
:param n_spin_orbs:The number of spin orbitals
:return: return a Qiskit circuit for this VQE ansatz
'''
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main")
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# number of beta spin orbitals
norb_b = norb_a
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# initialize the HF state
qc = HartreeFock(n_spin_orbs, na, nb)
# form the list of single and double excitations
singles = []
doubles = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
singles.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
singles.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
doubles.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp)
# add to ansatz
qc.compose(cluster_qc, inplace=True)
# method 2, only compute the last term in the Hamiltonian
if method == 2:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
for p in qubit_op:
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# add to circuit list
qc_list.append(qc_with_mea)
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
return qc_list
def ClusterOperatorCircuit(pauli_op):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit()
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=1):
# a flag that tells whether we need to perform rotation
need_rotate = False
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
need_rotate = True
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
need_rotate = True
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb)
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# return the circuit
return qc
import json
from qiskit import execute, Aer
backend = Aer.get_backend("qasm_simulator")
precalculated_data = {}
def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2):
print(f"... using circuit method {method}")
# validate parameters (smallest circuit is 4 qubits)
max_qubits = max(4, max_qubits)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
if method == 1: max_circuits = 1
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for input_size in range(min_qubits, max_qubits + 1, 2):
# determine the number of circuits to execute fo this group
num_circuits = max_circuits
num_qubits = input_size
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# decides number of unoccupied orbitals
nvira = int(num_qubits/2) - na
nvirb = int(num_qubits/2) - nb
# determine the size of t1 and t2 amplitudes
t1_size = na * nvira + nb * nvirb
t2_size = na * nb * nvira * nvirb
# random seed
np.random.seed(0)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# method 1 (default)
if method == 1:
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
else:
# loop over circuits
for circuit_id in range(num_circuits):
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
print(f"************\nExecuting VQE with num_qubits {num_qubits}")
for qc in qc_list:
# get circuit id
if method == 1:
circuit_id = qc.name.split()[0]
else:
circuit_id = qc.name.split()[2]
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
job = execute(qc, backend, shots=num_shots)
# executation result
result = job.result()
# get measurement counts
counts = result.get_counts(qc)
# initialize empty dictionary
dist = {}
for key in counts.keys():
prob = counts[key] / num_shots
dist[key] = prob
# add dist values to precalculated data for use in fidelity calculation
precalculated_data[f"{circuit_id}"] = dist
with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f:
f.write(json.dumps(
precalculated_data,
sort_keys=True,
indent=4,
separators=(',', ': ')
))
run()
|
https://github.com/antonioscardace/Practical-Quantum-ESM
|
antonioscardace
|
# Practical Implementation of a Quantum String Matching Algorithm
# S. Faro, F.P. Marino, and A. Scardace
# QUASAR 2024
%%capture
!pip install ibm-cloud-sdk-core==3.18.2
!pip install qiskit==0.45.1
!pip install qiskit-aer==0.13.1
!pip install pylatexenc==2.10
from numpy import log2, sqrt
from numpy import pi
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.gate import Gate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer
from qiskit import transpile
def run(circuit: QuantumCircuit, shots: int) -> dict:
simulator = Aer.get_backend('aer_simulator')
compiled_circuit = transpile(circuit, simulator)
job = simulator.run(compiled_circuit, shots=shots)
result = job.result()
return result.get_counts(compiled_circuit)
def init_register(bin_str: str) -> QuantumCircuit:
data_qr = QuantumRegister(len(bin_str), 'data')
qc = QuantumCircuit(data_qr)
for i, bit in enumerate(bin_str):
if bit == '1':
qc.x(data_qr[i])
return qc
classical_value = '1001'
init_register(classical_value).draw(fold=255)
def rot(n: int, s: int) -> QuantumCircuit:
y_qr = QuantumRegister(n, 'y')
qc = QuantumCircuit(y_qr, name='ROT_' + str(s))
for i in range(1, (int(log2(n)) - int(log2(s)) + 2)):
for j in range(int(n / (s * (2**i)))):
for q in range(j * s * (2**i), s * (j*2 ** i+1)):
qc.swap(n - 1 - (q+s), n - 1 - (q+2 ** (i-1) * s + s))
return qc
num_qubits = 8
shift_value = 2
rot(num_qubits, shift_value).draw(fold=255)
def rot_gate(n: int, s: int) -> Gate:
rot_circuit = rot(n, s)
return rot_circuit.to_gate(label='ROT_' + str(s))
def parameterized_rot(n: int) -> QuantumCircuit:
j_qr = QuantumRegister(int(log2(n)), 'j')
y_qr = QuantumRegister(n, 'y')
qc = QuantumCircuit(j_qr, y_qr)
for i in range(int(log2(n))):
crot = rot_gate(n, 2**i).control(1)
qc = qc.compose(crot, [j_qr[i]] + y_qr[:])
return qc
num_qubits = 8
parameterized_rot(num_qubits).draw(fold=255)
text = '10110001'
text_length = len(text)
shift_qr = QuantumRegister(int(log2(text_length)), 'shift')
text_qr = QuantumRegister(text_length, 'text')
output_cr = ClassicalRegister(text_length, 'output_classic')
circ = QuantumCircuit(shift_qr, text_qr, output_cr)
circ.h(shift_qr)
circ.append(init_register(text), text_qr[:])
circ.append(parameterized_rot(text_length), shift_qr[:] + text_qr[:])
circ.measure(text_qr, output_cr)
counts = run(circ, 100)
plot_histogram(counts, title='Rotate ' + text + ' Leftward in Superposition')
def match(m: int) -> QuantumCircuit:
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(m, 'y')
out_qr = QuantumRegister(1, 'out')
qc = QuantumCircuit(x_qr, y_qr, out_qr)
for i in range(m):
qc.cx(x_qr[i], y_qr[i])
qc.x(y_qr[i])
qc.mcx(y_qr[:], out_qr)
for i in reversed(range(m)):
qc.x(y_qr[i])
qc.cx(x_qr[i], y_qr[i])
return qc
pattern_length = 4
match(pattern_length).draw(fold=255)
text = '1011'
text_length = len(text)
pattern_qr = QuantumRegister(text_length, 'pattern')
text_qr = QuantumRegister(text_length, 'text')
output_qr = QuantumRegister(1, 'output')
output_cr = ClassicalRegister(text_length + 1, 'output_classic')
circ = QuantumCircuit(pattern_qr, text_qr, output_qr, output_cr)
circ.h(pattern_qr)
circ.append(init_register(text), text_qr[:])
circ.append(match(text_length), pattern_qr[:] + text_qr[:] + output_qr[:])
circ.measure(pattern_qr, output_cr[:-1])
circ.measure(output_qr, output_cr[-1])
counts = run(circ, 100)
plot_histogram(counts, title='Matching ' + text)
def match_gate(m: int) -> Gate:
match_circuit = match(m)
return match_circuit.to_gate(label='MATCH')
def esm(m: int, n: int) -> QuantumCircuit:
j_qr = QuantumRegister(int(log2(n)), 'j')
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(n, 'y')
out = QuantumRegister(1, 'out')
qc = QuantumCircuit(
j_qr,
x_qr,
y_qr,
out
)
qc = qc.compose(parameterized_rot(n), j_qr[:] + y_qr[:])
qc = qc.compose(match_gate(m), x_qr[:] + y_qr[:m] + out[:])
qc = qc.compose(parameterized_rot(n).inverse(), j_qr[:] + y_qr[:])
return qc
pattern_length = 2
text_length = 4
esm(pattern_length, text_length).draw(fold=255)
def esm_oracle(m: int, n: int):
esm_circuit = esm(m, n)
return esm_circuit.to_gate(label='ESMO')
def diffuser(n: int) -> Gate:
qc = QuantumCircuit(n)
qc.h(range(n))
qc.x(range(n))
qc.h(n-1)
qc.mcx(list(range(n-1)), n-1)
qc.h(n-1)
qc.x(range(n))
qc.h(range(n))
return qc.to_gate(label='DIFF')
def grover(esmo: Gate, t: int, x: str, y: str) -> QuantumCircuit:
n = len(y)
m = len(x)
logn = int(log2(n))
num_iterations = int(pi/4 * sqrt(n/t))
j_qr = QuantumRegister(logn, 'j')
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(n, 'y')
out_qr = QuantumRegister(2, 'out')
out_cr = ClassicalRegister(logn+1, 'c')
qc = QuantumCircuit(j_qr, x_qr, y_qr, out_qr, out_cr)
qc.h(j_qr)
qc.x(out_qr[0])
qc.h(out_qr[0])
qc = qc.compose(init_register(x), x_qr[:])
qc = qc.compose(init_register(y), y_qr[:])
for _ in range(num_iterations):
qc = qc.compose(esmo)
qc = qc.compose(diffuser(logn))
qc.measure(j_qr, out_cr[:-1])
qc = qc.compose(esmo, j_qr[:] + x_qr[:] + y_qr[:] + [out_qr[1]])
qc.measure(out_qr[1], out_cr[-1])
return qc
x = '11'
y = '10101100'
esmo = esm_oracle(len(x), len(y))
grover(esmo, 1, x, y).draw(fold=255)
x = '00'
y = '01010101'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 1, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 0 occurrence(s)')
x = '00'
y = '11010011'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 1, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 1 occurrence(s)')
x = '00'
y = '00111001'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 2, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 2 occurrence(s)')
def search(x: str, y: str) -> int:
m = len(x)
n = len(y)
esmo = esm_oracle(m, n)
for t in range(1, int(n/2) + 1):
print('Trying with t =', t)
results = run(grover(esmo, t, x, y), 1)
results = list(results.keys())[0]
outcome = int(results[0])
position = int(results[1:], 2)
if outcome: return position
else: print('Pattern not found in position', position)
return -1
x = input('Enter the value of x: ')
y = input('Enter the value of y: ')
if len(x) > len(y):
raise Exception('The length of x must be shorter than the length of y.')
if x.count('0') + x.count('1') < len(x):
raise Exception('The pattern must be a binary string.')
if y.count('0') + y.count('1') < len(y):
raise Exception('The text must be a binary string.')
print('')
position = search(x, y)
if position >= 0: print('Pattern occurrence found in position', str(position))
else: print('Pattern occurrence not found.')
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
from qiskit.utils import QuantumInstance
from qiskit.algorithms.minimum_eigen_solvers import VQE
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import SPSA
from qiskit_aer import Aer
from qrao import (
QuantumRandomAccessOptimizer,
QuantumRandomAccessEncoding,
SemideterministicRounding,
MagicRounding,
)
from qrao.utils import get_random_maxcut_qp
# Generate a random QUBO in the form of a QuadraticProgram
problem = get_random_maxcut_qp(degree=3, num_nodes=6, seed=1, draw=True)
# Create and encode the problem using the (3,1,p)-QRAC
encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3)
encoding.encode(problem)
backend = Aer.get_backend("aer_simulator")
# Create a QuantumInstance for solving the relaxed Hamiltonian using VQE
relaxed_qi = QuantumInstance(backend=backend, shots=500)
# Create a QuantumInstance for magic rounding
rounding_qi = QuantumInstance(backend=backend, shots=1000)
# Set up the variational quantum eigensolver (ansatz width is determined by the encoding)
vqe = VQE(
ansatz=RealAmplitudes(encoding.num_qubits),
optimizer=SPSA(maxiter=50),
quantum_instance=relaxed_qi,
)
# Use magic rounding
rounding_scheme = MagicRounding(rounding_qi)
# Construct the optimizer
qrao = QuantumRandomAccessOptimizer(
encoding=encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme
)
# Solve the optimization problem
results = qrao.solve()
print(results)
# Calculate number of consolidated samples
len(results.samples)
# The first solution sample (which is not optimal in this case since the optimal
# function value is 14.0)
results.samples[0]
print(f"The optimal function value is {results.fval} at {results.x}.")
# Solve the relaxed problem manually
relaxed_results, rounding_context = qrao.solve_relaxed()
# Print the MinimumEigensolverResult object, from Terra
print(relaxed_results)
mr_results = MagicRounding(rounding_qi).round(rounding_context)
print(
f"Collected {len(mr_results.samples)} samples in {mr_results.time_taken} seconds."
)
sdr_results = SemideterministicRounding().round(rounding_context)
print(f"Performed semideterministic rounding ({len(sdr_results.samples)} sample).")
print(f"Result: {sdr_results.samples[0]}")
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PaulaGarciaMolina/QNLP_Qiskit_Hackathon
|
PaulaGarciaMolina
|
import numpy as np
import math
import pickle
from discopy import Ty, Word # Import the classes for the type of word and for the word
s, n = Ty('s'), Ty('n') # Define the types s (sentence) and n (noun)
# Define the words (notice that we include both meaning and grammar)
# nouns (subjects)
man, woman = Word('man', n), Word('woman', n)
mujer, hombre = Word('mujer', n), Word('hombre', n)
# nouns (objects)
car, sofa, notebook = Word('car', n), Word('sofa', n), Word('notebook', n)
coche, sillon, cuaderno = Word('coche', n), Word('sillon', n), Word('cuaderno', n)
# adjectives
old, new, red, blue = Word('old', n @ n.l), Word('new', n @ n.l), Word('red', n @ n.l), Word('blue', n @ n.l)
viejo, nuevo, rojo, azul = Word('viejo', n.r @ n), Word('nuevo', n.r @ n ), Word('rojo', n.r @ n ), Word('azul', n.r @ n )
# Transitive verbs
buys, steals, breaks = Word('buys', n.r @ s @ n.l), Word('steals', n.r @ s @ n.l), Word('breaks', n.r @ s @ n.l)
compra, roba, rompe = Word('compra', n.r @ s @ n.l), Word('roba', n.r @ s @ n.l), Word('rompe', n.r @ s @ n.l)
subjects = [man, woman]
sujetos = [mujer, hombre]
verbs = [buys, steals, breaks]
verbos = [compra, roba, rompe]
adjectives = [old, new, red, blue]
adjetivos = [viejo, nuevo, rojo, azul]
objects = [car, sofa, notebook]
objetos = [coche, sillon, cuaderno]
#Save the vocabulary
vocab_E = subjects + verbs + adjectives + objects #English words
vocab_S = sujetos + verbos + adjetivos + objetos #Spanish words
from discopy import Cup, Id, pregroup
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n)
sentence = woman @ buys @ car >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n)
sentence = woman @ buys @ new @ car >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id (s @ n.l) @ Cup(n, n.r) @ Id(n) >> Id(s) @ Cup(n.l, n) >> Id(s)
sentence = mujer @ compra @ coche @ viejo >> grammar
pregroup.draw(sentence)
from discopy import Diagram
from discopy.grammar import draw
# Store the grammatical structures in a dictionary
grammar_dict = {
'NVN' : Cup(n, n.r) @ Id(s) @ Cup(n.l, n),
'NVAN' : Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n),
'NVNA' : Cup(n, n.r) @ Id (s @ n.l) @ Cup(n, n.r) @ Id(n) >> Id(s) @ Cup(n.l, n) >> Id(s)}
# Create parsing (grammatical analysis) dictionary where the grammatical sentences
# are the keys and the associated values are the diagrams (words + grammar)
data_psr = {}
# English noun+verb+noun sentences
parsing_NVNe = {"{} {} {}.".format(subj, verb, obj): subj @ verb @ obj >> grammar_dict['NVN']
for subj in subjects for verb in verbs for obj in objects}
sentences_NVNe = list(parsing_NVNe.keys())
for sentence in sentences_NVNe:
diagram = parsing_NVNe[sentence]
data_psr[sentence] = parsing_NVNe[sentence]
# Spanish noun+verb+noun sentences
parsing_NVNs = {"{} {} {}.".format(subj, verb, obj): subj @ verb @ obj >> grammar_dict['NVN']
for subj in sujetos for verb in verbos for obj in objetos}
sentences_NVNs = list(parsing_NVNs.keys())
for sentence in sentences_NVNs:
diagram = parsing_NVNs[sentence]
data_psr[sentence] = parsing_NVNs[sentence]
# English noun+verb+adjective+noun sentences
parsing_NVANe = {"{} {} {} {}.".format(subj, verb, adj, obj): subj @ verb @ adj @ obj >> grammar_dict['NVAN']
for subj in subjects for verb in verbs for adj in adjectives for obj in objects}
sentences_NVANe = list(parsing_NVANe.keys())
for sentence in sentences_NVANe:
diagram = parsing_NVANe[sentence]
data_psr[sentence] = parsing_NVANe[sentence]
# Spanish noun+verb+noun+adjectives sentences
parsing_NVNAs = {"{} {} {} {}.".format(subj, verb, obj, adj): subj @ verb @ obj @ adj >> grammar_dict['NVNA']
for subj in sujetos for verb in verbos for obj in objetos for adj in adjetivos}
sentences_NVNAs = list(parsing_NVNAs.keys())
for sentence in sentences_NVNAs:
diagram = parsing_NVNAs[sentence]
data_psr[sentence] = parsing_NVNAs[sentence]
#*****************************************************************************************************
#Load datasets containing sentences and labels
#*****************************************************************************************************
#Small (20 sentences in english and 20 in spanish; 400 possible combinations)
with open('DataSet_SI_eng_small.txt') as f:
dataeng_small = f.readlines()
with open('DataSet_SI_spa_small.txt') as f:
dataspa_small = f.readlines()
with open('TrainingSet_SI_labels_small.txt') as f:
train_labels_small = f.readlines()
with open('TestSet_SI_labels_small.txt') as f:
test_labels_small = f.readlines()
#Medium (65 sentences in english and 65 in spanish; 4225 possible combinations)
with open('DataSet_SI_eng_medium.txt') as f:
dataeng_medium = f.readlines()
with open('DataSet_SI_spa_medium.txt') as f:
dataspa_medium = f.readlines()
with open('TrainingSet_SI_labels_medium.txt') as f:
train_labels_medium = f.readlines()
with open('TestSet_SI_labels_medium.txt') as f:
test_labels_medium = f.readlines()
#Big (90 sentences in english and 90 in spanish; 8100 possible combinations)
with open('DataSet_SI_eng_big.txt') as f:
dataeng_big = f.readlines()
with open('DataSet_SI_spa_big.txt') as f:
dataspa_big = f.readlines()
with open('TrainingSet_SI_labels_big.txt') as f:
train_labels_big = f.readlines()
with open('TestSet_SI_labels_big.txt') as f:
test_labels_big = f.readlines()
#*****************************************************************************************************
# Transform senteces into diagrams
#*****************************************************************************************************
#Small
dataeng_psr_dict_small, dataspa_psr_dict_small= {},{}
dict_small=[dataeng_psr_dict_small, dataspa_psr_dict_small]
sent_type_small={}
data_small=[dataeng_small,dataspa_small]
#Medium
dataeng_psr_dict_medium, dataspa_psr_dict_medium = {},{}
dict_medium=[dataeng_psr_dict_medium, dataspa_psr_dict_medium]
sent_type_medium={}
data_medium=[dataeng_medium,dataspa_medium]
#Big
dataeng_psr_dict_big, dataspa_psr_dict_big = {},{}
dict_big=[dataeng_psr_dict_big, dataspa_psr_dict_big]
sent_type_big={}
data_big=[dataeng_big,dataspa_big]
################
parsing=[parsing_NVNe,parsing_NVNs,parsing_NVANe,parsing_NVNAs]
types=['NVN','NVN','NVAN','NVNA']
for (datasize,dictsize,sent_type) in zip([data_small,data_medium,data_big],[dict_small,dict_medium,dict_big],
[sent_type_small,sent_type_medium,sent_type_big]):
for (data,data_psr_dict) in zip(datasize,dictsize):
for sentence in data:
sentstr = sentence[:-1]
for (par,typ) in zip(parsing,types):
if sentstr in list(par.keys()):
diagram = par[sentstr]
data_psr_dict[sentstr] = diagram
sent_type[sentstr] = typ
#*****************************************************************************************************
# Save labels in lists to be used later on
#*****************************************************************************************************
#Training set (To train the paramenters)
train_labelslist_small,train_labelslist_medium,train_labelslist_big=[],[],[]
train_labelslist=[train_labelslist_small,train_labelslist_medium,train_labelslist_big]
trainset_labels=[train_labels_small,train_labels_medium,train_labels_big]
for (labelslist,labelsset) in zip(train_labelslist,trainset_labels):
for pair in labelsset:
label=pair[-2]
labelslist.append(label)
#Testing set (To test the trained paramenters)
test_labelslist_small,test_labelslist_medium,test_labelslist_big=[],[],[]
test_labelslist=[test_labelslist_small,test_labelslist_medium,test_labelslist_big]
testset_labels=[test_labels_small,test_labels_medium,test_labels_big]
for (labelslist,labelsset) in zip(test_labelslist,testset_labels):
for pair in labelsset:
label=pair[-2]
labelslist.append(label)
#*****************************************************************************************************
# Remove resource-consumming cups and transform them into effects (see [2])
#*****************************************************************************************************
from discopy import Cap, Box
#Old data with cups
dataeng_psr_dict_sizes=[dataeng_psr_dict_small,dataeng_psr_dict_medium,dataeng_psr_dict_big]
dataspa_psr_dict_sizes=[dataspa_psr_dict_small,dataspa_psr_dict_medium,dataspa_psr_dict_big]
#New data with effects
dataeng_new_psr_dict_small,dataeng_new_psr_dict_medium,dataeng_new_psr_dict_big = {},{},{}
dataspa_new_psr_dict_small,dataspa_new_psr_dict_medium,dataspa_new_psr_dict_big = {},{},{}
dataeng_new_psr_dict_sizes=[dataeng_new_psr_dict_small,dataeng_new_psr_dict_medium,dataeng_new_psr_dict_big]
dataspa_new_psr_dict_sizes=[dataspa_new_psr_dict_small,dataspa_new_psr_dict_medium,dataspa_new_psr_dict_big]
###########
sent_type_size=[sent_type_small,sent_type_medium,sent_type_big]
for (dataeng_new_psr_dict,dataspa_new_psr_dict,
dataeng_psr_dict,dataspa_psr_dict,sent_type) in zip(dataeng_new_psr_dict_sizes,dataspa_new_psr_dict_sizes,
dataeng_psr_dict_sizes,dataspa_psr_dict_sizes,sent_type_size):
for (data_psr_dict,data_new_psr_dict) in zip([dataeng_psr_dict,dataspa_psr_dict],
[dataeng_new_psr_dict,dataspa_new_psr_dict]):
for sentstr in data_psr_dict.keys():
num_words = len(sentstr.split(' '))
words = data_psr_dict[sentstr].boxes[:num_words]
if sent_type[sentstr] == 'NVN': #noun-verb-noun sentences (English and Spanish)
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[2].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2) # Rearranged words
sentence = words_new >> grammar_dict['NVN'] # Apply grammar on rearranged words
data_new_psr_dict[sentstr] = sentence.normal_form() # Store sentence with optimum diagram
elif sent_type[sentstr] == 'NVAN': #noun-verb-adjective-noun sentences (English)
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['NVAN']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'NVNA': #noun-verb-noun-adjective sentences (Spanish)
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[2].name, n.r, Ty())
words_new = (Cap(n.r, n) @ Cap(n.r, n)) >> (noun1 @ Id(n) @ words[1] @ noun2 @ Id(n) @ words[3])
sentence = words_new >> grammar_dict['NVNA']
data_new_psr_dict[sentstr] = sentence.normal_form()
#*****************************************************************************************************
# Redefine the vocabulary according to the new domain and code nouns as effects.
#*****************************************************************************************************
from discopy import Cap, Box
#English
vocab_psr_E = []
for word in vocab_E:
if word.cod == Ty('n'):
vocab_psr_E.append(Box(word.name, n.r, Ty()))
else:
vocab_psr_E.append(word)
#Spanish
vocab_psr_S = []
for word in vocab_S:
if word.cod == Ty('n'):
vocab_psr_S.append(Box(word.name, n.r, Ty()))
else:
vocab_psr_S.append(word)
vocab_psr=vocab_psr_E+vocab_psr_S
#*****************************************************
# Functions to deal with the ansätze (functions from [2])
#*****************************************************
from discopy.quantum import Ket, IQPansatz, Bra, qubit
from discopy.quantum import Ket, IQPansatz, Bra, qubit
from discopy.quantum.gates import Rx, Rz
from discopy.quantum.circuit import Functor, Id
from discopy.quantum.circuit import Circuit
from functools import reduce, partial
q_s = 2 # number of qubits for type s (sentence)
q_n = 1 # number of qubits for type n (noun)
depth = 1 # depth of the IQPansatz
p_n = 1 # number of parameters for a single-qubit word (noun); valued in {1,2,3}.
# Define the dimensions of the objects of the circuit functor
ob = {s: q_s, n: q_n}
ob_cqmap = {s: qubit ** q_s, n: qubit ** q_n}
# Define the ansätze for states and effects
def single_qubit_iqp_ansatz(params):
if len(params) == 1:
return Rx(params[0])
if len(params) == 2:
return Rx(params[0]) >> Rz(params[1])
if len(params) == 3:
return IQPansatz(1, params)
def ansatz_state(state, params):
arity = sum(ob[Ty(factor.name)] for factor in state.cod)
if arity == 1:
return Ket(0) >> single_qubit_iqp_ansatz(params)
else:
return Ket(*tuple([0 for i in range(arity)])) >> IQPansatz(arity, params)
def ansatz_effect(effect, params):
arity = sum(ob[Ty(factor.name)] for factor in effect.dom)
if arity == 1:
return single_qubit_iqp_ansatz(params) >> Bra(0)
else:
return IQPansatz(arity, params) >> Bra(*tuple([0 for i in range(arity)]))
def ansatz(box,params):
dom_type = box.dom
cod_type = box.cod
if len(dom_type) == 0 and len(cod_type) != 0:
return ansatz_state(box, params)
if len(dom_type) != 0 and len(cod_type) == 0:
return ansatz_effect(box, params)
# Construct the circuit functor
def F(params):
ar = dict()
for i in range(len(vocab_psr)):
pgbox = vocab_psr[i]
qbox = ansatz(vocab_psr[i], params[i])
ar.update({pgbox: qbox})
if pgbox.cod == Ty():
ar.update({Box(pgbox.name, n.l, Ty()): qbox})
return Functor(ob_cqmap, ar)
#*****************************************************
# Functions to deal with the parametrisation (functions from [2])
#*****************************************************
def paramshapes(vocab_psr):
parshapes = []
for box in vocab_psr:
dom_type = box.dom
cod_type = box.cod
dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom)
cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod)
if dom_arity == 0 or cod_arity == 0:
arity = max(dom_arity, cod_arity)
assert arity != 0
if arity == 1:
parshapes.append((p_n,))
if arity != 1:
parshapes.append((depth, arity-1))
return parshapes
def randparams(par_shapes):
params = np.array([])
for i in range(len(par_shapes)):
params = np.concatenate((params, np.ravel(np.random.rand(*par_shapes[i]))))
return params
def reshape_params(unshaped_pars, par_shapes):
pars_reshaped = [[] for ii in range(len(par_shapes))]
shift = 0
for ss, s in enumerate(par_shapes):
idx0 = 0 + shift
if len(s) == 1:
idx1 = s[0] + shift
elif len(s) == 2:
idx1 = s[0] * s[1] + shift
pars_reshaped[ss] = np.reshape(unshaped_pars[idx0:idx1], s)
if len(s) == 1:
shift += s[0]
elif len(s) == 2:
shift += s[0] * s[1]
return pars_reshaped
#****************************************
# Parameters of the current model
#****************************************
par_shapes = paramshapes(vocab_psr)
rand_unshaped_pars = randparams(par_shapes)
rand_shaped_pars = reshape_params(rand_unshaped_pars, par_shapes)
print('Number of parameters: ', len(rand_unshaped_pars))
#****************************************
# Transform sentences diagrams into Qiskit Quantum Circuits
#****************************************
from pytket.extensions.qiskit import tk_to_qiskit
from discopy.quantum import Measure
def to_qiskitcircuit(unshaped_params,diagrams_dict):
"""Function to transform a DisCoCat diagram into a Qiskit Quantum Circuit.
Args:
unshaped_params = parameters to the variationals circuits.
diagrams_dict = dictionary with the sentences as keys and their diagrams as values.
Returns:
Qiskit Quantum Circuit.
"""
func = F(reshape_params(unshaped_params, par_shapes))
circs=[]
for sentstr in diagrams_dict.keys():
diagram=diagrams_dict[sentstr]
circuit=(func(diagram) >> Measure() @ Measure()) #Add the measurements to the circuit
pytket_circuit = circuit.to_tk()
qiskit_circuit = tk_to_qiskit(pytket_circuit) #Create Qiskit Quantum Circuit
circs.append(qiskit_circuit)
return circs
##########
#For example (with random parameters "rand_shaped_pars")
circuits_eng_small,circuits_eng_medium,circuits_eng_big=[],[],[]
circuits_spa_small,circuits_spa_medium,circuits_spa_big=[],[],[]
circuits_eng = [circuits_eng_small,circuits_eng_medium,circuits_eng_big] # list of Qiskit Quantum Crcuits of english sentences
circuits_spa = [circuits_spa_small,circuits_spa_medium,circuits_spa_big] # list of Qiskit Quantum Circuits of spanish sentences
for (circ_eng,circ_spa,dataeng_new_psr_dict,dataspa_new_psr_dict) in zip(circuits_eng,circuits_spa,
dataeng_new_psr_dict_sizes,dataspa_new_psr_dict_sizes):
for (circ,data_new_psr_dict) in zip([circ_eng,circ_spa],
[dataeng_new_psr_dict,dataspa_new_psr_dict]):
circ.append(to_qiskitcircuit(rand_unshaped_pars,data_new_psr_dict))
j=2
print(list(dataeng_new_psr_dict_medium.keys())[j])
circuits_eng_medium[0][j].draw(output='mpl',filename='circuit_example_NVN.pdf')
j=45
print(list(dataeng_new_psr_dict_medium.keys())[j])
circuits_eng_medium[0][j].draw(output='mpl',filename='circuit_example_ADJenglish.pdf')
j=30
print(list(dataspa_new_psr_dict_medium.keys())[j])
circuits_spa_medium[0][j].draw(output='mpl',filename='circuit_example_ADJspanish.pdf')
#****************************************
# Load qiskit classes to execute circuits and IBM-Q account
#****************************************
from qiskit import BasicAer, execute, Aer, IBMQ
from qiskit.quantum_info import Statevector
from qiskit.providers.aer.noise import NoiseModel
provider=IBMQ.load_account()
#****************************************
# Functions to perform the hybrid quantum-classical machine learning (optimization of variational parameters)
#****************************************
####Predict labels (which sentences have the same meaning)
def get_probs(unshaped_params,withshots=True,simulation=True,withnoise=False):
"""Function to get the predicted labels of our dataset from a specific set of parameters.
Args:
unshaped_params = parameters to the variationals circuits.
withshots = True: a limited number of shots will be performed or simulated; False: a classical simulation
equivalent to an unlimited number of shots is performed (statevector simulation). (Default True)
simulation = True: QASM or statevector simulation ; False: real quantum device (ibmq_16_melbourne). (Default True)
withnoise = True: simulate ibmq_16_melbourne noise and architecture; False: not noise model. (Default False)
Returns:
array: predicted labels.
"""
circuits_eng = to_qiskitcircuit(unshaped_params,diagrams_eng)
circuits_spa = to_qiskitcircuit(unshaped_params,diagrams_spa)
if withshots:
if simulation:
if withnoise:
# Build noise model from backend properties
backend = provider.get_backend('ibmq_16_melbourne')
noise_model = NoiseModel.from_backend(backend)
# Get coupling map from backend
coupling_map = backend.configuration().coupling_map
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
else:
noise_model,coupling_map,basis_gates = None,None,None
backend=Aer.get_backend('qasm_simulator')
results=execute(circuits_eng+circuits_spa, backend=backend,shots=n_shots, noise_model=noise_model,
coupling_map=coupling_map,basis_gates=basis_gates).result().get_counts()
else:
ibmq_device='ibmq_16_melbourne'
backend=IBMQ.get_provider(group='internal').get_backend(ibmq_device)
results=execute(circuits_eng+circuits_spa, backend=backend,shots=n_shots).result().get_counts()
results_eng=results[:len(circuits_eng)]
results_spa=results[len(circuits_spa):]
pred_labels_distrs=[]
for countssent_eng in results_eng: #Loop over English sentences
for countssent_spa in results_spa: #Loop over Spanish sentences
predlabel=0
for bits in countssent_eng.keys():
if bits[q_s:]==len(bits[q_s:])*'0': #Postselection
if bits in countssent_spa.keys():
predlabel+=countssent_eng[bits]*countssent_spa[bits]
else:
predlabel+=0
counteng_select,countspa_select=0,0
for bits in countssent_eng.keys():
if bits[q_s:]==len(bits[q_s:])*'0':
counteng_select+=countssent_eng[bits]
for bits in countssent_spa.keys():
if bits[q_s:]==len(bits[q_s:])*'0':
countspa_select+=countssent_spa[bits]
if counteng_select==0 or countspa_select==0:
#print('Total postselction 0')
label=1e-9
else:
label=abs(predlabel/(counteng_select*countspa_select) - 1e-9) #Final label
pred_labels_distrs.append(label)
maxlabel=max(pred_labels_distrs)
pred_labels_distrs_norm=[x/maxlabel for x in pred_labels_distrs]
elif simulation:
backend=Aer.get_backend('statevector_simulator')
state_vector_dicts=[]
for circ in circuits_eng+circuits_spa:
circ.remove_final_measurements()
state_vector_dicts.append(Statevector(circ).to_dict())
qsen=[1,2]
pred_labels_distrs=[]
for countssent_eng in state_vector_dicts[:len(circuits_eng)]:
for countssent_spa in state_vector_dicts[len(circuits_spa):]:
predlabel=0
for bits in countssent_eng.keys():
selections = ['0' * qsen[0] + val + '0' * (len(bits) - qsen[1] - 1) for val in ['00', '01', '10', '11']]
if bits in selections: #Postselection
if bits in countssent_spa.keys():
predlabel+=abs(countssent_eng[bits]**2*countssent_spa[bits]**2)
else:
predlabel+=0
counteng_select,countspa_select=0,0
for bits in countssent_eng.keys():
if bits in selections:
counteng_select+=abs(countssent_eng[bits]**2)
for bits in countssent_spa.keys():
if bits in selections:
countspa_select+=abs(countssent_spa[bits]**2)
if counteng_select==0 or countspa_select==0:
label=1e-9
else:
label=abs(predlabel/(counteng_select*countspa_select) - 1e-9) #Final label
pred_labels_distrs.append(label)
maxlabel=max(pred_labels_distrs)
pred_labels_distrs_norm=[x/maxlabel for x in pred_labels_distrs]
return pred_labels_distrs_norm
####Two possible cost functions for the model (the function that the machine tries to minimize)
def get_cost_crossentropy(pred_labels_distrs):
"""Function to compute the binary cross-entropy from predicted labels.
Args:
pred_labels_distrs = array of predicted labels.
Returns:
float: binary cross-entropy.
"""
cross_entropies = np.array([int(train_labels[s]) * math.log2(pred_labels_distrs[s])
for s in range(len(train_labels)) if train_labels[s]!='x'])
return -1 / len([train_labels[s] for s in range(len(train_labels)) if train_labels[s]!='x']) * np.sum(cross_entropies)
def get_cost_absoluteerror(pred_labels_distrs):
"""Function to compute the absolute error of the predicted labels with respect to the correct ones.
Args:
pred_labels_distrs = array of predicted labels.
Returns:
float: absolute error.
"""
error = 0
train_size=0
for (i, res) in enumerate(pred_labels_distrs):
if train_labels[i]!='x':
train_size+=1
error+=abs(int(train_labels[i])-res)
return error * 100 / train_size
####Error functions for the model (a measure of how many sentences the quantum device translates correctly)
def get_train_error(pred_labels_distrs):
"""Function to compute the percentage of sentences in the training set that the predicted labels translate correctly.
Args:
pred_labels_distrs = array of predicted labels.
Returns:
float: percentage of correct translations.
"""
correct = 0
train_size=0
for (i, res) in enumerate(pred_labels_distrs):
if train_labels[i]!='x':
train_size+=1
try:
pred_result = round(res) #We are taking as 1 (same meaning) when the output is >0.5 and viceversa
except:
pred_result = None
else:
pass
train_result = round(int(train_labels[i]))
if train_result == pred_result:
correct += 1
return 100 - correct * 100 / train_size
def get_test_error(pred_labels_distrs):
"""Function to compute the percentage of sentences in the test set that the predicted labels translate correctly.
Args:
pred_labels_distrs = array of predicted labels.
Returns:
float: percentage of correct translations.
"""
correct = 0
test_size=0
for (i, res) in enumerate(pred_labels_distrs):
if test_labels[i]!='x':
test_size+=1
pred_result = round(res) #We are taking as 1 (same meaning) when the output is >0.5 and viceversa
test_result = round(int(test_labels[i]))
if test_result == pred_result:
correct += 1
return 100 - correct * 100 / test_size
####Other useful functions for performing optimization and tracking intermediate results
def objective_function(unshaped_params,costfunction=get_cost_absoluteerror): #cost_function=get_cost_crossentropy or
"""Objective function to perform an evaluation of the classical optimization from a specific set of parameters.
Args:
unshaped_params = parameters to the variationals circuits.
costfunction = cost function that will be minimized by the classical optimization method.
The options are "get_cost_crossentropy" or "get_cost_absoluteerror". (Default get_cost_absoluteerror)
Returns:
float: value of cost function.
"""
#To perform optimization
pred_labels_distrs=get_probs(unshaped_params,withshots=withshots,simulation=simulation,withnoise=withnoise)
cost=costfunction(pred_labels_distrs)
#To track the results
trainerror=get_train_error(pred_labels_distrs)
testerror=get_test_error(pred_labels_distrs)
cost_crossentr=get_cost_crossentropy(pred_labels_distrs)
cost_abserr=get_cost_absoluteerror(pred_labels_distrs)
tracking=callback(trainerror,testerror,cost_crossentr,cost_abserr)
return cost
def callback(trainerror,testerror,cost_crossentr,cost_abserr):
"""Function to track the results in each objective function evaluation.
Args:
trainerror = array of get_train_error values for each objective function evaluation.
testerror = array of get_test_error values for each objective function evaluation.
cost_crossentr = array of get_cost_crossentropy values for each objective function evaluation.
cost_abserr = array of get_cost_absoluteerror values for each objective function evaluation.
Returns:
-
"""
global error_train_history,error_test_history,cost_crossentropy_history,cost_abserror_history,nevaluations
error_train_history[run].append(trainerror)
error_test_history[run].append(testerror)
cost_crossentropy_history[run].append(cost_crossentr)
cost_abserror_history[run].append(cost_abserr)
print("Cost_AbsErr: {} ,Cost_CrossEntr: {} , ErrorTrain: {}, ErrorTest: {}".format(cost_abserr,cost_crossentr,
trainerror,testerror))
nevaluations+=1
print('NºEvals: ',nevaluations)
#************************************
# Quantum-Classical run: training and error calculation
#************************************
from time import time
from qiskit.algorithms.optimizers import COBYLA,SPSA,L_BFGS_B
####Experiment Parameters
n_runs = 1
niter = 2000
cost_function=get_cost_absoluteerror #costfunction=get_cost_crossentropy or get_cost_absoluteerror
method='SPSA' #Classical optimization method= 'COBYLA','SPSA' or'L_BFGS_B'
n_shots = 8192 # number of shots (maximum in real hardware: 8192)
withshots=True
simulation=True
withnoise=True
dataset='small' #dataset='small','medium','big'
####Data for the experiment
if dataset=='small':
#Diagrams
diagrams_eng = dataeng_new_psr_dict_small
diagrams_spa = dataspa_new_psr_dict_small
#Training and test labels
train_labels = train_labelslist_small
test_labels = test_labelslist_small
if dataset=='medium':
#Diagrams
diagrams_eng = dataeng_new_psr_dict_medium
diagrams_spa = dataspa_new_psr_dict_medium
#Training and test labels
train_labels = train_labelslist_medium
test_labels = test_labelslist_medium
if dataset=='big':
#Diagrams
diagrams_eng = dataeng_new_psr_dict_big
diagrams_spa = dataspa_new_psr_dict_big
#Training and test labels
train_labels = train_labelslist_big
test_labels = test_labelslist_big
####Classical Optimizers (from qiskit.algorithms.optimizers)
if method=='COBYLA':
optimizer=COBYLA(maxiter=niter)
elif method=='SPSA': #Some additional function evaluations are performed to calibrate the hyperparameters
optimizer=SPSA(maxiter=niter)
elif method=='L_BFGS_B':
optimizer=L_BFGS_B(maxiter=niter)
####Tracking variables
param_histories = [[] for r in range(n_runs)]
error_train_history,error_test_history = [[] for r in range(n_runs)],[[] for r in range(n_runs)]
cost_crossentropy_history,cost_abserror_history = [[] for r in range(n_runs)],[[] for r in range(n_runs)]
final_result=[]
####Running
for run in range(n_runs):
print('---------------------------------')
print('Start run ', run+1)
rand_unshaped_pars = randparams(par_shapes)
start = time()
nevaluations=0
res = optimizer.optimize(len(rand_unshaped_pars),objective_function,initial_point=rand_unshaped_pars) #Optimization
print("Parameters: {} ,CostFunction: {} , NºEvaluations: {}".format(res[0],res[1],res[2]))
final_result.append(res)
print('run', run+1, 'done')
print('Time taken: ', time() - start)
####Save the results
data = {'param_histories': param_histories,
'cost_crossentropy_history': cost_crossentropy_history,
'cost_abserror_history': cost_abserror_history,
'error_train_history': error_train_history,
'error_test_history': error_test_history,
'final_result': final_result}
with open('SIresults_it'+str(niter)+'_met'+method+'_size-'+dataset+'_sim'+str(simulation)+'_shots'+str(withshots)+
str(n_shots)+'_withnoise'+str(withnoise)+'_costabserr'+'_0.pickle', 'wb') as file_handle:
pickle.dump(data, file_handle)
#************************************
# Results
#************************************
import matplotlib.pyplot as plt
import pickle
import numpy as np
#######StateVector Simulations
#SPSA 200 iterations
with open('SIresults_it200_metSPSA_size-small_simTrue_shotsFalse8192_costabserr_0.pickle', 'rb') as f:
small_sv_spsa200=pickle.load(f)
with open('SIresults_it200_metSPSA_size-medium_simTrue_shotsFalse8192_costabserr_0.pickle', 'rb') as f:
medium_sv_spsa200=pickle.load(f)
with open('SIresults_it200_metSPSA_size-big_simTrue_shotsFalse8192_costabserr_0.pickle', 'rb') as f:
big_sv_spsa200=pickle.load(f)
#SPSA 1000 iterations
with open('SIresults_it1000_metSPSA_size-small_simTrue_shotsFalse8192_costabserr_0.pickle', 'rb') as f:
small_sv_spsa1000=pickle.load(f)
with open('SIresults_it1000_metSPSA_size-medium_simTrue_shotsFalse8192_withnoiseFalse_costabserr_0.pickle', 'rb') as f:
medium_sv_spsa1000=pickle.load(f)
with open('SIresults_it1000_metSPSA_size-big_simTrue_shotsFalse8192_withnoiseFalse_costabserr_0.pickle', 'rb') as f:
big_sv_spsa1000=pickle.load(f)
#COBYLA 1000 ev
with open('SIresults_it1000_metCOBYLA_size-small_simTrue_shotsFalse8192_costabserr_0.pickle', 'rb') as f:
small_sv_cobyla1000=pickle.load(f)
with open('SIresults_it1000_metCOBYLA_size-medium_simTrue_shotsFalse8192_withnoiseFalse_costabserr_0.pickle', 'rb') as f:
medium_sv_cobyla1000=pickle.load(f)
with open('SIresults_it1000_metCOBYLA_size-big_simTrue_shotsFalse8192_withnoiseFalse_costabserr_0.pickle', 'rb') as f:
big_sv_cobyla1000=pickle.load(f)
#######QASM Simulations
#200 iterations
with open('SIresults_it200_metSPSA_size-small_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f:
small_qs_spsa200=pickle.load(f)
with open('SIresults_it200_metSPSA_size-medium_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f:
medium_qs_spsa200=pickle.load(f)
with open('SIresults_it200_metSPSA_size-big_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f:
big_qs_spsa200=pickle.load(f)
#2000 iterations
with open('SIresults_it2000_metSPSA_size-small_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f: #
small_qs_spsa2000=pickle.load(f)
with open('SIresults_it2000_metSPSA_size-medium_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f:
medium_qs_spsa2000=pickle.load(f)
with open('SIresults_it2000_metSPSA_size-big_simTrue_shotsTrue8192_costabserr_0.pickle', 'rb') as f:
big_qs_spsa2000=pickle.load(f)
####Noisy QASM Simulations
#300 iterations
with open('SIresults_it300_metSPSA_size-medium_simTrue_shotsTrue8192_withnoiseTrue_costabserr_0.pickle', 'rb') as f:
medium_mel_spsa300=pickle.load(f)
with open('SIresults_it300_metSPSA_size-big_simTrue_shotsTrue8192_withnoiseTrue_costabserr_0.pickle', 'rb') as f:
big_mel_spsa300=pickle.load(f)
#Many iterations
with open('SIresults_it2000_metSPSA_size-small_simTrue_shotsTrue8192_withnoiseTrue_costabserr_0.pickle', 'rb') as f:
small_mel_spsa2000=pickle.load(f)
with open('SIresults_it1309_metSPSA_size-medium_simTrue_shotsTrue8192_withnoiseTrue_costabserr_0.pickle', 'rb') as f:
medium_mel_spsa2000=pickle.load(f)
with open('SIresults_it928_metSPSA_size-big_simTrue_shotsTrue8192_withnoiseTrue_costabserr_0.pickle', 'rb') as f:
big_mel_spsa2000=pickle.load(f)
####Functions to process the results obtained from SPSA optimization
def process_result(result,nit):
"""Function to process SPSA results.
Args:
result = array of specific results (cost function or error).
nit = number of iterations performed in SPSA optimization.
Returns:
array: processed results.
"""
res=result[-(nit*2):] #remove calibration steps
return [(res[i]+res[i+1])/2 for i in range(len(res)) if i%2==0]
def secondprocess_result(processresult,nit):
"""Function to obtain the trend of the results.
Args:
processresult = array of result processed by process_result.
nit = number of iterations performed in SPSA optimization.
Returns:
[array,array]: [np.arange of the points, trend].
"""
res = processresult
for number in range(20,0,-1):
if nit%number==0:
break
y = [sum([res[i+x] for x in range(number)])/number for i in range(len(processresult)) if i%number==0]
x = np.arange(0,nit,nit/len(y))
return x,y
#************************************
# Plot the Results
#************************************
fig, axes = plt.subplots(3,2,figsize=(35,42))
nit=[[1000,1000,1000],[2000,2000,2000],[2000,1308,928]]
font=35
lw=5
colors=['red','green','orange']
label=['Small','Medium','Big']
results=[[small_sv_spsa1000,medium_sv_spsa1000,big_sv_spsa1000],[small_qs_spsa2000,medium_qs_spsa2000,big_qs_spsa2000],
[small_mel_spsa2000,medium_mel_spsa2000,big_mel_spsa2000]]
titles=[r'Statevector simulation (NºShots=$\infty$)',r'QASM simulation (NºShots=8192)',
'IBMQ_16_Melbourne simulation (NºShots=8192)']
for (result,ax,title,iterations) in zip(results,axes[:,0],titles,nit):
for (res,col,lab,it) in zip(result,colors,label,iterations):
y=process_result(res['error_train_history'][0],it)[:it]
x=np.arange(0,len(y))
pl=ax.plot(x,y,color=col,alpha=0.3)
x2,y2 = secondprocess_result(y,it)
pl=ax.plot(x2,y2,color=col,label=lab,linewidth=lw)
ax.set_ylabel('Train Error (%)',fontsize=font)
ax.set_xlabel('SPSA iterations',fontsize=font)
ax.set_title(title,fontsize=font)
ax.tick_params(axis='both', labelsize=font)
leg=ax.legend(title='Dataset size',fontsize=font-3)
plt.setp(leg.get_title(),fontsize=font-3)
for (result,ax,title,iterations) in zip(results,axes[:,1],titles,nit):
for (res,col,lab,it) in zip(result,colors,label,iterations):
y=process_result(res['error_test_history'][0],it)
x=np.arange(0,len(y))
pl=ax.plot(x,y,color=col,alpha=0.3)
x2,y2 = secondprocess_result(y,it)
pl=ax.plot(x2,y2,color=col,label=lab,linewidth=lw,linestyle='--')
ax.set_ylabel('Test Error (%)',fontsize=font)
ax.set_xlabel('SPSA iterations',fontsize=font)
ax.set_title(title,fontsize=font)
ax.tick_params(axis='both', labelsize=font)
leg=ax.legend(title='Dataset size',fontsize=font-3)
plt.setp(leg.get_title(),fontsize=font-3)
plt.savefig('results_itSPSA.pdf')
plt.show(pl)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/iamr0b0tx/qiskit_practice
|
iamr0b0tx
|
import numpy as np
# import qiskit libs
from qiskit import IBMQ, QuantumCircuit, Aer, execute
from qiskit.quantum_info import Operator
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
API_KEY = 'c6f6569ab6b6f9ec1a437d4d1187b7c7ea2ac4bd91679613e204e7bb9728efd9639af14a86f840cbb05e60b6a249e532e3168c7dbff07edc4c37de9c4bb3e0b3'
try:
provider = IBMQ.enable_account(API_KEY)
except Exception as e:
print(e)
# qiskit plot tool
from qiskit.visualization import plot_histogram
def phase_oracle(n, indices_to_mark, name="Oracle"):
qc = QuantumCircuit(n, name=name)
oracle_matrix = np.identity(2**n)
for index_to_mark in indices_to_mark:
oracle_matrix[index_to_mark, index_to_mark] = -1
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
qc = QuantumCircuit(n, name="Diffuser (V)")
qc.h(range(n))
qc.append(phase_oracle(n, [0]), range(n))
qc.h(range(n))
return qc
def grover(n, marked):
qc = QuantumCircuit(n, n)
r = int(np.round(np.pi / (4 * np.arcsin(np.sqrt(len(marked) / 2**n))) - 1/2))
print(f'{n} qubits, basis state {marked} marked, {r} rounds')
qc.h(range(n))
for _ in range(r):
qc.append(phase_oracle(n, marked), range(n))
qc.append(diffuser(n), range(n))
qc.measure(range(n), range(n))
return qc
n = 5
x = np.random.randint(2**n)
marked = [x]
qc = grover(n, marked)
qc.draw()
# using local simulator
backend = Aer.get_backend('qasm_simulator')
results = execute(qc, backend=backend, shots=10_000).result()
counts = results.get_counts(qc)
print(counts)
print(np.pi / (4 * np.arcsin(np.sqrt(len(marked) / 2**n))) - 1/2)
plot_histogram(counts)
x, bin(x)
|
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 drawing of timeline drawer."""
import numpy as np
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import drawings, types
class TestDrawingObjects(QiskitTestCase):
"""Tests for drawings."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
# bits
self.qubits = list(qiskit.QuantumRegister(2))
# metadata
self.meta1 = {"val1": 0, "val2": 1}
self.meta2 = {"val1": 2, "val2": 3}
# style data
self.style1 = {"property1": 0, "property2": 1}
self.style2 = {"property1": 2, "property2": 3}
def test_line_data_equivalent(self):
"""Test LineData equivalent check."""
xs = list(np.arange(10))
ys = list(np.ones(10))
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_line_data_equivalent_abstract_coord(self):
"""Test LineData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.LineData(
data_type=types.LineType.BARRIER,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent(self):
"""Test BoxData equivalent check."""
xs = [0, 1]
ys = [0, 1]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_box_data_equivalent_abstract_coord(self):
"""Test BoxData equivalent check with abstract coordinate."""
xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP]
obj1 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.BoxData(
data_type=types.BoxType.SCHED_GATE,
bit=self.qubits[0],
xvals=xs,
yvals=ys,
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent(self):
"""Test TextData equivalent check."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=0,
yval=0,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_text_data_equivalent_abstract_coord(self):
"""Test TextData equivalent check with abstract coordinate."""
obj1 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta1,
styles=self.style1,
)
obj2 = drawings.TextData(
data_type=types.LabelType.GATE_NAME,
bit=self.qubits[0],
xval=types.AbstractCoordinate.LEFT,
yval=types.AbstractCoordinate.BOTTOM,
text="test",
latex="test",
meta=self.meta2,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent(self):
"""Test BitLinkData equivalent check."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2
)
self.assertEqual(obj1, obj2)
def test_bit_link_data_equivalent_abstract_coord(self):
"""Test BitLinkData equivalent check with abstract coordinate."""
obj1 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style1,
)
obj2 = drawings.GateLinkData(
bits=[self.qubits[0], self.qubits[1]],
xval=types.AbstractCoordinate.LEFT,
styles=self.style2,
)
self.assertEqual(obj1, obj2)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qiskit.__qiskit_version__
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts
IBMQ.load_account()
n = 13 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
djCircuit.draw(output='mpl',scale=0.5)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
djCompiled = transpile(djCircuit, backend=backend, optimization_level=1)
djCompiled.draw(output='mpl',scale=0.5)
job = execute(djCompiled, backend=backend, shots=1024)
job_monitor(job)
results = job.result()
answer = results.get_counts()
threshold = int(0.01 * shots) # the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} # filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) # number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts # the removed counts are assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/Chibikuri/Quantum-Othello
|
Chibikuri
|
# -*- coding: utf-8 -*-
import warnings
# warnings.filterwarnings('ignore')
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import np
import time
import datetime
import random
import np
import pandas as pd
import multiprocessing as mul
import umap
import csv
import pandas as pd
from scipy.sparse.csgraph import connected_components
from notification import Notify
from scipy.special import expit
from multiprocessing import pool
from pprint import pprint
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.manifold import TSNE
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer, compile
from numpy import pi
from qiskit.tools.visualization import plot_histogram, circuit_drawer
from qiskit.tools.visualization import matplotlib_circuit_drawer
from numba import jit
from matplotlib.colors import ListedColormap as clp
class QVC:
def __init__(self, qubits, cbits, target, shots, l_iteration, dimension, n_class):
'''
This is initial config.
qubits, cbits: the instance of qubits, classical bits
qc: the name of circuit
num_q, num_c: the number of qubits, cbits
train, test: the directory of training data, test data
'''
self.q = QuantumRegister(qubits)
self.c = ClassicalRegister(cbits)
self.qc = QuantumCircuit(self.q, self.c)
self.num_q = qubits
self.num_c = cbits
self.target = target
self.shots = shots
self.l_iter = l_iteration
self.dim = dimension
self.n_class = n_class
def _reduce_dimension(self):
pass
def _feature_map(self, qc, S, data_angle):
'''
Quantum State Mapping
apply feature map circuit(fig1 b)
using two qubits for making reading feature map
1.applying feature map circuit to 0state. <-- in this part
2.training theta
3.measurement
4.fitting cost function
qc : circuit name
S : the number of test data set
x_angle : the angle for fitting traingin data sets
### In this paper, x_angle is artifitially generated.
'''
q = self.q
n = self.num_q
# TODO understand how to decide theta of u1
for i in range(n):
qc.h(q[i])
qc.u1(data_angle[0], q[0])
for j in range(S-1):
qc.cx(q[j], q[j+1])
qc.u1(data_angle[j], q[j+1])
qc.cx(q[j], q[j+1])
qc.u1(data_angle[S-1], q[S-1])
for i in range(n):
qc.h(q[i])
qc.u1(data_angle[0], q[0])
for j in range(S-1):
qc.cx(q[j], q[j+1])
qc.u1(data_angle[j], q[j+1])
qc.cx(q[j], q[j+1])
qc.u1(data_angle[S-1], q[S-1])
return qc
def _w_circuit(self, qc, theta_list):
'''
repeat this circuit for l times to classify
qc: The name of quantum circuit
theta : the angle for u3gate
'''
q = self.q
n = self.num_q
# TODO how to tune the theta_list
# for ini in range(n):
# qc.u3(theta_list[ini], 0, theta_list[ini], q[ini]) # FIXME This part is wrong? should be one time but this part is apply many times.
for iter in range(self.l_iter):
for j in range(1, n):
qc.cz(q[j-1], q[j])
qc.cz(q[n-1], q[0])
# TODO how to decide lambda of u3?
for m in range(n):
qc.u3(0, 0, theta_list[m], q[m])
return qc
def _R_emp(self, distribution, y, bias):
'''
this is cost fucntion for optimize theta(lambda)
theta: lambda for u3 gate
'''
a_1 = (np.sqrt(self.shots)*(1/2-(distribution-y*bias/2)))
a_2 = np.sqrt(abs(2*(1-distribution)*distribution))
sig = expit(a_1/a_2) # expit is sigmoid function
print(sig)
# FIXME 1/T should multiplied by the sum of emps?
return 1/self.dim * sig
def _multi_emp_cost(self, count, correct_class):
binlabel = self._label2binary(correct_class)
print(max(count, key=count.get))
n_c = count[binlabel]
oth_dict = count.pop(binlabel)
at = (np.sqrt(self.shots)*max(count.values())-n_c)
bt = np.sqrt(2*(self.shots-n_c)*n_c)
return expit(at/bt)
# @jit
def _multic_cost(self, val_list, correct_class):
# print(val_list)
n_c = val_list[correct_class]
_ = val_list.pop(correct_class)
at = (np.sqrt(self.shots)*max(val_list)-n_c)
bt = np.sqrt(2*(self.shots-n_c)*n_c)
return expit(at/bt)
def _label2binary(self, correct_class):
'''
maybe no need this function.
input: class label ex 3
-------------------------------------
output: binary(String) ex.'0000000100'
correct class -> binary label boolean
now:10qubit # FIXME fir for any qubits.
'''
if correct_class == 0:
return '0'*self.dim
else:
return '0'*(self.dim-correct_class)+'1'+'0'*(correct_class-1)
def _aggregate(self, count, labels):
'''
input:count
output:list(aggregate by number)
'''
values = []
for k in labels:
rc = 0
for i, j in zip(count.keys(), count.values()):
if list(i)[self.dim-1-k] == '1': # FIXME wrong?
rc += (j/self.shots)
values.append(rc)
return values
def fit(self, x_data, y_data, labels):
''' training and fitting parameter
1.applying feature map circuit to 0state.
2.training theta <-- in this part
3.measurement
4.fitting cost function
'''
initial_theta = [0.01]*self.num_q
b = list(np.arange(-1, 1, 0.1))
x_data = zip(*[iter(x_data)]*3)
y_data = zip(*[iter(y_data)]*3)
while True:
count = 0
params = []
emp_cost = [99, 99]
theta_l = [initial_theta, initial_theta]
for training_data, t_label in zip(x_data, y_data): # like(1, 3, 4)
fit_theta = self._fitting_theta(theta_l, emp_cost, count)
# print("fit!", fit_theta)
count_results = self._circuit(fit_theta, list(training_data)) # array
# print(theta_l)
theta_l.append(fit_theta)
bias = random.choice(b)
# print(t_label)
for i, j in zip(count_results, t_label):
count_vals = self._aggregate(i, labels)
empirical = self._multic_cost(count_vals, list(t_label).index(j))
emp_cost.append(empirical)
# print(emp_cost)
count += 1
print("="*25, count, "="*25)
if self.isOptimized(min(emp_cost)):
break
index = np.array(emp_cost).argmin()
# print("min 1", theta_l[-1])
return theta_l[-1]
def isOptimized(self, empirical_cost):
'''
This fucntion is for checking R_empirical is optimized or not.
empirical_cost : the value of R_emp()
'''
# return True
# if len(empirical_cost) > 3:
# if empirical_cost[-1] == min(empirical_cost):
# return True
# else:
# return False
# if len(empirical_cost) > 5:
# return True
return True
def _fitting_theta(self, theta_list, Rempirical_cost, count):
# print("fit_theta!", theta_list)
# print("emps!", Rempirical_cost)
theta_range = 2*self.dim*(self.l_iter+1)
interval = 2*pi/theta_range
index = np.mod(count, self.dim+1)
sum_list = [interval if i == index else 0 for i in range(self.dim)]
n_thetalist = np.array(theta_list[-2]) + np.array(sum_list)
theta_list.append(list(n_thetalist))
if Rempirical_cost[-1] < Rempirical_cost[-2]:
return theta_list[-1]
else:
return theta_list[-2]
def _circuit(self, theta_list, training_data):
qc = self.qc
q = self.q
c = self.c
# TODO we have to chenge the angle of feature map for each data.
# TODO multi circuit
mean = np.median(training_data, axis=0)
# feature_angle = [((mean - (training_data[i]))**2) for i in range(self.dim)]
# feature_angle = [(np.sin(training_data[0]))*(np.sin(training_data[1]))*(np.sin(training_data[2])) for i in range(3)]
qc_list = []
for data in training_data:
# print(data)
feature_angle = [(pi - 1/np.exp(i)) for i in data]
self._feature_map(qc, self.dim, feature_angle)
self._w_circuit(qc, theta_list)
qc.measure(q, c)
qc_list.append(qc)
backends = ['ibmq_20_tokyo',
'qasm_simulator',
'ibmqx_hpc_qasm_simulator',
'statevector_simulator']
backend_options = {'max_parallel_threads': 0,
'max_parallel_experiments': 0,
'max_parallel_shots': 0,
'statevector_parallel_threshold': 12}
backend = Aer.get_backend(backends[1])
qobj_list = [compile(qc, backend) for qc in qc_list]
count_list = []
job_list = [backend.run(qobj) for qobj in qobj_list]
for job in job_list:
counts = job.result().get_counts()
# print([(k,v) for k, v in counts.items() if v > 10])
count_list.append(counts)
# print(count_list)
return count_list
def _test_circuit(self, theta_list, test_data):
qc = self.qc
q = self.q
c = self.c
# TODO we have to chenge the angle of feature map for each data.
# TODO multi circuit
# mean = np.median(training_data, axis=0)
# feature_angle = [((mean - (training_data[i]))**2) for i in range(self.dim)]
# feature_angle = [(np.sin(training_data[0]))*(np.sin(training_data[1]))*(np.sin(training_data[2])) for i in range(3)]
feature_angle = [(pi - np.sin(i)) for i in test_data]
self._feature_map(qc, self.dim, feature_angle)
self._w_circuit(qc, theta_list)
qc.measure(q, c)
# qc_list.append(qc)
backends = ['ibmq_20_tokyo',
'qasm_simulator',
'ibmqx_hpc_qasm_simulator',
'statevector_simulator']
backend_options = {'max_parallel_threads': 0,
'max_parallel_experiments': 0,
'max_parallel_shots': 0,
'statevector_parallel_threshold': 12}
backend = Aer.get_backend(backends[1])
exec = execute(qc, backend, shots=self.shots, config=backend_options)
result = exec.result()
counts = result.get_counts(qc)
# print([k for k, v in counts.items() if v > 10])
return counts
def predict(self, test_data, theta_list, label):
# FIXME have to modify add testdata and
# for p in parameter:
vals = []
# for theta in theta_list:
count_results = self._test_circuit(theta_list, test_data)
test_val = self._aggregate(count_results, label)
answer = label[np.array(test_val).argmax()]
return answer
@staticmethod
def calc_accuracy(labels, test_y):
correct_answer = 0
for i, j in zip(labels, test_y):
if i == j:
correct_answer += 1
return correct_answer/len(test_y)
def visualize(self, x, y, theta, bias, resolution=0.5):
# print(x)
markers = ('o', 'x')
cmap = clp(('red', 'blue'))
x1_min, x1_max = x[:, 0].min()-1, x[:, 0].max()+1
x2_min, x2_max = x[:, 1].min()-1, x[:, 1].max()+1
x1_mesh, x2_mesh = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
z = self.predict(np.array([x1_mesh.ravel(), x2_mesh.ravel()]).T, theta, bias)
z = np.array(z)
z = z.reshape(x1_mesh.shape)
# print(z)
plt.contourf(x1_mesh, x2_mesh, z, alpha=0.4, cmap=cmap)
plt.xlim(x1_mesh.min(), x1_mesh.max())
plt.ylim(x2_mesh.min(), x2_mesh.max())
@staticmethod
def _sigmoid(x):
return 1/(1+np.exp(-x))
@staticmethod
def _ReLU(x):
return max(0, x)
@staticmethod
def _ELU(x):
if x > 0:
return x
else:
return np.exp(x) - 1
@staticmethod
def circle_data(r):
x = np.arange(-r, r, r/100)
print(np.sqrt((r**2)-(x**2)), -np.sqrt((r**2)-(x**2)))
return x, np.array(np.sqrt((r**2)-(x**2))), np.array(-np.sqrt((r**2)-(x**2)))
def wrapper(self, args):
return self.fit(*args)
def multi_process(self, data_list):
p = mul.Pool(8)
output = p.map(self.wrapper, data_list)
p.close()
return output
if __name__ == '__main__':
print('start')
start = time.time()
fig = plt.figure()
# mnist dataset
digits = datasets.load_digits()
x_data = digits.data[0:100]
y_d = digits.target[0:100]
labels = (2, 3, 7)
x_list = []
y_list = []
for i, j in zip(x_data, y_d):
if j in labels:
x_list.append(i)
y_list.append(j)
x_data = umap.UMAP(n_neighbors=20,
n_components=10,
min_dist=0.01,
metric='correlation').fit_transform(x_list, y=y_list)
parameters = []
sc = StandardScaler()
sc.fit(x_data)
x_data = sc.transform(x_data)
# labels = random.sample(range(10), k=3)
x_train, x_test, y_train, y_test = train_test_split(x_data,
y_list,
test_size=0.1,
shuffle=False)
dim = len(x_data[0])
theta_list = []
test = QVC(dim, dim, ["0"*dim, "1"*dim], 16384, 1, dim, max(y_d))
parameter = test.fit(x_train, y_train, labels)
# theta_list.append(parameter)
# print("theta", theta_list)
count = 1
answers = []
print("param!",parameter)
for i in x_test:
prob_all = []
print("="*25, "test", count, "="*25)
label = test.predict(i, parameter, labels)
answers.append(label)
count += 1
acc = test.calc_accuracy(answers, y_test)
Notify.notify(acc)
print(acc)
print(answers)
print(y_test)
print(parameters)
# df = pd.DataFrame([[acc], [parameters]])
# print(df)
df.to_csv('./data/%sn%s.csv' % ('237', str(sys.argv[1])))
print(time.time() - start)
|
https://github.com/jakelishman/qiskit-qasm2
|
jakelishman
|
# 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
import itertools
import math
import sys
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestSimple(QiskitTestCase):
def test_unary_constants(self):
program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
self.assertEqual(list(parsed.data[0].operation.params), expected)
def test_unary_symbolic(self):
program = """
gate u(a, b, c) q {
U(-(a + a), +(+b - c), -+-+c) q;
}
qreg q[1];
u(0.5, 1.0, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
expected = [-1.0, -1.0, 2.0]
actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_constants(self, str_op, py_op):
program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("+", lambda a, b: a + b),
("-", lambda a, b: a - b),
("*", lambda a, b: a * b),
("/", lambda a, b: a / b),
("^", lambda a, b: a**b),
)
@ddt.unpack
def test_binary_symbolic(self, str_op, py_op):
program = f"""
gate u(a, b, c) q {{
U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q;
}}
qreg q[1];
u(1.0, 2.0, 3.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [1.0, 2.0, 3.0]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_constants(self, function_str, function_py):
program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];"
parsed = qiskit.qasm2.loads(program)
expected = [function_py(0.5), function_py(1.0), function_py(math.pi)]
# These should be bit-for-bit exact.
self.assertEqual(list(parsed.data[0].operation.params), expected)
@ddt.data(
("cos", math.cos),
("exp", math.exp),
("ln", math.log),
("sin", math.sin),
("sqrt", math.sqrt),
("tan", math.tan),
)
@ddt.unpack
def test_function_symbolic(self, function_str, function_py):
program = f"""
gate u(a, b, c) q {{
U({function_str}(a), {function_str}(b), {function_str}(c)) q;
}}
qreg q[1];
u(0.5, 1.0, pi) q[0];
"""
parsed = qiskit.qasm2.loads(program)
outer = [0.5, 1.0, math.pi]
abstract_op = parsed.data[0].operation
self.assertEqual(list(abstract_op.params), outer)
expected = [function_py(x) for x in outer]
actual = [float(x) for x in abstract_op.definition.data[0].operation.params]
self.assertEqual(list(actual), expected)
class TestPrecedenceAssociativity(QiskitTestCase):
def test_precedence(self):
# OQ3's precedence rules are the same as Python's, so we can effectively just eval.
expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25"
expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25
program = f"qreg q[1]; U({expr}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed.data[0].operation.params[0], expected)
def test_addition_left(self):
# `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if
# addition is correctly parsed and resolved as left-associative, then the first parameter
# should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas
# the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different.
eps = sys.float_info.epsilon
program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test.
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0])
def test_multiplication_left(self):
# A similar principle to the epsilon test for addition; if multiplication associates right,
# then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`.
fmax = sys.float_info.max
program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf])
def test_subtraction_left(self):
# If subtraction associated right, we'd accidentally get 2.
program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0])
def test_division_left(self):
# If division associated right, we'd accidentally get 4.
program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0])
def test_power_right(self):
# If the power operator associated left, we'd accidentally get 64 instead.
program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0])
class TestCustomClassical(QiskitTestCase):
def test_evaluation_order(self):
"""We should be evaluating all functions, including custom user ones the exact number of
times we expect, and left-to-right in parameter lists."""
# pylint: disable=invalid-name
order = itertools.count()
def f():
return next(order)
program = """
qreg q[1];
U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 0, f),
qiskit.qasm2.CustomClassical("atan2", 2, math.atan2),
],
)
self.assertEqual(
list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5]
)
self.assertEqual(next(order), 6)
@ddt.ddt
class TestErrors(QiskitTestCase):
@ddt.data("0.0", "(1.0 - 1.0)")
def test_refuses_to_divide_by_zero(self, denom):
program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"):
qiskit.qasm2.loads(program)
@ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0")
def test_refuses_to_ln_non_positive(self, operand):
program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"):
qiskit.qasm2.loads(program)
@ddt.data("-2.0", "2.0 - 3.0")
def test_refuses_to_sqrt_negative(self, operand):
program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"):
qiskit.qasm2.loads(program)
@ddt.data("*", "/", "^")
def test_cannot_use_nonunary_operators_in_unary_position(self, operator):
program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"):
qiskit.qasm2.loads(program)
@ddt.data("+", "-", "*", "/", "^")
def test_missing_binary_operand_errors(self, operator):
program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"):
qiskit.qasm2.loads(program)
def test_parenthesis_must_be_closed(self):
program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"):
qiskit.qasm2.loads(program)
def test_premature_right_parenthesis(self):
program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"):
qiskit.qasm2.loads(program)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
import os
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
# PROGRAM_PREFIX = 'qiskit-test'
def main():
provider = DellRuntimeProvider()
here = os.path.dirname(os.path.realpath(__file__))
program_id = provider.runtime.upload_program(here + "/dirtest", metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
job.result(timeout=120)
if __name__ == "__main__":
main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# 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.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-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")
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
# QREM
shots = 1 << 13
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')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for the pulse schedule block."""
import re
import unittest
from typing import List, Any
from qiskit import pulse, circuit
from qiskit.pulse import transforms
from qiskit.pulse.exceptions import PulseError
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeArmonk
from qiskit.utils import has_aer
class BaseTestBlock(QiskitTestCase):
"""ScheduleBlock tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.test_waveform0 = pulse.Constant(100, 0.1)
self.test_waveform1 = pulse.Constant(200, 0.1)
self.d0 = pulse.DriveChannel(0)
self.d1 = pulse.DriveChannel(1)
self.left_context = transforms.AlignLeft()
self.right_context = transforms.AlignRight()
self.sequential_context = transforms.AlignSequential()
self.equispaced_context = transforms.AlignEquispaced(duration=1000)
def _align_func(j):
return {1: 0.1, 2: 0.25, 3: 0.7, 4: 0.85}.get(j)
self.func_context = transforms.AlignFunc(duration=1000, func=_align_func)
def assertScheduleEqual(self, target, reference):
"""Check if two block are equal schedule representation."""
self.assertEqual(transforms.target_qobj_transform(target), reference)
class TestTransformation(BaseTestBlock):
"""Test conversion of ScheduleBlock to Schedule."""
def test_left_alignment(self):
"""Test left alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.left_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_right_alignment(self):
"""Test right alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.right_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_sequential_alignment(self):
"""Test sequential alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block = block.append(pulse.Play(self.test_waveform0, self.d0))
block = block.append(pulse.Play(self.test_waveform1, self.d1))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d1))
self.assertScheduleEqual(block, ref_sched)
def test_equispace_alignment(self):
"""Test equispace alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(300, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(600, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(900, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_func_alignment(self):
"""Test func alignment context."""
block = pulse.ScheduleBlock(alignment_context=self.func_context)
for _ in range(4):
block = block.append(pulse.Play(self.test_waveform0, self.d0))
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(50, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(650, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(800, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_nested_alignment(self):
"""Test nested block scheduling."""
block_sub = pulse.ScheduleBlock(alignment_context=self.right_context)
block_sub = block_sub.append(pulse.Play(self.test_waveform0, self.d0))
block_sub = block_sub.append(pulse.Play(self.test_waveform1, self.d1))
block_main = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block_main = block_main.append(block_sub)
block_main = block_main.append(pulse.Delay(10, self.d0))
block_main = block_main.append(block_sub)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(200, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(210, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(310, pulse.Play(self.test_waveform0, self.d0))
self.assertScheduleEqual(block_main, ref_sched)
class TestBlockOperation(BaseTestBlock):
"""Test fundamental operation on schedule block.
Because ScheduleBlock adapts to the lazy scheduling, no uniitest for
overlap constraints is necessary. Test scheme becomes simpler than the schedule.
Some tests have dependency on schedule conversion.
This operation should be tested in `test.python.pulse.test_block.TestTransformation`.
"""
def setUp(self):
super().setUp()
self.test_blocks = [
pulse.Play(self.test_waveform0, self.d0),
pulse.Play(self.test_waveform1, self.d1),
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform1, self.d0),
]
def test_append_an_instruction_to_empty_block(self):
"""Test append instructions to an empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Play(self.test_waveform0, self.d0))
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_sugar(self):
"""Test append instructions to an empty block with syntax sugar."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_an_instruction_to_empty_block_inplace(self):
"""Test append instructions to an empty block with inplace."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0))
def test_append_a_block_to_empty_block(self):
"""Test append another ScheduleBlock to empty block."""
block = pulse.ScheduleBlock()
block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True)
block_main = pulse.ScheduleBlock()
block_main = block_main.append(block)
self.assertEqual(block_main.blocks[0], block)
def test_append_an_instruction_to_block(self):
"""Test append instructions to a non-empty block."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block = block.append(pulse.Delay(100, self.d0))
self.assertEqual(len(block.blocks), 2)
def test_append_an_instruction_to_block_inplace(self):
"""Test append instructions to a non-empty block with inplace."""
block = pulse.ScheduleBlock()
block = block.append(pulse.Delay(100, self.d0))
block.append(pulse.Delay(100, self.d0), inplace=True)
self.assertEqual(len(block.blocks), 2)
def test_duration(self):
"""Test if correct duration is returned with implicit scheduling."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.duration, 350)
def test_channels(self):
"""Test if all channels are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(len(block.channels), 2)
def test_instructions(self):
"""Test if all instructions are returned."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.blocks, tuple(self.test_blocks))
def test_channel_duraction(self):
"""Test if correct durations is calculated for each channel."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
self.assertEqual(block.ch_duration(self.d0), 350)
self.assertEqual(block.ch_duration(self.d1), 200)
def test_cannot_append_schedule(self):
"""Test schedule cannot be appended. Schedule should be input as Call instruction."""
block = pulse.ScheduleBlock()
sched = pulse.Schedule()
sched += pulse.Delay(10, self.d0)
with self.assertRaises(PulseError):
block.append(sched)
def test_replace(self):
"""Test replacing specific instruction."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block_replaced = block.replace(target, replaced, inplace=False)
# original schedule is not destroyed
self.assertListEqual(list(block.blocks), self.test_blocks)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block_replaced, ref_sched)
def test_replace_inplace(self):
"""Test replacing specific instruction with inplace."""
block = pulse.ScheduleBlock()
for inst in self.test_blocks:
block.append(inst)
replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1)
target = pulse.Delay(50, self.d0)
block.replace(target, replaced, inplace=True)
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0))
ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1))
ref_sched = ref_sched.insert(200, replaced)
ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0))
self.assertScheduleEqual(block, ref_sched)
def test_replace_block_by_instruction(self):
"""Test replacing block with instruction."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(sub_block1)
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(sub_block1, pulse.Delay(100, self.d0))
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
pulse.Delay(100, self.d0),
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_replace_instruction_by_block(self):
"""Test replacing instruction with block."""
sub_block1 = pulse.ScheduleBlock()
sub_block1 = sub_block1.append(pulse.Delay(50, self.d0))
sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0))
sub_block2 = pulse.ScheduleBlock()
sub_block2 = sub_block2.append(pulse.Delay(50, self.d0))
sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1))
main_block = pulse.ScheduleBlock()
main_block = main_block.append(pulse.Delay(50, self.d0))
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0))
main_block = main_block.append(pulse.Delay(100, self.d0))
main_block = main_block.append(sub_block2)
main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1))
replaced = main_block.replace(pulse.Delay(100, self.d0), sub_block1)
ref_blocks = [
pulse.Delay(50, self.d0),
pulse.Play(self.test_waveform0, self.d0),
sub_block1,
sub_block2,
pulse.Play(self.test_waveform0, self.d1),
]
self.assertListEqual(list(replaced.blocks), ref_blocks)
def test_len(self):
"""Test __len__ method"""
block = pulse.ScheduleBlock()
self.assertEqual(len(block), 0)
for j in range(1, 10):
block = block.append(pulse.Delay(10, self.d0))
self.assertEqual(len(block), j)
def test_inherit_from(self):
"""Test creating schedule with another schedule."""
ref_metadata = {"test": "value"}
ref_name = "test"
base_sched = pulse.ScheduleBlock(name=ref_name, metadata=ref_metadata)
new_sched = pulse.ScheduleBlock.initialize_from(base_sched)
self.assertEqual(new_sched.name, ref_name)
self.assertDictEqual(new_sched.metadata, ref_metadata)
@unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.")
def test_execute_block(self):
"""Test executing a ScheduleBlock on a Pulse backend"""
with pulse.build(name="test_block") as sched_block:
pulse.play(pulse.Constant(160, 1.0), pulse.DriveChannel(0))
pulse.acquire(50, pulse.AcquireChannel(0), pulse.MemorySlot(0))
backend = FakeArmonk()
# TODO: Rewrite test to simulate with qiskit-dynamics
with self.assertWarns(DeprecationWarning):
test_result = backend.run(sched_block).result()
self.assertDictEqual(test_result.get_counts(), {"0": 1024})
class TestBlockEquality(BaseTestBlock):
"""Test equality of blocks.
Equality of instruction ordering is compared on DAG representation.
This should be tested for each transform.
"""
def test_different_channels(self):
"""Test equality is False if different channels."""
block1 = pulse.ScheduleBlock()
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock()
block2 += pulse.Delay(10, self.d1)
self.assertNotEqual(block1, block2)
def test_different_transform(self):
"""Test equality is False if different transforms."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_different_transform_opts(self):
"""Test equality is False if different transform options."""
context1 = transforms.AlignEquispaced(duration=100)
context2 = transforms.AlignEquispaced(duration=500)
block1 = pulse.ScheduleBlock(alignment_context=context1)
block1 += pulse.Delay(10, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=context2)
block2 += pulse.Delay(10, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_left(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_left(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_right(self):
"""Test equality is True if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertEqual(block1, block2)
def test_instruction_in_order_right(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.right_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.right_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_sequential(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_sequential_more(self):
"""Test equality is False if three blocks have instructions in different order.
This could detect a particular bug as discussed in this thread:
https://github.com/Qiskit/qiskit-terra/pull/8005#discussion_r966191018
"""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_sequential(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_equispaced(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_equispaced(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instruction_out_of_order_func(self):
"""Test equality is False if two blocks have instructions in different order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d1)
block2 += pulse.Play(self.test_waveform0, self.d0)
self.assertNotEqual(block1, block2)
def test_instruction_in_order_func(self):
"""Test equality is True if two blocks have instructions in same order."""
block1 = pulse.ScheduleBlock(alignment_context=self.func_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform0, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.func_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertEqual(block1, block2)
def test_instrution_in_oder_but_different_node(self):
"""Test equality is False if two blocks have different instructions."""
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, self.d0)
block1 += pulse.Play(self.test_waveform1, self.d1)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, self.d1)
self.assertNotEqual(block1, block2)
def test_instruction_out_of_order_complex_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Delay(10, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertEqual(block2_a, block2_b)
def test_instruction_out_of_order_complex_not_equal(self):
"""Test complex schedule equality can be correctly evaluated."""
block1_a = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_a += pulse.Play(self.test_waveform0, self.d0)
block1_a += pulse.Play(self.test_waveform1, self.d1)
block1_a += pulse.Delay(10, self.d0)
block1_b = pulse.ScheduleBlock(alignment_context=self.left_context)
block1_b += pulse.Play(self.test_waveform1, self.d1)
block1_b += pulse.Delay(10, self.d0)
block1_b += pulse.Play(self.test_waveform0, self.d0)
block2_a = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_a += block1_a
block2_a += block1_b
block2_a += block1_a
block2_b = pulse.ScheduleBlock(alignment_context=self.right_context)
block2_b += block1_a
block2_b += block1_a
block2_b += block1_b
self.assertNotEqual(block2_a, block2_b)
class TestParametrizedBlockOperation(BaseTestBlock):
"""Test fundamental operation with parametrization."""
def setUp(self):
super().setUp()
self.amp0 = circuit.Parameter("amp0")
self.amp1 = circuit.Parameter("amp1")
self.dur0 = circuit.Parameter("dur0")
self.dur1 = circuit.Parameter("dur1")
self.test_par_waveform0 = pulse.Constant(self.dur0, self.amp0)
self.test_par_waveform1 = pulse.Constant(self.dur1, self.amp1)
def test_report_parameter_assignment(self):
"""Test duration assignment check."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
# check parameter evaluation mechanism
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
# assign duration
block = block.assign_parameters({self.dur0: 200})
self.assertTrue(block.is_parameterized())
self.assertTrue(block.is_schedulable())
def test_cannot_get_duration_if_not_assigned(self):
"""Test raise error when duration is not assigned."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
with self.assertRaises(PulseError):
# pylint: disable=pointless-statement
block.duration
def test_get_assigend_duration(self):
"""Test duration is correctly evaluated."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
block = block.assign_parameters({self.dur0: 300})
self.assertEqual(block.duration, 400)
def test_nested_parametrized_instructions(self):
"""Test parameters of nested schedule can be assigned."""
test_waveform = pulse.Constant(100, self.amp0)
param_sched = pulse.Schedule(pulse.Play(test_waveform, self.d0))
with self.assertWarns(DeprecationWarning):
call_inst = pulse.instructions.Call(param_sched)
sub_block = pulse.ScheduleBlock()
sub_block += call_inst
block = pulse.ScheduleBlock()
block += sub_block
self.assertTrue(block.is_parameterized())
# assign durations
block = block.assign_parameters({self.amp0: 0.1})
self.assertFalse(block.is_parameterized())
def test_equality_of_parametrized_channels(self):
"""Test check equality of blocks involving parametrized channels."""
par_ch = circuit.Parameter("ch")
block1 = pulse.ScheduleBlock(alignment_context=self.left_context)
block1 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
block1 += pulse.Play(self.test_par_waveform0, self.d0)
block2 = pulse.ScheduleBlock(alignment_context=self.left_context)
block2 += pulse.Play(self.test_par_waveform0, self.d0)
block2 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch))
self.assertEqual(block1, block2)
block1_assigned = block1.assign_parameters({par_ch: 1})
block2_assigned = block2.assign_parameters({par_ch: 1})
self.assertEqual(block1_assigned, block2_assigned)
def test_replace_parametrized_instruction(self):
"""Test parametrized instruction can updated with parameter table."""
block = pulse.ScheduleBlock()
block += pulse.Play(self.test_par_waveform0, self.d0)
block += pulse.Delay(100, self.d0)
block += pulse.Play(self.test_waveform0, self.d0)
replaced = block.replace(
pulse.Play(self.test_par_waveform0, self.d0),
pulse.Play(self.test_par_waveform1, self.d0),
)
self.assertTrue(replaced.is_parameterized())
# check assign parameters
replaced_assigned = replaced.assign_parameters({self.dur1: 100, self.amp1: 0.1})
self.assertFalse(replaced_assigned.is_parameterized())
def test_parametrized_context(self):
"""Test parametrize context parameter."""
duration = circuit.Parameter("dur")
param_context = transforms.AlignEquispaced(duration=duration)
block = pulse.ScheduleBlock(alignment_context=param_context)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
block += pulse.Delay(10, self.d0)
self.assertTrue(block.is_parameterized())
self.assertFalse(block.is_schedulable())
block.assign_parameters({duration: 100}, inplace=True)
self.assertFalse(block.is_parameterized())
self.assertTrue(block.is_schedulable())
ref_sched = pulse.Schedule()
ref_sched = ref_sched.insert(0, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(30, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(60, pulse.Delay(10, self.d0))
ref_sched = ref_sched.insert(90, pulse.Delay(10, self.d0))
self.assertScheduleEqual(block, ref_sched)
class TestBlockFilter(BaseTestBlock):
"""Test ScheduleBlock filtering methods."""
def test_filter_channels(self):
"""Test filtering over channels."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
pulse.play(self.test_waveform1, self.d1)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d0 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform0, self.d0)
pulse.delay(10, self.d0)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d1])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(self.d1 in filtered_blk.channels)
with pulse.build() as ref_blk:
pulse.play(self.test_waveform1, self.d1)
self.assertEqual(filtered_blk, ref_blk)
filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0, self.d1])
self.assertEqual(len(filtered_blk.channels), 2)
for ch in [self.d0, self.d1]:
self.assertTrue(ch in filtered_blk.channels)
self.assertEqual(filtered_blk, blk)
def test_filter_channels_nested_block(self):
"""Test filtering over channels in a nested block."""
with pulse.build() as blk:
with pulse.align_sequential():
pulse.play(self.test_waveform0, self.d0)
pulse.delay(5, self.d0)
with pulse.build(self.backend) as cx_blk:
pulse.cx(0, 1)
pulse.call(cx_blk)
for ch in [self.d0, self.d1, pulse.ControlChannel(0)]:
filtered_blk = self._filter_and_test_consistency(blk, channels=[ch])
self.assertEqual(len(filtered_blk.channels), 1)
self.assertTrue(ch in filtered_blk.channels)
def test_filter_inst_types(self):
"""Test filtering on instruction types."""
with pulse.build() as blk:
pulse.acquire(5, pulse.AcquireChannel(0), pulse.MemorySlot(0))
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1)
pulse.call(blk_internal)
pulse.reference(name="dummy_reference")
pulse.delay(10, self.d0)
pulse.play(self.test_waveform0, self.d0)
pulse.barrier(self.d0, self.d1, pulse.AcquireChannel(0), pulse.MemorySlot(0))
pulse.set_frequency(10, self.d0)
pulse.shift_frequency(5, self.d1)
pulse.set_phase(3.14 / 4.0, self.d0)
pulse.shift_phase(-3.14 / 2.0, self.d1)
pulse.snapshot(label="dummy_snapshot")
# test filtering Acquire
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Acquire])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Acquire)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering Reference
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.Reference]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.Reference)
# test filtering Delay
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Delay])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Delay)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering Play
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Play])
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0].blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
# test filtering RelativeBarrier
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.instructions.RelativeBarrier]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.RelativeBarrier)
self.assertEqual(len(filtered_blk.channels), 4)
# test filtering SetFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.SetFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftFrequency
filtered_blk = self._filter_and_test_consistency(
blk, instruction_types=[pulse.ShiftFrequency]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftFrequency)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SetPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.SetPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.SetPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering ShiftPhase
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.ShiftPhase])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftPhase)
self.assertEqual(len(filtered_blk.channels), 1)
# test filtering SnapShot
filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Snapshot])
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Snapshot)
self.assertEqual(len(filtered_blk.channels), 1)
def test_filter_functionals(self):
"""Test functional filtering."""
with pulse.build() as blk:
pulse.play(self.test_waveform0, self.d0, "play0")
pulse.delay(10, self.d0, "delay0")
with pulse.build() as blk_internal:
pulse.play(self.test_waveform1, self.d1, "play1")
pulse.call(blk_internal)
pulse.play(self.test_waveform1, self.d1)
def filter_with_inst_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.name, str):
match_obj = re.search(pattern="play", string=inst.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(blk, filter_with_inst_name)
self.assertEqual(len(filtered_blk.blocks), 2)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertIsInstance(filtered_blk.blocks[1].blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 2)
def test_filter_multiple(self):
"""Test filter composition."""
with pulse.build() as blk:
pulse.play(pulse.Constant(100, 0.1, name="play0"), self.d0)
pulse.delay(10, self.d0, "delay0")
with pulse.build(name="internal_blk") as blk_internal:
pulse.play(pulse.Constant(50, 0.1, name="play1"), self.d0)
pulse.call(blk_internal)
pulse.barrier(self.d0, self.d1)
pulse.play(pulse.Constant(100, 0.1, name="play2"), self.d1)
def filter_with_pulse_name(inst: pulse.Instruction) -> bool:
try:
if isinstance(inst.pulse.name, str):
match_obj = re.search(pattern="play", string=inst.pulse.name)
if match_obj is not None:
return True
except AttributeError:
pass
return False
filtered_blk = self._filter_and_test_consistency(
blk, filter_with_pulse_name, channels=[self.d1], instruction_types=[pulse.Play]
)
self.assertEqual(len(filtered_blk.blocks), 1)
self.assertIsInstance(filtered_blk.blocks[0], pulse.Play)
self.assertEqual(len(filtered_blk.channels), 1)
def _filter_and_test_consistency(
self, sched_blk: pulse.ScheduleBlock, *args: Any, **kwargs: Any
) -> pulse.ScheduleBlock:
"""
Returns sched_blk.filter(*args, **kwargs),
including a test that sched_blk.filter | sched_blk.exclude == sched_blk
in terms of instructions.
"""
filtered = sched_blk.filter(*args, **kwargs)
excluded = sched_blk.exclude(*args, **kwargs)
def list_instructions(blk: pulse.ScheduleBlock) -> List[pulse.Instruction]:
insts = []
for element in blk.blocks:
if isinstance(element, pulse.ScheduleBlock):
inner_insts = list_instructions(element)
if len(inner_insts) != 0:
insts.extend(inner_insts)
elif isinstance(element, pulse.Instruction):
insts.append(element)
return insts
sum_insts = list_instructions(filtered) + list_instructions(excluded)
ref_insts = list_instructions(sched_blk)
self.assertEqual(len(sum_insts), len(ref_insts))
self.assertTrue(all(inst in ref_insts for inst in sum_insts))
return filtered
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
#import numpy as np
q = QuantumRegister(2)
c = ClassicalRegister(2)
# Define Quantum circuit with 2 quantum register and 2 classical register
bell = QuantumCircuit(q,c)
# Create a Bell state
bell.x(q[0])
bell.x(q[1])
bell.h(q[0])
bell.cx(q[0], q[1])
# Draw circuit
bell.draw(output = 'mpl')
backend_statevector = Aer.get_backend('statevector_simulator')
job = execute(bell, backend_statevector)
result = job.result()
outputstate = result.get_statevector(bell, decimals = 3)
print(outputstate)
#plot_bloch_multivector(job.result().get_statevector(bell))
bell.measure(q, c)
bell.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(bell, backend)
result = job.result()
result.get_counts(bell)
plot_histogram(job.result().get_counts(bell))
import numpy as np
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
def mixed_state(pure_state, visibility):
#density_matrix = pure_state @ pure_state.T.conj()
density_matrix = np.dot( pure_state, np.matrix.getH(pure_state) )
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
#print (array_to_latex(ϕ, pretext="$\phi$ = "))
print(f"Maximum visibility is a pure state: \n{mixed_state(ϕ, 1.0)}\n")
print(f"The state is still entangled with visibility 0.8:\n {mixed_state(ϕ, 0.8)}\n")
print(f"Entanglement is lost by 0.6:\n{mixed_state(ϕ, 0.6)}\n")
print(f"Barely any coherence remains by 0.2:\n{mixed_state(ϕ, 0.2)}\n")
import matplotlib.pyplot as plt
temperatures = [.5, 5, 2000]
energies = np.linspace(0, 20, 100)
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$="+str(T))
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
cq = QuantumRegister(2,'code\_qubit\_')
lq = QuantumRegister(1,'ancilla\_qubit\_')
sb = ClassicalRegister(1,'syndrome\_bit')
qc = QuantumCircuit(cq,lq,sb)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
qc.measure(lq,sb)
qc.draw('mpl')
qc_init = QuantumCircuit(cq)
(qc_init+qc).draw('mpl')
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.x(cq)
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
qc_init.x(cq[0])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
|
https://github.com/FilipeChagasDev/register-by-constant-qft-adder
|
FilipeChagasDev
|
#By Filipe Chagas
#2022
import qiskit
from math import *
from qiskit_quantum_fourier_transform import qft
from numeric_systems import *
def reg_by_const_fourier_basis_adder(n: int, c: int) -> qiskit.circuit.Gate:
"""
Register-by-constant addition gate in Fourier basis.
Get a gate to perform an addition of a constant $c$ to an integer register in Fourier basis.
No ancillary qubits needed.
[see https://doi.org/10.48550/arXiv.2207.05309]
:param n: Number of target qubits.
:type n: int
:param c: Constant to add.
:type c: int
:return: $U_{\phi(+)}(c)$ gate.
:rtype: qiskit.circuit.Gate
"""
assert n > 0
my_circuit = qiskit.QuantumCircuit(n, name=f'$U_{{\\phi(+)}}({c})$')
for i in range(n):
theta = c * (pi / (2**(n-i-1)))
my_circuit.rz(theta, i)
return my_circuit.to_gate()
def reg_by_const_qft_adder(n: int, c: int) -> qiskit.circuit.Gate:
"""
Register-by-constant QFT addition gate.
Get a gate to perform an addition of a constant $c$ to a integer register.
No ancillary qubits needed.
[see https://doi.org/10.48550/arXiv.2207.05309]
:param n: Number of target qubits.
:type n: int
:param c: Constant to add.
:type c: int
:return: $U_{+}(c)$ gate.
:rtype: qiskit.circuit.Gate
"""
assert n > 0
my_circuit = qiskit.QuantumCircuit(n, name=f'$U_{{+}}({c})$')
my_qft = qft(n)
my_circuit.append(my_qft, list(range(n)))
my_circuit.append(reg_by_const_fourier_basis_adder(n, c), list(range(n)))
my_circuit.append(my_qft.inverse(), list(range(n)))
return my_circuit.to_gate()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.circuit.library import RawFeatureVector
from qiskit_machine_learning.neural_networks import SamplerQNN
algorithm_globals.random_seed = 42
def ansatz(num_qubits):
return RealAmplitudes(num_qubits, reps=5)
num_qubits = 5
circ = ansatz(num_qubits)
circ.decompose().draw("mpl")
def auto_encoder_circuit(num_latent, num_trash):
qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True)
circuit.barrier()
auxiliary_qubit = num_latent + 2 * num_trash
# swap test
circuit.h(auxiliary_qubit)
for i in range(num_trash):
circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i)
circuit.h(auxiliary_qubit)
circuit.measure(auxiliary_qubit, cr[0])
return circuit
num_latent = 3
num_trash = 2
circuit = auto_encoder_circuit(num_latent, num_trash)
circuit.draw("mpl")
def domain_wall(circuit, a, b):
# Here we place the Domain Wall to qubits a - b in our circuit
for i in np.arange(int(b / 2), int(b)):
circuit.x(i)
return circuit
domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5)
domain_wall_circuit.draw("mpl")
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
# Here we define our interpret for our SamplerQNN
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=[],
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_domain(params_values):
probabilities = qnn.forward([], params_values)
# we pick a probability of getting 1 as the output of the network
cost = np.sum(probabilities[:, 1])
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
opt = COBYLA(maxiter=150)
initial_point = algorithm_globals.random.random(ae.num_parameters)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(cost_func_domain, initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(domain_wall_circuit)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
test_qc.draw("mpl")
test_qc = test_qc.assign_parameters(opt_result.x)
domain_wall_state = Statevector(domain_wall_circuit).data
output_state = Statevector(test_qc).data
fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2)
print("Fidelity of our Output State with our Input State: ", fidelity.real)
def zero_idx(j, i):
# Index for zero pixels
return [
[i, j],
[i - 1, j - 1],
[i - 1, j + 1],
[i - 2, j - 1],
[i - 2, j + 1],
[i - 3, j - 1],
[i - 3, j + 1],
[i - 4, j - 1],
[i - 4, j + 1],
[i - 5, j],
]
def one_idx(i, j):
# Index for one pixels
return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]]
def get_dataset_digits(num, draw=True):
# Create Dataset containing zero and one
train_images = []
train_labels = []
for i in range(int(num / 2)):
# First we introduce background noise
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the one
for i, j in one_idx(2, 6):
empty[j][i] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(1)
if draw:
plt.title("This is a One")
plt.imshow(train_images[-1])
plt.show()
for i in range(int(num / 2)):
empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape(
8, 4
)
# Now we insert the pixels for the zero
for k, j in zero_idx(2, 6):
empty[k][j] = algorithm_globals.random.uniform(0.9, 1)
train_images.append(empty)
train_labels.append(0)
if draw:
plt.imshow(train_images[-1])
plt.title("This is a Zero")
plt.show()
train_images = np.array(train_images)
train_images = train_images.reshape(len(train_images), 32)
for i in range(len(train_images)):
sum_sq = np.sum(train_images[i] ** 2)
train_images[i] = train_images[i] / np.sqrt(sum_sq)
return train_images, train_labels
train_images, __ = get_dataset_digits(2)
num_latent = 3
num_trash = 2
fm = RawFeatureVector(2 ** (num_latent + num_trash))
ae = auto_encoder_circuit(num_latent, num_trash)
qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1)
qc = qc.compose(fm, range(num_latent + num_trash))
qc = qc.compose(ae)
qc.draw("mpl")
def identity_interpret(x):
return x
qnn = SamplerQNN(
circuit=qc,
input_params=fm.parameters,
weight_params=ae.parameters,
interpret=identity_interpret,
output_shape=2,
)
def cost_func_digits(params_values):
probabilities = qnn.forward(train_images, params_values)
cost = np.sum(probabilities[:, 1]) / train_images.shape[0]
# plotting part
clear_output(wait=True)
objective_func_vals.append(cost)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
return cost
with open("12_qae_initial_point.json", "r") as f:
initial_point = json.load(f)
opt = COBYLA(maxiter=150)
objective_func_vals = []
# make the plot nicer
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point)
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} seconds")
# Test
test_qc = QuantumCircuit(num_latent + num_trash)
test_qc = test_qc.compose(fm)
ansatz_qc = ansatz(num_latent + num_trash)
test_qc = test_qc.compose(ansatz_qc)
test_qc.barrier()
test_qc.reset(4)
test_qc.reset(3)
test_qc.barrier()
test_qc = test_qc.compose(ansatz_qc.inverse())
# sample new images
test_images, test_labels = get_dataset_digits(2, draw=False)
for image, label in zip(test_images, test_labels):
original_qc = fm.assign_parameters(image)
original_sv = Statevector(original_qc).data
original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4))
param_values = np.concatenate((image, opt_result.x))
output_qc = test_qc.assign_parameters(param_values)
output_sv = Statevector(output_qc).data
output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(original_sv)
ax1.set_title("Input Data")
ax2.imshow(output_sv)
ax2.set_title("Output Data")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SLSQP
ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1)
optimizer = SLSQP()
ansatz.decompose().draw('mpl')
from qiskit.primitives import Sampler, Estimator
from qiskit.algorithms.state_fidelities import ComputeUncompute
estimator = Estimator()
sampler = Sampler()
fidelity = ComputeUncompute(sampler)
k = 3
betas = [33, 33, 33]
counts = []
values = []
steps = []
def callback(eval_count, params, value, meta, step):
counts.append(eval_count)
values.append(value)
steps.append(step)
from qiskit.algorithms.eigensolvers import VQD
vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback)
result = vqd.compute_eigenvalues(operator = H2_op)
vqd_values = result.optimal_values
print(vqd_values)
import numpy as np
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
steps = np.asarray(steps)
counts = np.asarray(counts)
values = np.asarray(values)
for i in range(1,4):
_counts = counts[np.where(steps == i)]
_values = values[np.where(steps == i)]
pylab.plot(_counts, _values, label=f"State {i-1}")
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for each computed state")
pylab.legend(loc="upper right");
from qiskit.algorithms.eigensolvers import NumPyEigensolver
from qiskit.opflow import PauliSumOp
exact_solver = NumPyEigensolver(k=3)
exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op))
ref_values = exact_result.eigenvalues
print(f"Reference values: {ref_values}")
print(f"VQD values: {vqd_values}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import datetime
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.rcParams.update({"text.usetex": True})
plt.rcParams["figure.figsize"] = (6,4)
mpl.rcParams["figure.dpi"] = 200
from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
service = QiskitRuntimeService()
backend_simulator = "backend_simulator"
backend = "ibmq_montreal"
qubits = 4
trotter_layer = QuantumCircuit(qubits)
trotter_layer.rx(0.1, range(qubits))
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.rz(-0.2, [1, 3])
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.cx(1, 2)
trotter_layer.rz(-0.2, 2)
trotter_layer.cx(1, 2)
num_steps = 6
trotter_circuit_list = []
for i in range(1, num_steps):
trotter_circuit = QuantumCircuit(qubits)
for _ in range(i):
trotter_circuit = trotter_circuit.compose(trotter_layer)
trotter_circuit_list.append(trotter_circuit)
print(f'Trotter circuit with {i} Trotter steps`)
display(trotter_circuit.draw(fold=-1))
obs = SparsePauliOp("Z"*qubits)
obs_list = [obs]*len(trotter_circuit_list)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No mitigation
with Session(service=service, backend=backend_simulator) as session:
estimator_sim = Estimator(session=session, options=options)
job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_sim.job_id)
print(job_sim.result())
expvals_ideal = job_sim.result().values
expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata]
std_error_ideal = np.sqrt(expvals_ideal_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job.job_id)
print(job.result())
expvals_unmit = job.result().values
expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata]
std_error_unmit = np.sqrt(expvals_unmit_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 3 # Dynamical decoupling
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_dd.job_id)
print(job_dd.result())
expvals_unmit_dd = job_dd.result().values
expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata]
std_error_dd = np.sqrt(expvals_unmit_dd_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.resilience_level = 1 # T-REx
options.optimization_level = 0 # No optimization
options.execution.shots = 1000
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_trex.job_id)
print(job_trex.result())
expvals_unmit_trex = job_trex.result().values
expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata]
std_error_trex = np.sqrt(expvals_unmit_trex_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 2 # ZNE
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne.job_id)
print(job_zne.result())
expvals_unmit_zne = job_zne.result().values
# Standard error: coming soon!
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.xlabel('No. Trotter Steps')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
def interim_results_callback(job_id, result):
now = datetime.datetime.now()
print(now, "*** Callback ***", result, "\n")
options = Options()
options.optimization_level = 0 # No optimization
options.execution.shots = 100
options.resilience_level = 3 # PEC
options.environment.callback = interim_results_callback
with Session(service=service, backend=backend) as session:
estimator_pec = Estimator(session=session, options=options)
job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_pec.job_id)
expvals_pec = job_pec.result().values
std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata]
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
print(job_pec.result())
pec_metadata = job_pec.result().metadata
fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)
twin1 = ax.twinx()
twin2 = ax.twinx()
twin3 = ax.twinx()
twin2.spines.right.set_position(("axes", 1.2))
twin3.spines.right.set_position(("axes", 1.4))
p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers")
p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead")
p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples")
p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots")
ax.set_ylim(0, 20)
twin1.set_ylim(0, 2.8)
twin2.set_ylim(0, 300)
twin3.set_ylim(0, 35000)
ax.set_xlabel("No. Trotter Steps")
ax.set_ylabel("Total mitigated layers")
twin1.set_ylabel("Sampling overhead")
twin2.set_ylabel("Samples")
twin3.set_ylabel("Shots")
ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())
twin3.yaxis.label.set_color(p4.get_color())
tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
twin3.tick_params(axis='y', colors=p4.get_color(), **tkw)
plt.xticks([1, 2, 3, 4, 5])
ax.legend(handles=[p1, p2, p3, p4])
plt.title('PEC metadata')
plt.show()
from matplotlib.pyplot import figure
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.title('Trotter circuits expectation value')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # no optimization
options.resilience_level = 2 # ZNE
options.resilience.noise_factors = [1, 2, 3, 4]
options.resilience.noise_amplifier = "LocalFoldingAmplifier"
options.resilience.extrapolator = "QuadraticExtrapolator"
with Session(service=service, backend='ibmq_montreal') as session:
estimator = Estimator(session=session, options=options)
job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne_options.job_id)
print(job_zne_options.result())
from qiskit.tools import jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import ParityMapper
from qiskit_nature.second_q.properties import ParticleNumber
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
bond_distance = 2.5 # in Angstrom
# specify driver
driver = PySCFDriver(
atom=f"Li 0 0 0; H 0 0 {bond_distance}",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
# specify active space transformation
active_space_trafo = ActiveSpaceTransformer(
num_electrons=problem.num_particles, num_spatial_orbitals=3
)
# transform the electronic structure problem
problem = active_space_trafo.transform(problem)
# construct the parity mapper with 2-qubit reduction
qubit_mapper = ParityMapper(num_particles=problem.num_particles)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver
np_solver = NumPyMinimumEigensolver()
np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver)
np_result = np_groundstate_solver.solve(problem)
target_energy = np_result.total_energies[0]
print(np_result)
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True)
ansatz.decompose().draw("mpl", style="iqx")
import numpy as np
from qiskit.utils import algorithm_globals
# fix random seeds for reproducibility
np.random.seed(5)
algorithm_globals.random_seed = 5
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(maxiter=100)
initial_point = np.random.random(ansatz.num_parameters)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.primitives import Estimator
estimator = Estimator()
local_vqe = VQE(
estimator,
ansatz,
optimizer,
initial_point=initial_point,
)
local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe)
local_vqe_result = local_vqe_groundstate_solver.solve(problem)
print(local_vqe_result)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(group="open") # replace by your runtime provider
backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime
from qiskit_nature.runtime import VQEClient
runtime_vqe = VQEClient(
ansatz=ansatz,
optimizer=optimizer,
initial_point=initial_point,
provider=provider,
backend=backend,
shots=1024,
measurement_error_mitigation=True,
) # use a complete measurement fitter for error mitigation
runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe)
runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem)
print(runtime_vqe_result)
runtime_result = runtime_vqe_result.raw_result
history = runtime_result.optimizer_history
loss = history["energy"]
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# plot loss and reference value
plt.figure(figsize=(12, 6))
plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE")
plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH")
plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy");
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
#from IPython import display
#Import Qiskit classes
import qiskit
from qiskit.tools.monitor import job_monitor
from qiskit import Aer
from qiskit.providers.aer.noise import NoiseModel
from qiskit import QuantumRegister, QuantumCircuit
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
# import the bayesian packages
import pymc3 as pm
import arviz as az
from scipy.optimize import curve_fit
import bayesian_fitter as bf
# initialize the Bayesian extension
%config InlineBackend.figure_format = 'retina'
# Initialize random number generator
RANDOM_SEED = 8927
np.random.seed(RANDOM_SEED)
az.style.use("arviz-darkgrid")
RB_process = "2_Q RB"
if RB_process in ["3_Q RB","2-3_Q RB"] :
#Number of qubits
nQ = 3
#There are 3 qubits: Q0,Q1,Q2.
#2Q RB on Q0,Q2 and 1Q RB on Q1
rb_pattern = [[0,1],[2]] # because 3 qubits
#Do three times as many 1Q Cliffords
length_multiplier = [1,3]
#Interleaved Clifford gates (2-qubits and 1-qubit)
interleaved_gates = [['cx 0 1'],['x 2']]
else:
#Number of qubits
nQ = 2
#There are 2 qubits: Q0,Q1.
#2Q RB Q0,Q1
rb_pattern = [[0,1]]
length_multiplier = 1
interleaved_gates = [['cx 0 1']]
#Number of Cliffords in the sequence (start, stop, steps)
nCliffs = [1, 20, 40, 60, 80, 100, 150, 200, 250, 300]
#Number of seeds (random sequences)
nseeds=8
scale = (2 ** len(rb_pattern[0]) - 1) / (2 ** len(rb_pattern[0]))
qregs_02 = QuantumRegister(2)
circ_02 = QuantumCircuit(qregs_02, name='circ_02')
#circ_02.h(qregs_02[0]) # booptrap! WIP!
circ_02.cx(qregs_02[0], qregs_02[1])
circ_02.draw()
qregs_1 = QuantumRegister(1)
circ_1 = QuantumCircuit(qregs_1, name='circ_1')
circ_1.x(qregs_1[0]) # booptrap! WIP!
circ_1.draw()
rb_opts = {}
rb_opts['rand_seed'] = 61946
rb_opts['length_vector'] = nCliffs
rb_opts['nseeds'] = nseeds
rb_opts['rb_pattern'] = rb_pattern
rb_opts['length_multiplier'] = length_multiplier
#rb_opts['align_cliffs'] = True
if RB_process in ["3_Q RB","2-3_Q RB"]:
rb_opts['interleaved_elem'] = [circ_02, circ_1]
if RB_process == "2_Q RB":
rb_opts['interleaved_elem'] = [circ_02]
rb_original_circs, xdata, rb_interleaved_circs = rb.randomized_benchmarking_seq(**rb_opts)
#Original RB circuits
print (rb_original_circs[0][0])
#Interleaved RB circuits
print (rb_interleaved_circs[0][0])
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
device = provider.get_backend('ibmq_lima')
properties = device.properties()
coupling_map = device.configuration().coupling_map
backend = device
hardware = device.name()
shots = 2**9
basis_gates = ['id', 'rz', 'sx', 'x', 'cx', 'reset']
noise_model = None
epc_calib = 6.401E-3 # as noted at experiment time
retrieve_list = []
original_result_list, original_transpile_list = bf.get_and_run_seeds(rb_circs=rb_original_circs,
shots=shots,
backend = backend,
coupling_map = coupling_map,
basis_gates = basis_gates,
noise_model = noise_model,
retrieve_list=retrieve_list)
retrieve_list = []
interleaved_result_list, interleaved_transpile_list = bf.get_and_run_seeds(rb_circs=rb_interleaved_circs,
shots=shots,
backend = backend,
coupling_map = coupling_map,
basis_gates = basis_gates,
noise_model = noise_model,
retrieve_list=retrieve_list)
Y1 = bf.get_count_data(original_result_list, nCliffs=nCliffs )
Y2 = bf.get_count_data(interleaved_result_list, nCliffs=nCliffs)
# function to optimize
def lsf(x, a, alpha, b):
return a * alpha ** x + b
# curve fit
popt_s,pcov_s = curve_fit(lsf, np.array(nseeds*list(nCliffs)),
np.ravel(Y1)/shots,
bounds = ([.65,.9,0.15],[.85,.999,0.35]))
perr_s= np.sqrt(np.diag(pcov_s))
# get EPC and EPC sigma for LSF accelerated
alpha_f = popt_s[1]
alpha_f_err = perr_s[1]
popt_s,perr_s
# curve fit
popt_i,pcov_i = curve_fit(lsf, np.array(nseeds*list(nCliffs)),
np.ravel(Y2)/shots,
bounds = ([.65,.9,0.15],[.85,.999,0.35]))
perr_i= np.sqrt(np.diag(pcov_i))
# get EPC and EPC sigma for LSF accelerated
alphC_f = popt_i[1]
alphC_f_err = perr_i[1]
popt_i,perr_i
epc_est_f = scale*(1 - alphC_f/alpha_f)
epc_est_f_err = scale*(alphC_f/alpha_f)*(np.sqrt(alpha_f_err**2 + alphC_f_err**2))
# function to optimize
def lsmf(x, a, alpha, p_tilde_m, b):
return x[1]*(a * alpha ** x[0] + b) + x[2]*(a * (alpha*p_tilde_m) ** x[0] + b)
# obtain the data
m_len = len(nCliffs)*nseeds
x0_lsmf = np.array(nseeds*2*list(nCliffs))
x1_lsmf = np.hstack((np.ones(m_len),np.zeros(m_len)))
x2_lsmf = np.hstack((np.zeros(m_len),np.ones(m_len)))
x_lsmf = np.vstack((x0_lsmf,x1_lsmf,x2_lsmf))
y_lsmf=np.hstack((np.ravel(Y1),np.ravel(Y2)))/shots
# curve fit
popt_m,pcov_m = curve_fit(lsmf, x_lsmf, y_lsmf,
bounds = ([.65,.9,.9,0.15],
[.85,.999,.999,0.35]))
perr_m = np.sqrt(np.diag(pcov_m))
# get EPC and EPC sigma for LSF accelerated
alpha_fm = popt_m[1]
p_tilde_m = popt_m[2]
alpha_fm_err = perr_m[1]
p_tilde_m_err = perr_m[2]
popt_m,perr_m
epc_est_fm = scale*(1 - p_tilde_m)
epc_est_fm_err = scale*p_tilde_m_err
original_model = bf.get_bayesian_model(model_type="pooled",Y=Y1,shots=shots,m_gates=nCliffs,
mu_AB=[popt_s[0],popt_s[2]],cov_AB=[perr_s[0],perr_s[2]],
alpha_ref=alpha_f)
pm.model_to_graphviz(original_model)
trace_o = bf.get_trace(original_model)
azo_summary = bf.get_summary(original_model, trace_o)
azo_summary
alpha_original_p = azo_summary['mean']['alpha']
alpha_original_p_err = azo_summary['sd']['alpha']
interleaved_model = bf.get_bayesian_model(model_type="pooled",Y=Y2,shots=shots,m_gates=nCliffs,
mu_AB=[popt_i[0],popt_i[2]],cov_AB=[perr_i[0],perr_i[2]],
alpha_ref=alphC_f)
pm.model_to_graphviz(interleaved_model)
trace_i = bf.get_trace(interleaved_model)
azi_summary = bf.get_summary(interleaved_model, trace_i)
azi_summary
alpha_c_p = azi_summary['mean']['alpha']
alpha_c_p_err = azi_summary['sd']['alpha']
epc_est_p = scale*(1 - alpha_c_p/alpha_original_p)
epc_est_p_err = scale*(alpha_c_p/alpha_original_p)*(np.sqrt(alpha_original_p_err**2 + alpha_c_p_err**2))
Y = np.vstack((Y1,Y2))
RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2)))
IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2)))
tilde =bf.get_bayesian_model("tilde",Y=Y,shots=shots, m_gates=nCliffs,
alpha_ref=alpha_fm, p_testval= p_tilde_m,
mu_AB=[popt_m[0],popt_m[3]],cov_AB=[perr_m[0],perr_m[3]],
RvsI=RvsI,IvsR=IvsR)
pm.model_to_graphviz(tilde)
trace_t = bf.get_trace(tilde)
azt_summary = bf.get_summary(tilde, trace_t)
azt_summary
epc_est_a = scale*(1 - azt_summary['mean']['p_tilde'])
epc_est_a_err = scale* (azt_summary['sd']['p_tilde'])
# compare LSF and SMC
print("Model: Frequentist Bayesian Calibration")
print(" two-run accelerated two-run accelerated ")
print("EPC {0:.5f} {1:.5f} {2:.5f} {3:.5f} {4:.5f} "
.format(epc_est_f, epc_est_fm, epc_est_p, epc_est_a, epc_calib))
print("± sigma ± {0:.5f} ± {1:.5f} ± {2:.5f} ± {3:.5f} ------ "
.format(epc_est_f_err, epc_est_fm_err, epc_est_p_err, epc_est_a_err))
# obtain EPC from alpha (used by plot_posterior)
def alpha_to_EPC(alpha):
return scale*(1-alpha)
# for refering the interleaved gate in the title of the graphs
intl_g=str(interleaved_gates[0][0][0:2])+str(rb_pattern[0][0:2])
if RB_process in ["3_Q RB","2-3_Q RB"] :
intl_g=intl_g+"<"+str(interleaved_gates[1][0][0:1]+str(rb_pattern[1][0:2]))
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
with tilde:
ax = az.plot_posterior(trace_t, var_names=['p_tilde'], round_to=4, point_estimate=None,
transform = alpha_to_EPC)
ax.set_xlim(0.0, 0.010)
plt.axvline(x=epc_est_fm,color='red',ls=":")
plt.axvline(x=epc_est_p,color='orange',ls="-")
plt.axvline(x=epc_est_f,color='cyan',ls="-")
if epc_calib > 0.0:
plt.axvline(x=epc_calib,color='green',ls=":")
plt.axvline(x=epc_est_a,color='blue',ls=":")
plt.title(RB_process +' $accelerated$, gate: ' + intl_g\
+", "+hardware+', backend: '+backend.name(),
fontsize=12)
Bayes_legend = "EPC Accelerated SMC: {0:1.3e} ({1:1.3e})".format(epc_est_a, epc_est_a_err)
Bayes2_legend = "EPC SMC 2-runs: {0:1.3e} ({1:1.3e})".format(epc_est_p, epc_est_p_err)
Fitter_legend = "EPC LSF 2-runs: {0:1.3e} ({1:1.3e})".format(epc_est_f, epc_est_f_err)
LSM_legend = "EPC Accelerated LSF: {0:1.3e} ({1:1.3e})".format(epc_est_fm, epc_est_fm_err)
Cal_legend = "EPC Calibration: {0:1.3e}".format(epc_calib)
if epc_calib > 0.0:
plt.legend((Bayes_legend, "$Higher\; density\; interval$ HDI",
LSM_legend,Bayes2_legend,
Fitter_legend,Cal_legend), fontsize=10 )
else:
plt.legend((Bayes_legend, "$Higher\; density\; interval$ HDI",
LSM_legend, Bayes2_legend,
Fitter_legend), fontsize=10 )
import matplotlib.pyplot as plt # seems we need to reimport for replot WIP
fig, plt = plt.subplots(1, 1)
plt.set_ylabel("Ground State Population")
plt.set_xlabel("Number of Cliffords")
for i_seed in range(nseeds):
plt.scatter(nCliffs, Y1[i_seed,:]/shots, label = "data", marker="x",color="b")
plt.scatter(nCliffs, Y2[i_seed,:]/shots, label = "data", marker="+",color="r")
plt.plot(nCliffs,azt_summary['mean']['AB[0]']*azt_summary['mean']['alpha']**nCliffs+\
azt_summary['mean']['AB[1]'],'--',color="b")
plt.plot(nCliffs,azt_summary['mean']['AB[0]']*(azt_summary['mean']['alpha']*azt_summary['mean']['p_tilde'])**\
nCliffs+azt_summary['mean']['AB[1]'],'--',color="r")
plt.legend(("Standard",
"Interleaved"))
plt.set_title(RB_process +' SMC $accelerated$, gate: ' + intl_g\
+", "+hardware+', backend: '+backend.name(),
fontsize=14);
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
CompleteMeasFitter, MeasurementFilter)
|
https://github.com/AlphaMiyaL/Qiskit-Quantum-Journey
|
AlphaMiyaL
|
#Extending Grover's Algorithm to cover the Satisfiability Problem
#Satifiability Problem Ex
#Ordering food
# Satisfiability Constraints
# Open, Nearby, Deliver, Thai Food
#For a reasonable # of resturants, classical comp is fine
#However for big datasets, we can use a quantum speedup
#recast problem into search problem
#Grover's Dinner Party
#Invite as many friends over as possible while everyone gets along
#Grover's search can be used for boolean satisfiability problems
#((Olivia & Abe) | (Jin & Amira)) & ~(Abe & Amira)
#((A & B) | (C & D)) & ~(A & D)
from qiskit import BasicAer
#Deprecation of Aqua
#from qiskit.aqua.algorithms import Grover
#from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.circuit.library import PhaseOracle
from qiskit.algorithms import Grover, AmplificationProblem
from qiskit.utils import QuantumInstance
from qiskit.tools.visualization import plot_histogram
log_expr = '((Olivia & Abe) | (Jin & Amira)) & ~(Abe & Amira)'
oracle = PhaseOracle(log_expr)
problem = AmplificationProblem(oracle=oracle)
backend = BasicAer.get_backend('qasm_simulator')
qinstance = QuantumInstance(backend, shots = 1000)
grover = Grover(quantum_instance = qinstance)
#algorithm = Grover(oracle)
result = grover.amplify(problem)
print('Top measurement:', result.top_measurement)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from qiskit import QuantumCircuit
from qc_grader.grade import grade_circuit, grade_number, submit_circuit, submit_number
criteria: dict = {
'max_qubits': 28,
'min_cost': 30
}
def grade_ex1a(circuit: QuantumCircuit) -> None:
if grade_circuit(circuit, 'week1', 'exA', **criteria):
print('Feel free to submit your answer.')
def submit_ex1a(circuit: QuantumCircuit) -> None:
submit_circuit(circuit, 'week1', 'exA', **criteria)
def grade_ex1b(answer: int) -> None:
if grade_number(answer, 'week1', 'exB'):
print('Feel free to submit your answer.')
def submit_ex1b(answer: int) -> None:
if submit_number(answer, 'week1', 'exB'):
print('Have you ever wonder about the quantum realm? Ask Dr. Ryoko about it.')
|
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/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 demonstrate conditional gate execution.
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.providers.basic_provider import BasicProvider
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/')
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="conditional")
qc.h(q[0])
qc.h(q[1]).c_if(c0, 0) # h-gate on q[1] is executed
qc.h(q[2]).c_if(c1, 1) # h-gate on q[2] is not executed
qc.measure(q[0], c0)
qc.measure(q[1], c1)
qc.measure(q[2], c2)
qc = transpile(qc, backend=qi_backend)
qi_job = qi_backend.run(qc, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicProvider().get_backend(name="basic_simulator") # qasm_simulator
qc = transpile(qc, backend=backend)
job = backend.run(qc, shots=1024)
result = job.result()
print(result.get_counts(qc))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
from qiskit.opflow import I, X, Y, Z, MatrixEvolution, PauliTrotterEvolution
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
from qiskit import Aer
from qiskit.compiler import transpile
import qc_grader
# Define which will contain the Paulis
pauli_list = []
# Define Paulis and add them to the list
###INSERT CODE BELOW THIS LINE
pauli_list = [X, Y, Z, I]
###DO NOT EDIT BELOW THIS LINE
for pauli in pauli_list:
print(pauli, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex1
grade_lab2_ex1(pauli_list)
# Define list of ladder operators
ladder_operator_list = []
# Define ladder operators and add the to the list
###INSERT CODE BELOW THIS LINE
ladder_operator_list = [0.5*(X+(1j*Y)), 0.5*(X-(1j*Y))]
###DO NOT EDIT BELOW THIS LINE
for ladder_operator in ladder_operator_list:
print(ladder_operator, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex2
grade_lab2_ex2(ladder_operator_list)
# Define list which will contain the matrices representing the Pauli operators
matrix_sigma_list = []
# Add matrix representation of Paulis to the list
###INSERT CODE BELOW THIS LINE
matrix_sigma_list = [X.to_matrix(), Y.to_matrix(), Z.to_matrix(), I.to_matrix()]
###DO NOT EDIT BELOW THIS LINE
for matrix_sigma in matrix_sigma_list:
print(matrix_sigma, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex3
grade_lab2_ex3(matrix_sigma_list)
# Define a list which will contain the circuit representation of the Paulis
circuit_sigma_list = []
# Add circuits to list
###INSERT CODE BELOW THIS LINE
circuit_sigma_list = [X.to_circuit(), Y.to_circuit(), Z.to_circuit(), I.to_circuit()]
###DO NOT EDIT BELOW THIS LINE
for circuit in circuit_sigma_list:
print(circuit, '\n')
from qc_grader.challenges.qgss_2022 import grade_lab2_ex4
grade_lab2_ex4(circuit_sigma_list)
# Define a variable theta to be a parameter with name 'theta'
theta = Parameter('theta')
# Set number of qubits to 1
qubits_count = 1
# Initialize a quantum circuit with one qubit
quantum_circuit = QuantumCircuit(qubits_count)
# Add a parametrized RX rotation on the qubit
###INSERT CODE BELOW THIS LINE
quantum_circuit.rx(theta, 0)
###DO NOT EDIT BELOW THIS LINE
print(quantum_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex5
grade_lab2_ex5(quantum_circuit)
# Set the value of the parameter
theta_value = np.pi
# Bind the value to the parametrized circuit
###INSERT CODE BELOW THIS LINE
quantum_circuit = quantum_circuit.bind_parameters({theta: theta_value})
###DO NOT EDIT BELOW THIS LINE
print(quantum_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex6
grade_lab2_ex6(quantum_circuit)
# Use the formula above to define the Hamiltonian operator
###INSERT CODE BELOW THIS LINE
H = 0.5*((I^I)+(X^X)+(Y^Y)+(Z^Z))
###DO NOT EDIT BELOW THIS LINE
# Get its matrix representation
H_matrix = H.to_matrix()
print(H_matrix)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex7
grade_lab2_ex7(H_matrix)
# Define a parameter t for the time in the time evolution operator
t = Parameter('t')
# Follow the instructions above to define a time-evolution operator
###INSERT CODE BELOW THIS LINE
time_evolution_operator = (H*t).exp_i()
###DO NOT EDIT BELOW THIS LINE
print(time_evolution_operator)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex8
grade_lab2_ex8(time_evolution_operator)
# Set a total time for the time evolution
evolution_time = 0.5
# Instantiate a MatrixEvolution() object to convert the time evolution operator
# and bind the value for the time parameter
###INSERT CODE BELOW THIS LINE
matrix_evol = MatrixEvolution()
bound_matrix_exponentiation_circuit = matrix_evol.convert(time_evolution_operator)
bound_matrix_exponentiation_circuit = bound_matrix_exponentiation_circuit.bind_parameters({t:evolution_time})
###DO NOT EDIT BELOW THIS LINE
print(bound_matrix_exponentiation_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex9
grade_lab2_ex9(bound_matrix_exponentiation_circuit)
# Define a value for the duration of the time-step
time_step_value = 0.1
# Instantiate a PauliTrotterEvolution() object and convert the time-evolution operator
# to then bind the value of the time step
###INSERT CODE BELOW THIS LINE
pauli_t_evol = PauliTrotterEvolution()
bound_trotter_exponentiation_circuit = pauli_t_evol.convert(time_evolution_operator)
bound_trotter_exponentiation_circuit = bound_trotter_exponentiation_circuit.bind_parameters({
t: time_step_value
})
###DO NOT EDIT BELOW THIS LINE
print(bound_trotter_exponentiation_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex10
grade_lab2_ex10(bound_trotter_exponentiation_circuit)
# Define the number of steps needed to reach the previously set total time-evolution
steps = int(evolution_time/time_step_value)
# Compose the operator for a Trotter step several times to generate the
# operator for the full time-evolution
###INSERT CODE BELOW THIS LINE
total_time_evolution_circuit = bound_trotter_exponentiation_circuit
for i in range(1, steps):
total_time_evolution_circuit = total_time_evolution_circuit @ bound_trotter_exponentiation_circuit
###DO NOT EDIT BELOW THIS LINE
print(total_time_evolution_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex11
grade_lab2_ex11(total_time_evolution_circuit)
# Set number of qubits
num_qubits = 3
# Define time parameter
t = Parameter('t')
# Set total evolution time
evolution_time_t = 2
# Set size of time-step for Trotter evolution
time_step_value_t = 0.1
# Define the number of steps
steps_t = int(evolution_time_t/time_step_value_t)
# Create circuit
tight_binding_circuit = QuantumCircuit(num_qubits)
# Add initial state preparation
tight_binding_circuit.x(0)
# Define the Hamiltonian, the time-evolution operator, the Trotter step and the total evolution
###INSERT CODE BELOW THIS LINE
H = (I^X^X) + (X^X^I) + (I^Y^Y) + (Y^Y^I)
# Define a parameter t for the time in the time evolution operator
t = Parameter('t')
time_evolution_operator = (H*t).exp_i()
pauli_t_evol = PauliTrotterEvolution()
bound_trotter_exponentiation_circuit = pauli_t_evol.convert(time_evolution_operator)
bound_trotter_exponentiation_circuit = bound_trotter_exponentiation_circuit.bind_parameters({
t: time_step_value_t
})
total_time_evolution_circuit = bound_trotter_exponentiation_circuit
for i in range(1, steps_t):
total_time_evolution_circuit = total_time_evolution_circuit @ bound_trotter_exponentiation_circuit
full_time_evolution_circuit = tight_binding_circuit + total_time_evolution_circuit.to_circuit()
###DO NOT EDIT BELOW THIS LINE
print(full_time_evolution_circuit)
from qc_grader.challenges.qgss_2022 import grade_lab2_ex12
grade_lab2_ex12(full_time_evolution_circuit)
|
https://github.com/QuTech-Delft/quantuminspire
|
QuTech-Delft
|
import time
import os
import numpy as np
from IPython.display import display
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.visualization import plot_histogram, circuit_drawer
from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI
QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')
def pcircuit(nqubits, depth = 10):
""" Circuit to test performance of quantum computer """
q = QuantumRegister(nqubits)
ans = ClassicalRegister(nqubits)
qc = QuantumCircuit(q, ans)
for level in range(depth):
for qidx in range(nqubits):
qc.h( q[qidx] )
qc.barrier()
for qidx in range(nqubits):
qc.rx(np.pi/2, q[qidx])
qc.barrier()
for qidx in range(nqubits):
if qidx!=0:
qc.cx(q[qidx], q[0])
for qidx in range(nqubits):
qc.measure(q[qidx], ans[qidx])
return q, qc
q,qc = pcircuit(4, 1)
qc.draw(output='mpl')
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
qc = transpile(qc, qi_backend)
job = qi_backend.run(qc)
result = job.result()
print('Generated histogram:')
print(result.get_counts())
plot_histogram(result.get_counts(qc))
q, qc = pcircuit(10, 10)
start_time = time.time()
qc = transpile(qc, qi_backend)
job = qi_backend.run(qc, shots=8)
job.result()
interval = time.time() - start_time
print('time needed: %.1f [s]' % (interval,))
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import IBMQ
from qiskit.utils import QuantumInstance
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API KEY HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator') # Specifies the quantum device
print('\n Shors Algorithm')
print('--------------------')
print('\nExecuting...\n')
factors = Shor(QuantumInstance(backend, shots=100, skip_qobj_validation=False))
result_dict = factors.factor(N=21, a=2)
result = result_dict.factors
print(result)
print('\nPress any key to close')
input()
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
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":
### removed x gate ###
pass
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/UST-QuAntiL/nisq-analyzer-content
|
UST-QuAntiL
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer
# https://quantum-circuit.com/app_details/about/66bpe6Jf5mgQMahgd
# oracle = '(A | B) & (A | ~B) & (~A | B)'
qc = QuantumCircuit()
q = QuantumRegister(8, 'q')
c = ClassicalRegister(2, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
qc.h(q[1])
qc.x(q[2])
qc.x(q[3])
qc.x(q[4])
qc.x(q[7])
qc.x(q[0])
qc.x(q[1])
qc.h(q[7])
qc.ccx(q[0], q[1], q[2])
qc.x(q[0])
qc.x(q[1])
qc.x(q[1])
qc.ccx(q[0], q[1], q[3])
qc.x(q[0])
qc.x(q[1])
qc.ccx(q[1], q[0], q[4])
qc.x(q[0])
qc.ccx(q[3], q[2], q[5])
qc.x(q[0])
qc.ccx(q[5], q[4], q[6])
qc.cx(q[6], q[7])
qc.ccx(q[4], q[5], q[6])
qc.ccx(q[2], q[3], q[5])
qc.x(q[4])
qc.ccx(q[0], q[1], q[4])
qc.x(q[0])
qc.x(q[1])
qc.x(q[3])
qc.ccx(q[0], q[1], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[1])
qc.ccx(q[0], q[1], q[2])
qc.x(q[0])
qc.x(q[1])
qc.h(q[0])
qc.h(q[1])
qc.x(q[0])
qc.x(q[1])
qc.cz(q[0], q[1])
qc.x(q[0])
qc.x(q[1])
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
def get_circuit(**kwargs):
return qc
|
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/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# required import of libraries and modules
# import array to latex converter from
# IBM's Qiskit visualization module
from qiskit.visualization import array_to_latex
# import state-vector and random state-vector from
# IBM's Qiskit quantum information module
from qiskit.quantum_info import Statevector, random_statevector
# import abstract operator and pauli operator from
# IBM's Qiskit quantum information's operators module
from qiskit.quantum_info.operators import Operator, Pauli
# import quantum circuit from IBM's Qiskit
from qiskit import QuantumCircuit
# import hadamard gate and CX/CNOT gate from IBM's Qiskit
from qiskit.circuit.library import HGate, CXGate
# import numpy
import numpy as np
# define the column-vector for |0>
ket0 = [[1],[0]]
# convert the column-vector |0> to latex
array_to_latex(ket0)
# define the row-vector for <0|
bra0 = [1, 0]
# convert the row-vector <0| to latex
array_to_latex(bra0)
# put your answer answer here for the column-vector |1>
ket1 = [ [0], [1] ]
# put your answer here for the row-vector <1|
bra1 = [0, 1]
# import the grader for the exercise 1 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
# grade the exercise 1 of the lab 1
grade_lab1_ex1([ket1, bra1])
# create a state-vector for the row-vector <0|
sv_bra0 = Statevector(bra0)
# show the object of the state-vector for the row-vector <0|
sv_bra0
# draw the state-vector for the row-vector <0| in latex
sv_bra0.draw("latex")
# create a complex state-vector for multiple qubits
sv_eq = Statevector( [ 1/2, 3/4, 4/5, 6/8 ] )
# draw the complex state-vector created before in latex
sv_eq.draw("latex")
# check if the complex state-vector created before
# is valid for a quantum state (i.e., if it is normalised)
sv_eq.is_valid()
# create your valid statevector here
sv_valid = Statevector( [ 1/2, 1/2, 1/2, 1/2 ] )
# import the grader for the exercise 2 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
# grade the exercise 2 of the lab 1
grade_lab1_ex2(sv_valid)
# create an operator for the row-vector <0|
op_bra0 = Operator(bra0)
# show the object of the operator for the row-vector <0|
op_bra0
# create an operator for the column-vector |0>
op_ket0 = Operator(ket0)
# apply the tensor product of the operator
# created before to the operator applied to
# the row-vector <0|
op_bra0.tensor(op_ket0)
# compute the inner product between the row-vector <0|
# and the column-vector |0>, as a bra-ket product <0|0>
# note: this operator is also used to check if
# two pure quantum states overlap (i.e., are equal)
braket = np.dot(op_bra0, op_ket0)
# convert the result of the inner product
# computed before to latex
array_to_latex(braket)
# compute the outer product between the column-vector |0>
# and the column-vector <0|, as a ket-bra product |0><0|
ketbra = np.outer(ket0,bra0)
# convert the result of the outer product
# computed before to latex
array_to_latex(ketbra)
# definition of the operators for the row-vectors (bra vectors)
# <0| and <1|, and the column-vectors (ket vectors) |0> and |1>
op_bra0 = Operator(bra0)
op_bra1 = Operator(bra1)
op_ket0 = Operator(ket0)
op_ket1 = Operator(ket1)
# definition of the inner products (bra-ket products)
# put your answer for the inner product
# (bra-ket product) <1|0> here
bra1ket0 = np.dot(op_bra1, op_ket0)
# put your answer for the inner product
# (bra-ket product) <0|1> here
bra0ket1 = np.dot(op_bra0, op_ket1)
# put your answer for the inner product
# (bra-ket product) <1|1> here
bra1ket1 = np.dot(op_bra1, op_ket1)
# definition of the outer products (ket-bra products)
# put your answer for the outer product
# (ket-bra product) |1><0| here
ket1bra0 = np.outer(op_ket1, op_bra0)
# put your answer for the outer product
# (ket-bra product) |0><1| here
ket0bra1 = np.outer(op_ket0, op_bra1)
# put your answer for the outer product
# (ket-bra product) |1><1| here
ket1bra1 = np.outer(op_ket1, op_bra1)
# import the grader for the exercise 3 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
# grade the exercise 3 of the lab 1
grade_lab1_ex3( [ bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1 ] )
# two quantum states are orthogonal if
# they are completely opposite and
# never overlap with each other
# (i.e., when their inner product is equal to 0)
# <0|1> = <1|0> = 0, the quantum states |0> and |1>
# never overlap with each other and are completely opposite,
# or in other words, they are orthogonal
# add or remove your answer from this list
answer = ["a"]
# import the grader for the exercise 4 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
# grade the exercise 4 of the lab 1
grade_lab1_ex4(answer)
# create an operator for a single qubit system defined as
# m_1 = [ [1, 1],
# [0, 0] ], which represents the f1 = constant-0
# deterministic operation
m1 = Operator( [ [1, 1], [0, 0] ] )
# convert the operator created before to latex
array_to_latex(m1)
# create an operator for a single qubit system defined as
# m_3 = [ [0, 1],
# [1, 0] ], which represents the f3 = bit flip / not
# deterministic operation
m3 = Operator( [ [0, 1], [1,0] ] )
# convert the operator created before to latex
array_to_latex(m3)
# represent in latex the result of applying
# the operator m1 to the column-vector (ket vector) |0>
array_to_latex(m1@ket0)
# create an operator for a single qubit system defined as
# m_2 = [ [1, 0],
# [0, 1] ], which represents the f2 = identity
# deterministic operation
m2 = Operator( [ [1, 0], [0, 1] ] )
# create an operator for a single qubit system defined as
# m_4 = [ [0, 0],
# [1, 1] ], which represents the f4 = constant-1
# deterministic operation
m4 = Operator( [ [0, 0], [1, 1] ] )
# import the grader for the exercise 5 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
# grade the exercise 5 of the lab 1
grade_lab1_ex5( [ m2, m4 ] )
# create a CX/CNOT quantum gate as an operator
cnot = CXGate()
# convert the operator created before to latex
array_to_latex(cnot)
# check if the operator for a single qubit system defined as
# m_3 = [ [0, 1],
# [1, 0] ], which represents the f3 = bit flip / not
# deterministic operation, is unitary
m3.is_unitary()
# create a random operator for multiple qubit system
random = Operator( np.array(
[ [ 0.50778085 - 0.44607116j, -0.1523741 + 0.14128434j,
0.44607116 + 0.50778085j, -0.14128434 - 0.1523741j ],
[ 0.16855994 + 0.12151822j, 0.55868196 + 0.38038841j,
-0.12151822 + 0.16855994j, -0.38038841 + 0.55868196j ],
[ 0.50778085 - 0.44607116j, -0.1523741 + 0.14128434j,
-0.44607116 - 0.50778085j, 0.14128434 + 0.1523741j ],
[ 0.16855994 + 0.12151822j, 0.55868196 + 0.38038841j,
0.12151822 - 0.16855994j, 0.38038841-0.55868196j ] ] ) )
# check if the random operator for multiple qubit system is random
random.is_unitary()
# create your non-unitary operator here
non_unitary_op = Operator( [ [1, 0], [1, 1] ] )
# import the grader for the exercise 6 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
# grade the exercise 6 of the lab 1
grade_lab1_ex6(non_unitary_op)
# create the Pauli-X (bit flip / not) quantum gate
pauli_x = Pauli("X")
# convert the quantum gate created before to latex
array_to_latex(pauli_x)
# create the Pauli-Y quantum gate
pauli_y = Pauli("Y")
# convert the quantum gate created before to latex
array_to_latex(pauli_y)
# create the Pauli-Z (phase flip) quantum gate
pauli_z = Pauli("Z")
# convert the quantum gate created before to latex
array_to_latex(pauli_z)
# convert the Pauli-X (bit flip / not)
# quantum gate to an operator
op_x = Operator(pauli_x)
# show the Pauli-X (bit flip / not)
# quantum gate converted to an operator
op_x
# apply the inner product between the Pauli-X (bit flip / not) operator
# the quantum state of the column-vector (ket vector) |0>, resulting to
# a new quantum state of the column-vector (ket vector) |1>
op_new = np.dot(op_x ,ket0)
# convert the resulting new operator to latex
array_to_latex(op_new)
# do your operations here
# convert the Pauli-Z (phase flip)
# quantum gate to an operator
op_z = Operator(pauli_z)
# apply the inner product between the Pauli-Z (phase flip) operator
# the quantum state of the column-vector (ket vector) |1>, resulting to
# a new quantum state of the column-vector (ket vector) -|1>
result = np.dot(op_z ,ket1)
# convert the resulting new operator to latex
array_to_latex(result)
# import the grader for the exercise 7 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
# grade the exercise 7 of the lab 1
grade_lab1_ex7(result)
# create the Hadamard quantum gate
hadamard = HGate()
# convert the quantum gate created before to latex
array_to_latex(hadamard)
# convert the Hadamard quantum gate to an operator
op_h = Operator(hadamard)
# show the Hadamard quantum gate
# converted to an operator
print(op_h)
# check if the Hadamard quantum gate
# converted to an operator is unitary
op_h.is_unitary()
# create a quantum circuit for two qubits
# and to implement a Bell state
bell = QuantumCircuit(2)
# apply a Hadamard gate to
# the 1st qubit of the quantum circuit
bell.h(0)
# apply a CX/CNOT gate to
# the 1st and 2nd qubits of the quantum circuit
bell.cx(0, 1)
# draw the quantum circuit implementing the Bell state
bell.draw(output="mpl")
# converting the quantum circuit
# implementing the Bell state to an operator
bell_op = Operator(bell)
# convert the quantum operator representing
# the quantum circuit created before to latex
array_to_latex(bell_op)
# create a quantum circuit for three qubits
# and to implement a GHZ state
ghz = QuantumCircuit(3)
##############################
# add gates to your quantum circuit here
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
ghz.h(0)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1st qubit
# and target on 2nd qubit
ghz.cx(0, 1)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 2nd qubit
# and target on 3rd qubit
ghz.cx(1, 2)
##############################
# draw the quantum circuit implementing the GHZ state
ghz.draw(output="mpl")
# import the grader for the exercise 8 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
# grade the exercise 8 of the lab 1
grade_lab1_ex8(ghz)
# create the state-vector for
# the quantum superposition state |+>
plus_state = Statevector.from_label("+")
# convert the state-vector created before to latex
plus_state.draw("latex")
# show the state-vector |+> created before
plus_state
# show the probabilities of the possible
# classical outcomes/states resulting
# from measuring the quantum superposition state |+>
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing
# into one state or the other (i.e., 0 or 1)
# for a number of trials equal to 5
for _ in range(5):
# measure the quantum superposition state |+>
res = plus_state.measure()
# print the result of the measurement of
# the quantum superposition state |+>
print(res)
# create a quantum circuit for one qubit and one bit,
# to implement a |+> quantum superposition state
qc = QuantumCircuit(1, 1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc.h(0)
# measure the 1st qubit of the quantum circuit
# to the respective 1st bit of the same
qc.measure(0, 0)
# draw the quantum circuit for one qubit and one bit,
# implementing a |+> quantum superposition state
qc.draw(output="mpl")
# create the state-vector for the Bell State |phi^+>
sv_bell = Statevector( [ np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2) ] )
# draw the state-vector for the Bell State |phi^+>
sv_bell.draw("latex")
sv_bell.probabilities_dict()
# creation of the three quantum states in the Bell basis,
# namely, |psi^+⟩, |psi^-⟩, and |phi^-⟩
# create a statevector for |psi^+⟩ here
sv_psi_plus = Statevector( [ 0, np.sqrt(1 / 2), np.sqrt(1 / 2), 0 ] )
# find the measurement probabilities for |psi^+⟩ here
prob_psi_plus = sv_psi_plus.probabilities_dict()
# create a statevector for |psi^-⟩ here
sv_psi_minus = Statevector( [ 0, np.sqrt(1 / 2), -1 * np.sqrt(1 / 2), 0 ] )
# find the measurement probabilities for |psi^−⟩ here
prob_psi_minus = sv_psi_minus.probabilities_dict()
# create a statevector for |phi^-⟩ here
sv_phi_minus = Statevector( [ np.sqrt(1 / 2), 0, 0, -1 * np.sqrt(1 / 2) ] )
# find the measurement probabilities for |phi^-⟩ here
prob_phi_minus = sv_phi_minus.probabilities_dict()
# import the grader for the exercise 9 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
# grade the exercise 9 of the lab 1
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
# create a quantum circuit for two qubits,
# to implement a quantum fourier transform
qft = QuantumCircuit(2)
##############################
# add gates to your quantum circuit here
# apply an Hadamard gate to
# the quantum circuit, on the 2nd qubit
qft.h(1)
# apply a Controlled-Phase (CP) gate to
# the quantum circuit acccording to
# a theta angle, with control on
# the 1st qubit and target on the 2nd qubit
qft.cp( np.pi/2, 0, 1 )
# apply an Hadamard gate to
# the quantum circuit, on the 1st qubit
qft.h(0)
# apply a SWAP gate to
# the quantum circuit,
# between the 1st qubit
# and the 2nd qubit
qft.swap(0, 1)
##############################
# draw the quantum circuit for two qubits,
# implementing a quntum fourier transform
qft.draw(output="mpl")
# import the grader for the exercise 10 of the lab 1
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
# grade the exercise 10 of the lab 1
grade_lab1_ex10(qft)
# create an operator U from the quantum circuit of
# the quantum fourier transform created before
U = Operator(qft)
# convert the quantum operator U representing
# the quantum circuit created before to latex
array_to_latex(U)
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
from qiskit import *
%matplotlib inline
from matplotlib import style
style.use('bmh')
style.use('dark_background')
from math import pi, log
def new_mcrz(qc, theta, q_controls, q_target):
n = len(q_controls)
newtheta = -theta/2**n
a = lambda n: log(n-(n&(n-1)), 2)
qc.cx(q_controls[n-1], q_target)
qc.u1(newtheta, q_target)
for i in range(1, 2**n):
qc.cx(q_controls[int(a(i))], q_target)
qc.u1((-1)**i*newtheta,q_target)
QuantumCircuit.new_mcrz = new_mcrz
def new_mcz(qc, q_controls, q_target):
L = q_controls + [q_target]
n = len(L)
qc.u1(pi/2**(n-1), L[0])
for i in range(2, n+1):
qc.new_mcrz(pi/2**(n-i), L[0:i-1], L[i-1])
QuantumCircuit.new_mcz = new_mcz
Search_key = '1010'
# Total number of qubits to represent the search space
num_qubits = len(Search_key)
# Search space size
search_space = 2**num_qubits
print('Number of Qubits:', num_qubits)
print('Search-space size:', search_space)
from math import sqrt, ceil
def Uw(qc, key):
ctrl_on = ''
if num_qubits % 4 == 0:
ctrl_on = '1'
elif num_qubits % 4 == 2:
ctrl_on = '0'
for i, bin_val in enumerate(reversed(key)):
if bin_val == ctrl_on:
qc.x(i)
qc.new_mcz([range(num_qubits-1)], num_qubits-1)
for i, bin_val in enumerate(reversed(key)):
if bin_val == ctrl_on:
qc.x(i)
return qc
def Us(qc):
qc.h(range(num_qubits))
qc.x(range(num_qubits))
qc.new_mcz([range(num_qubits-1)], num_qubits-1)
qc.x(range(num_qubits))
qc.h(range(num_qubits))
return qc
def GroverSearch(qc, key):
steps = 0
if num_qubits < 4:
steps = int(sqrt(search_space) * pi / 4)
else:
steps = ceil(sqrt(search_space) * pi / 4)
if len(key) > num_qubits:
print('Invalid length of key, please check the key input.')
return
qc.h(range(num_qubits))
for i in range(steps):
qc = Uw(qc, key)
qc = Us(qc)
return qc
qc = QuantumCircuit(num_qubits, num_qubits)
qc = GroverSearch(qc, Search_key)
qc.measure(range(num_qubits), range(num_qubits))
qc.draw(output='mpl')
print('Depth of Circuit:', qc.depth())
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=8192).result()
plot_histogram(result.get_counts(qc))
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open')
device = provider.get_backend('ibmq_ourense')
job = execute(qc, backend=device, shots=8192)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
provider = IBMQ.get_provider(hub='ibm-q', group='open')
device = provider.get_backend('ibmq_ourense')
job = execute(qc, backend=device, shots=8192)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
|
https://github.com/RakhshandaMujib/Deutsch-Joza-Algorithm
|
RakhshandaMujib
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
driver = PySCFDriver(atom="O 0.0 0.0 0.115; H 0.0 0.754 -0.459; H 0.0 -0.754 -0.459")
transformer = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, [transformer])
second_q_ops = problem.second_q_ops()
# implicitly calls driver.run() EVERY time!
for name, op in second_q_ops.items():
print(f"{name}\n{op}\n")
hamiltonian = second_q_ops[problem.main_property_name]
print(problem.main_property_name)
print(hamiltonian)
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
driver = PySCFDriver(atom="O 0.0 0.0 0.115; H 0.0 0.754 -0.459; H 0.0 -0.754 -0.459")
transformer = FreezeCoreTransformer()
problem = driver.run()
transformed_problem = transformer.transform(problem)
hamiltonian, aux_ops = transformed_problem.second_q_ops()
print(hamiltonian)
for name, op in aux_ops.items():
print(f"{name}\n{op}\n")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
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/WhenTheyCry96/qiskitHackathon2022
|
WhenTheyCry96
|
%load_ext autoreload
%autoreload 2
import os
import warnings
import numpy as np
import pyEPR as epr
import qiskit_metal as metal
from collections import OrderedDict
import scqubits as scq
from scipy.constants import c, h, pi, hbar, e
from qiskit_metal import designs, draw, MetalGUI, Dict, Headings
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry
ws_path = os.getcwd()
warnings.filterwarnings("ignore")
design = designs.DesignPlanar()
design.overwrite_enabled = True
#constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
design.delete_all_components()
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
connection23_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection23_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
asym_h = 100
asym_v = 100
cpw = []
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
readouts_lwc = []
control_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
control_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='330um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
gui.screenshot(name="full_design.png")
# constants:
phi0 = h/(2*e)
varphi0 = phi0/(2*pi)
# project target parameters
f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz
f_rList = f_qList + 1.8 # GHz
L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH
# initial CPW readout lengths
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(f_rList, 10, 6, 2)
# CPW busline length is determined to be 7 mm
cpw[0].options.total_length = '7.0mm'
cpw[1].options.total_length = '7.0mm'
cpw[2].options.total_length = '7.0mm'
cpw[3].options.total_length = '7.0mm'
gui.rebuild()
gui.autoscale()
# qubit 1 design target f: 5.25 GHz
# readout resonator target f: 7.05 GHz
# qubit 2 design target f: 5.42 GHz
# readout resonator target f: 7.22 GHz
# qubit 3 design target f: 5.58 GHz
# readout resonator target f: 7.38 GHz
# qubit 4 design target f: 5.75 GHz
# readout resonator target f: 7.55 GHz
# tuning parameters
C_JJ4f = 2
L_JJ4f = 9.8
C_JJ4 = str(C_JJ4f)+' fF'
L_JJ4 = str(L_JJ4f)+' nH'
transmons[3].options.pad_gap = '35um'
transmons[3].options.pad_width = '510um'
transmons[3].options.pad_height = '125um'
transmons[3].options.connection_pads.c.pad_gap = '30um'
transmons[3].options.connection_pads.a.pad_gap = '15um' # cpw5
transmons[3].options.connection_pads.a.pad_width = '40um' # cpw5
transmons[3].options.connection_pads.b.pad_gap = '15um' # cpw3
transmons[3].options.connection_pads.b.pad_width = '40um' # cpw3
readout_lines[3].options.total_length = '7.5mm'
gui.rebuild()
gui.autoscale()
# EPR analysis
eig_q4 = EPRanalysis(design, "hfss")
hfss4 = eig_q4.sim.renderer
hfss4.start()
hfss4.activate_ansys_design("TransmonQ4", 'eigenmode')
hfss4.render_design(['Q4', 'ol4', 'cpw3', 'cpw5'], [('cpw3', 'end'), ('cpw5', 'start'), ('ol4', 'end')])
# Analysis properties
setup4 = hfss4.pinfo.setup
setup4.n_modes = 6
setup4.passes = 10
setup4.min_freq_ghz = 4
print(f"""
Number of eigenmodes to find = {setup4.n_modes}
Number of simulation passes = {setup4.passes}
Convergence freq max delta percent diff = {setup4.delta_f}
""")
pinfo4 = hfss4.pinfo
pinfo4.design.set_variable('Lj4', L_JJ4)
pinfo4.design.set_variable('Cj4', C_JJ4)
setup4.analyze()
eig_q4.sim.convergence_t, eig_q4.sim.convergence_f, _ = hfss4.get_convergences()
eig_q4.sim.plot_convergences()
pinfo4.junctions['jj'] = {'Lj_variable': 'Lj4', 'rect': 'JJ_rect_Lj_Q4_rect_jj',
'line': 'JJ_Lj_Q4_rect_jj_', 'Cj_variable': 'Cj4'}
pinfo4.validate_junction_info()
pinfo4.dissipative['dielectrics_bulk'] = ['main']
hfss4.set_mode(1, "Setup")
hfss4.modeler._modeler.ShowWindow()
hfss4.plot_fields('main')
eprd4 = epr.DistributedAnalysis(pinfo4)
ℰ_elec = eprd4.calc_energy_electric()
ℰ_elec_substrate = eprd4.calc_energy_electric(None, 'main')
ℰ_mag = eprd4.calc_energy_magnetic()
print(f"""
ℰ_elec_all = {ℰ_elec}
ℰ_elec_substrate = {ℰ_elec_substrate}
EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}%
ℰ_mag_all = {ℰ_mag}
ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}%
""")
eprd4.do_EPR_analysis()
#epra4 = epr.QuantumAnalysis(eprd4.data_filename)
#epra4.analyze_all_variations(cos_trunc = 8, fock_trunc = 7)
c4 = LOManalysis(design, "q3d")
q3d4 = c4.sim.renderer
q3d4.start()
q3d4.activate_ansys_design("TransmonQ4_q3d", 'capacitive')
q3d4.render_design(['Q4'], [('Q4', 'a'),('Q4', 'b'),('Q4', 'c')])
q3d4.add_q3d_setup(name="Setup", max_passes=15, min_converged_passes=5, percent_error=0.1)
q3d4.analyze_setup("Setup")
c4.sim.capacitance_matrix, c4.sim.units = q3d4.get_capacitance_matrix()
c4.sim.capacitance_all_passes, _ = q3d4.get_capacitance_all_passes()
c4.sim.capacitance_matrix
c4.setup.junctions = Dict({'Lj':L_JJ4f, 'Cj':C_JJ4f})
c4.setup.freq_readout = 7.45
c4.setup.freq_bus = [8.25, 8.25, 15]
c4.run_lom()
c4.lumped_oscillator_all
QuantumSystemRegistry.registry()
# Q4
path4= ws_path+"/Project71_TransmonQ4_q3d.txt"
t4_mat, _, _, _ = load_q3d_capacitance_matrix(path4)
# Cell 4 Transmon-4
opt4 = dict(
node_rename = {'a_connector_pad_Q4': 'cpw5',
'b_connector_pad_Q4': 'cpw3',
'c_connector_pad_Q4': 'readout4'},
cap_mat = t4_mat,
ind_dict = {('pad_top_Q4', 'pad_bot_Q4'): L_JJ4f}, # junction inductance in nH
jj_dict = {('pad_top_Q4', 'pad_bot_Q4'): 'j4'},
cj_dict = {('pad_top_Q4', 'pad_bot_Q4'): C_JJ4f} # junction capacitance in fF
)
cell_4 = Cell(opt4)
# subsystem 1: Transmon-4
transmon4 = Subsystem(name='transmon4', sys_type='TRANSMON', nodes=['j4'])
# Resonator Subsystems
q_opts = dict(
Z0 = 50, # characteristic impedance in Ohm
vp = 0.404314 * 3e8 # phase velocity
)
# subsystem 3: Q2 readout resonator
ro4 = Subsystem(name='readout4', sys_type='TL_RESONATOR', nodes=['readout4'], q_opts=dict(f_res = 7.57, **q_opts))
# subsystem 4: bus3 resonator
cpw3 = Subsystem(name='cpw3', sys_type='TL_RESONATOR', nodes=['cpw3'], q_opts=dict(f_res = 8.2, **q_opts))
# subsystem 15: bus5 resonator
cpw5 = Subsystem(name='cpw5', sys_type='TL_RESONATOR', nodes=['cpw5'], q_opts=dict(f_res = 8.29, **q_opts))
composite_sys = CompositeSystem(
subsystems=[transmon4, ro4, cpw3, cpw5],
cells=[cell_4],
grd_node='ground_main_plane',
nodes_force_keep=['readout4', 'cpw3', 'cpw5']
)
cg = composite_sys.circuitGraph()
print(cg)
hilbertspace = composite_sys.create_hilbertspace()
print(hilbertspace)
# Convert the hilbert space into
# "Interaction Picture"
hilbertspace = composite_sys.add_interaction()
hilbertspace.hamiltonian()
hamiltonian_results = composite_sys.hamiltonian_results(hilbertspace, evals_count=30)
composite_sys.compute_gs()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#import all the packages
# Checking the version of PYTHON
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
#append to system path so qiskit and Qconfig can be found from home directory
sys.path.append('../qiskit-sdk-py/')
# Import the QuantumProgram and configuration
from qiskit import QuantumProgram
#import Qconfig
#other useful packages
import math
#Super secret message
mes = 'hello world'
print('Your super secret message: ',mes)
#initial size of key
n = len(mes)*3
#break up message into smaller parts if length > 10
nlist = []
for i in range(int(n/10)):
nlist.append(10)
if n%10 != 0:
nlist.append(n%10)
print('Initial key length: ',n)
# Make random strings of length string_length
def randomStringGen(string_length):
#output variables used to access quantum computer results at the end of the function
output_list = []
output = ''
#start up your quantum program
qp = QuantumProgram()
backend = 'local_qasm_simulator'
circuits = ['rs']
#run circuit in batches of 10 qubits for fastest results. The results
#from each run will be appended and then clipped down to the right n size.
n = string_length
temp_n = 10
temp_output = ''
for i in range(math.ceil(n/temp_n)):
#initialize quantum registers for circuit
q = qp.create_quantum_register('q',temp_n)
c = qp.create_classical_register('c',temp_n)
rs = qp.create_circuit('rs',[q],[c])
#create temp_n number of qubits all in superpositions
for i in range(temp_n):
rs.h(q[i]) #the .h gate is the Hadamard gate that makes superpositions
rs.measure(q[i],c[i])
#execute circuit and extract 0s and 1s from key
result = qp.execute(circuits, backend, shots=1)
counts = result.get_counts('rs')
result_key = list(result.get_counts('rs').keys())
temp_output = result_key[0]
output += temp_output
#return output clipped to size of desired string length
return output[:n]
key = randomStringGen(n)
print('Initial key: ',key)
#generate random rotation strings for Alice and Bob
Alice_rotate = randomStringGen(n)
Bob_rotate = randomStringGen(n)
print("Alice's rotation string:",Alice_rotate)
print("Bob's rotation string: ",Bob_rotate)
#start up your quantum program
backend = 'local_qasm_simulator'
shots = 1
circuits = ['send_over']
Bob_result = ''
for ind,l in enumerate(nlist):
#define temp variables used in breaking up quantum program if message length > 10
if l < 10:
key_temp = key[10*ind:10*ind+l]
Ar_temp = Alice_rotate[10*ind:10*ind+l]
Br_temp = Bob_rotate[10*ind:10*ind+l]
else:
key_temp = key[l*ind:l*(ind+1)]
Ar_temp = Alice_rotate[l*ind:l*(ind+1)]
Br_temp = Bob_rotate[l*ind:l*(ind+1)]
#start up the rest of your quantum program
qp2 = QuantumProgram()
q = qp2.create_quantum_register('q',l)
c = qp2.create_classical_register('c',l)
send_over = qp2.create_circuit('send_over',[q],[c])
#prepare qubits based on key; add Hadamard gates based on Alice's and Bob's
#rotation strings
for i,j,k,n in zip(key_temp,Ar_temp,Br_temp,range(0,len(key_temp))):
i = int(i)
j = int(j)
k = int(k)
if i > 0:
send_over.x(q[n])
#Look at Alice's rotation string
if j > 0:
send_over.h(q[n])
#Look at Bob's rotation string
if k > 0:
send_over.h(q[n])
send_over.measure(q[n],c[n])
#execute quantum circuit
result_so = qp2.execute(circuits, backend, shots=shots)
counts_so = result_so.get_counts('send_over')
result_key_so = list(result_so.get_counts('send_over').keys())
Bob_result += result_key_so[0][::-1]
print("Bob's results: ", Bob_result)
def makeKey(rotation1,rotation2,results):
key = ''
count = 0
for i,j in zip(rotation1,rotation2):
if i == j:
key += results[count]
count += 1
return key
Akey = makeKey(Bob_rotate,Alice_rotate,key)
Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_result)
print("Alice's key:",Akey)
print("Bob's key: ",Bkey)
#make key same length has message
shortened_Akey = Akey[:len(mes)]
encoded_m=''
#encrypt message mes using encryption key final_key
for m,k in zip(mes,shortened_Akey):
encoded_c = chr(ord(m) + 2*ord(k) % 256)
encoded_m += encoded_c
print('encoded message: ',encoded_m)
#make key same length has message
shortened_Bkey = Bkey[:len(mes)]
#decrypt message mes using encryption key final_key
result = ''
for m,k in zip(encoded_m,shortened_Bkey):
encoded_c = chr(ord(m) - 2*ord(k) % 256)
result += encoded_c
print('recovered message:',result)
#start up your quantum program
backend = 'local_qasm_simulator'
shots = 1
circuits = ['Eve']
Eve_result = ''
for ind,l in enumerate(nlist):
#define temp variables used in breaking up quantum program if message length > 10
if l < 10:
key_temp = key[10*ind:10*ind+l]
Ar_temp = Alice_rotate[10*ind:10*ind+l]
else:
key_temp = key[l*ind:l*(ind+1)]
Ar_temp = Alice_rotate[l*ind:l*(ind+1)]
#start up the rest of your quantum program
qp3 = QuantumProgram()
q = qp3.create_quantum_register('q',l)
c = qp3.create_classical_register('c',l)
Eve = qp3.create_circuit('Eve',[q],[c])
#prepare qubits based on key; add Hadamard gates based on Alice's and Bob's
#rotation strings
for i,j,n in zip(key_temp,Ar_temp,range(0,len(key_temp))):
i = int(i)
j = int(j)
if i > 0:
Eve.x(q[n])
if j > 0:
Eve.h(q[n])
Eve.measure(q[n],c[n])
#execute
result_eve = qp3.execute(circuits, backend, shots=shots)
counts_eve = result_eve.get_counts('Eve')
result_key_eve = list(result_eve.get_counts('Eve').keys())
Eve_result += result_key_eve[0][::-1]
print("Eve's results: ", Eve_result)
#start up your quantum program
backend = 'local_qasm_simulator'
shots = 1
circuits = ['Eve2']
Bob_badresult = ''
for ind,l in enumerate(nlist):
#define temp variables used in breaking up quantum program if message length > 10
if l < 10:
key_temp = key[10*ind:10*ind+l]
Eve_temp = Eve_result[10*ind:10*ind+l]
Br_temp = Bob_rotate[10*ind:10*ind+l]
else:
key_temp = key[l*ind:l*(ind+1)]
Eve_temp = Eve_result[l*ind:l*(ind+1)]
Br_temp = Bob_rotate[l*ind:l*(ind+1)]
#start up the rest of your quantum program
qp4 = QuantumProgram()
q = qp4.create_quantum_register('q',l)
c = qp4.create_classical_register('c',l)
Eve2 = qp4.create_circuit('Eve2',[q],[c])
#prepare qubits
for i,j,n in zip(Eve_temp,Br_temp,range(0,len(key_temp))):
i = int(i)
j = int(j)
if i > 0:
Eve2.x(q[n])
if j > 0:
Eve2.h(q[n])
Eve2.measure(q[n],c[n])
#execute
result_eve = qp4.execute(circuits, backend, shots=shots)
counts_eve = result_eve.get_counts('Eve2')
result_key_eve = list(result_eve.get_counts('Eve2').keys())
Bob_badresult += result_key_eve[0][::-1]
print("Bob's previous results (w/o Eve):",Bob_result)
print("Bob's results from Eve:\t\t ",Bob_badresult)
#make keys for Alice and Bob
Akey = makeKey(Bob_rotate,Alice_rotate,key)
Bkey = makeKey(Bob_rotate,Alice_rotate,Bob_badresult)
print("Alice's key: ",Akey)
print("Bob's key: ",Bkey)
check_key = randomStringGen(len(Akey))
print('spots to check:',check_key)
#find which values in rotation string were used to make the key
Alice_keyrotate = makeKey(Bob_rotate,Alice_rotate,Alice_rotate)
Bob_keyrotate = makeKey(Bob_rotate,Alice_rotate,Bob_rotate)
# Detect Eve's interference
#extract a subset of Alice's key
sub_Akey = ''
sub_Arotate = ''
count = 0
for i,j in zip(Alice_rotate,Akey):
if int(check_key[count]) == 1:
sub_Akey += Akey[count]
sub_Arotate += Alice_keyrotate[count]
count += 1
#extract a subset of Bob's key
sub_Bkey = ''
sub_Brotate = ''
count = 0
for i,j in zip(Bob_rotate,Bkey):
if int(check_key[count]) == 1:
sub_Bkey += Bkey[count]
sub_Brotate += Bob_keyrotate[count]
count += 1
print("subset of Alice's key:",sub_Akey)
print("subset of Bob's key: ",sub_Bkey)
#compare Alice and Bob's key subsets
secure = True
for i,j in zip(sub_Akey,sub_Bkey):
if i == j:
secure = True
else:
secure = False
break;
if not secure:
print('Eve detected!')
else:
print('Eve escaped detection!')
#sub_Akey and sub_Bkey are public knowledge now, so we remove them from Akey and Bkey
if secure:
new_Akey = ''
new_Bkey = ''
for index,i in enumerate(check_key):
if int(i) == 0:
new_Akey += Akey[index]
new_Bkey += Bkey[index]
print('new A and B keys: ',new_Akey,new_Bkey)
if(len(mes)>len(new_Akey)):
print('Your new key is not long enough.')
#!!! you may need to execute this cell twice in order to see the output due to an problem with matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0., 30.0)
y = 1-(3/4)**x
plt.plot(y)
plt.title('Probablity of detecting Eve')
plt.xlabel('# of key bits compared')
plt.ylabel('Probablity of detecting Eve')
plt.show()
|
https://github.com/rochisha0/quantum-ugly-duckling
|
rochisha0
|
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.save_account('IBMQ ID', overwrite=True)
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") # The configuration returns dt in seconds, so multiply by
# 1e9 to get nanoseconds
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The 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.")
# samples need to be multiples of 16
def get_closest_multiple_of_16(num):
return int(num + 8 ) - (int(num + 8 ) % 16)
from qiskit import pulse # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
# Drive pulse parameters (us = microseconds)
drive_sigma_us = 0.075 # This determines the actual width of the gaussian
drive_samples_us = drive_sigma_us*8 # This is a truncating parameter, because gaussians don't have
# a natural finite length
drive_sigma = get_closest_multiple_of_16(drive_sigma_us * us /dt) # The width of the gaussian in units of dt
drive_samples = get_closest_multiple_of_16(drive_samples_us * us /dt) # The truncating parameter in units of dt
drive_amp = 0.3
# Drive pulse samples
drive_pulse = pulse_lib.gaussian(duration=drive_samples,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse')
# Find out which group of qubits need to be acquired with this qubit
meas_map_idx = None
for i, measure_group in enumerate(backend_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=backend_config.meas_map[meas_map_idx])
### 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 += Play(drive_pulse, drive_chan)
# 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)
from qiskit import assemble
num_shots_per_frequency = 1024
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_frequencies)
job = backend.run(frequency_sweep_program)
# print(job.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job)
frequency_sweep_results = job.result(timeout=120) # timeout parameter set to 120 seconds
import matplotlib.pyplot as plt
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, sweep_values_inverted, color='black') # 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()
sweep_values_inverted = -1*np.real(sweep_values)
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,
sweep_values_inverted,
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, sweep_values_inverted, color='black')
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()
A, rough_qubit_frequency, B, C = fit_params
rough_qubit_frequency = rough_qubit_frequency*GHz # make sure qubit freq is in Hz
print(f"We've updated our qubit frequency estimate from "
f"{round(backend_defaults.qubit_freq_est[qubit] / GHz, 5)} GHz to {round(rough_qubit_frequency/GHz, 5)} GHz.")
print(rough_qubit_frequency)
# This experiment uses these values from the previous experiment:
# `qubit`,
# `measure`, and
# `rough_qubit_frequency`.
# Rabi experiment parameters
num_rabi_points = 50
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# Reuse the measure instruction from the frequency sweep experiment
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True)
# Assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: rough_qubit_frequency}]
* num_rabi_points)
# print(job.job_id())
job = backend.run(rabi_experiment_program)
job_monitor(job)
rabi_results = job.result(timeout=120)
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='black') # plot real part of Rabi values
plt.show()
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[3, 0.1, 0.5, 0])
plt.scatter(drive_amps, rabi_values, color='black')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
pi_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=pi_amp,
sigma=drive_sigma,
name='pi_pulse')
# T1 experiment parameters
time_max_us = 450
time_step_us = 6
times_us = np.arange(1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# We will use the same `pi_pulse` and qubit frequency that we calibrated and used before
# Create schedules for the experiment
t1_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"T1 delay = {delay * dt/us} us")
this_schedule += Play(pi_pulse, drive_chan)
this_schedule |= measure << int(delay)
t1_schedules.append(this_schedule)
sched_idx = 0
t1_schedules[sched_idx].draw(label=True)
# Execution settings
num_shots = 256
t1_experiment = assemble(t1_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: rough_qubit_frequency}] * len(t1_schedules))
job = backend.run(t1_experiment)
# print(job.job_id())
job_monitor(job)
t1_results = job.result(timeout=120)
t1_values = []
for i in range(len(times_us)):
t1_values.append(t1_results.get_memory(i)[qubit]*scale_factor)
t1_values = np.real(t1_values)
plt.scatter(times_us, t1_values, color='black')
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.show()
# Fit the data
fit_params, y_fit = fit_function(times_us, t1_values,
lambda x, A, C, T1: (A * np.exp(-x / T1) + C),
[-3, 3, 100]
)
_, _, T1 = fit_params
plt.scatter(times_us, t1_values, color='black')
plt.plot(times_us, y_fit, color='red', label=f"T1 = {T1:.2f} us")
plt.xlim(0, np.max(times_us))
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.legend()
plt.show()
print("Value of T1 is {} us".format(T1))
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule |= Play(x90_pulse, drive_chan)
this_schedule |= Play(x90_pulse, drive_chan) << int(this_schedule.duration + delay)
this_schedule |= measure << int(this_schedule.duration)
ramsey_schedules.append(this_schedule)
ramsey_schedules[0].draw(label=True)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(rough_qubit_frequency + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
job = backend.run(ramsey_program)
# print(job.job_id())
job_monitor(job)
ramsey_results = job.result(timeout=120)
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.xlim(0, np.max(times_us))
plt.title("Ramsey Experiment", fontsize=15)
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.show()
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
precise_qubit_freq = rough_qubit_frequency + (del_f_MHz - detuning_MHz) * MHz # get new freq in Hz
print(f"Our updated qubit frequency is now {round(precise_qubit_freq/GHz, 6)} GHz. "
f"It used to be {round(rough_qubit_frequency / GHz, 6)} GHz")
precise_qubit_freq
# Ramsey experiment parameters
time_max_us = 240
time_step_us = 4
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule |= Play(x90_pulse, drive_chan)
this_schedule |= Play(x90_pulse, drive_chan) << int(this_schedule.duration + delay)
this_schedule |= measure << int(this_schedule.duration)
ramsey_schedules.append(this_schedule)
ramsey_schedules[0].draw(label=True)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(precise_qubit_freq, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
job = backend.run(ramsey_program)
# print(job.job_id())
job_monitor(job)
ramsey_results = job.result(timeout=120)
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.xlim(0, np.max(times_us))
plt.title("Ramsey Experiment", fontsize=15)
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.show()
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='black')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
# Ramsey experiment parameters
# time_max_us = 400
# time_step_us = 8
# times_us = np.arange(0.1, time_max_us, time_step_us)
times_us = np.array([100])
# Convert to units of dt
delay_times_dt = times_us * us / dt
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# create schedules for Ramsey experiment
ramsey_schedules_ = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule |= Play(x90_pulse, drive_chan)
this_schedule |= Play(x90_pulse, drive_chan) << int(this_schedule.duration + delay)
this_schedule |= measure << int(this_schedule.duration)
ramsey_schedules_.append(this_schedule)
ramsey_schedules_[0].draw(label=True)
# Execution settings
num_shots = 1024
detuning_MHz = 2
ramsey_frequency = round(precise_qubit_freq, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=2,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules_)
)
ramsey_schedules
job = backend.run(ramsey_program)
# print(job.job_id())
job_monitor(job)
ramsey_results = job.result(timeout=120)
len(counts)
counts = ramsey_results.get_counts()
from qiskit.visualization import plot_histogram
plot_histogram(counts[-1])
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
backend = provider.get_backend("ibmq_armonk")
pulse_job = backend.retrieve_job('5f8053f2d2769f00132c6bd9')
counts = pulse_job.result().get_counts()
counts
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/davidedellagiustina/qasp-solver
|
davidedellagiustina
|
'''Amplitude amplification algorithms.
'''
import copy
import math
import random
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit.library import GroverOperator
from ..oracle import Interpretation, QuantumOracle, Oracle
from ..simul import exec_circuit
# +-----------------------+
# | Amplification circuit |
# +-----------------------+
def __optimal_num_iters(n: int, m: int) -> int:
'''Return the optimal number of iterations for amplitude amplification.
Source: \
https://github.com/Qiskit/qiskit/blob/stable/0.45/qiskit/algorithms/amplitude_amplifiers/grover.py#L381.
#### Arguments
n (int): Number of search qubits.
m (int): (Known) number of solutions to the problem.
#### Return
int: Optimal number of iterations.
'''
amplitude = math.sqrt(m / 2**n)
return round(math.acos(amplitude) / (2 * math.asin(amplitude)))
def circuit_optimal(
algorithm: QuantumCircuit,
oracle: QuantumOracle,
m: int,
aux_qubits: list[int] = None
) -> QuantumCircuit:
'''Build a quantum circuit implementing the amplitude amplification algorithm.
#### Arguments
algorithm (QuantumCircuit): Circuit that implements the initialization algorithm.
oracle (QuantumOracle): Circuit that implements the oracle.
m (int): (Known) number of solutions.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
#### Returns
QuantumCircuit: Built circuit.
'''
aux_qubits = [] if aux_qubits is None else aux_qubits
assert algorithm.num_qubits == oracle.num_qubits
assert len(aux_qubits) <= algorithm.num_qubits
n = algorithm.num_qubits - len(aux_qubits) # Search qubits only
inc = m > 2**(n-1)
num_iters = __optimal_num_iters(n, m)
return circuit(algorithm, oracle, num_iters, inc, aux_qubits)
def circuit(
algorithm: QuantumCircuit,
oracle: QuantumOracle,
num_iters: int,
inc: bool = False,
aux_qubits: list[int] = None
) -> QuantumCircuit:
'''Build a quantum circuit implementing the amplitude amplification algorithm.
#### Arguments
algorithm (QuantumCircuit): Circuit that implements the initialization algorithm.
oracle (QuantumOracle): Circuit that implements the oracle.
num_iters (int): Number of iterations to perform.
inc (bool): Whether to use an additional qubit for searching (necessary if m > n/2). \
Defaults to False.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
#### Returns
QuantumCircuit: Built circuit.
'''
aux_qubits = [] if aux_qubits is None else aux_qubits
assert algorithm.num_qubits == oracle.num_qubits
assert len(aux_qubits) <= algorithm.num_qubits
n_all = algorithm.num_qubits
n_aux = len(aux_qubits)
n_search = n_all - n_aux
# Add a qubit if there are too many solutions
if inc:
n_all += 1
n_search += 1
# Algorithm
algorithm.name = 'AlgorithmAug'
aug = QuantumRegister(1, 'aug')
algorithm.add_register(aug)
algorithm.h(aug) # Equiprobable superposition
assert algorithm.num_qubits == n_all
# Oracle
c_oracle = oracle.control()
c_oracle.name = 'OracleAug'
oracle.data = []
aug = QuantumRegister(1, 'aug')
oracle.add_register(aug)
oracle.compose(
c_oracle,
[n_all-1] + list(range(n_all-1)),
inplace=True,
)
assert oracle.num_qubits == n_all
# Copy qubit strucure of oracle
circ = copy.deepcopy(oracle)
circ.data = []
circ.name = 'Amp'
# Qubit partitioning
qubits_search = list(filter(
lambda x: not x in aux_qubits,
list(range(n_all))
))
qubits_measure = list(filter(
lambda x: not x in aux_qubits,
list(range(n_all - (1 if inc else 0)))
))
# Initialization
circ.append(algorithm, circ.qubits)
# Iterations
op = GroverOperator(oracle, state_preparation=algorithm,
reflection_qubits=qubits_search).decompose()
op.name = "Q"
for _ in range(num_iters):
circ.append(op, circ.qubits)
# Measurements
result = ClassicalRegister(len(qubits_measure), name='result')
circ.add_register(result)
# Reverse order to match natural expectation
circ.measure(list(reversed(qubits_measure)), result)
return circ
# +----------------------+
# | Algorithm simulation |
# +----------------------+
def __measure_to_model(measurements: str, var_names: list[str]) -> Interpretation:
'''Convert the result of a measurement to a human-readable format with variable names.
#### Arguments
measurements (str): Measured bits.
var_names (list[str]): Ordered list of variable names that the measurements refer to.
#### Return
Interpretation: Solution representation.
'''
assert len(measurements) == len(var_names)
model = set()
for (name, value) in zip(var_names, measurements):
assert value in ('0', '1')
bool_value = value == '1'
model.add((name, bool_value))
return model
def exec_find_one_known_m(
algorithm: QuantumCircuit,
oracle: Oracle,
m: int,
aux_qubits: list[int] = None
) -> tuple[QuantumCircuit, int, Interpretation]:
'''Simulate the amplitude amplification circuit to find one solution to the problem.
#### Arguments
algorithm (QuantumCircuit): Circuit that implements the initialization algorithm.
oracle (Oracle): Pair of classical and quantum oracles.
m (int): (Known) number of solutions.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
#### Return
tuple[QuantumCircuit, int, Interpretation]: Used circuit, number of iterations performed, \
and found solution.
'''
# pylint: disable=too-many-locals
aux_qubits = [] if aux_qubits is None else aux_qubits
(c_oracle, q_oracle) = oracle
# Extract variable names associated to search qubits (from oracle circuit)
var_names = []
qubits = q_oracle.qubits
for (idx, qubit) in zip(range(len(qubits)), qubits):
if not idx in aux_qubits:
reg = q_oracle.find_bit(qubit).registers[0][0]
var_names = var_names + [reg.name]
# Build circuit
circ = circuit_optimal(algorithm, q_oracle, m, aux_qubits)
# Run simulation
model, iters = None, 0
while True:
iters += 1
result = exec_circuit(circ, shots=1)
measurements = list(result.get_counts().keys())[0]
model = __measure_to_model(measurements, var_names)
if c_oracle(model):
break
# Map output to readable format
return (circ, iters, model)
def exec_find_one_unknown_m(
algorithm: QuantumCircuit,
oracle: Oracle,
aux_qubits: list[int] = None,
c: float = 1.5
) -> tuple[list[QuantumCircuit], int, Interpretation]:
'''Exponentially guess the value of m to find one solution to the problem.
#### Arguments
algorithm (QuantumCircuit): Circuit that implements the initialization algorithm.
oracle (Oracle): Pair of classical and quantum oracles.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
c (float): Base of the exponential defining the guess for m.
#### Return
tuple[list[QuantumCircuit], int, Interpretation]: List of used circuits, number of \
iterations performed, and found solution.
'''
# pylint: disable=too-many-locals
aux_qubits = [] if aux_qubits is None else aux_qubits
(c_oracle, q_oracle) = oracle
inc = True # Since we do not know m, we must be the most general possible
random.seed()
# Extract variable names associated to search qubits (from oracle circuit)
var_names = []
qubits = q_oracle.qubits
for (idx, qubit) in zip(range(len(qubits)), qubits):
if not idx in aux_qubits:
reg = q_oracle.find_bit(qubit).registers[0][0]
var_names = var_names + [reg.name]
# Prepare circuit with no amplification iterations
circ_noiter = circuit(copy.deepcopy(algorithm),
copy.deepcopy(q_oracle), 0, inc, aux_qubits)
circs = [circ_noiter]
# Run simulation
model, iters = None, 0
while True:
iters += 1 # `l' in the paper
m = math.ceil(c**iters)
# Step 3
result = exec_circuit(circ_noiter, shots=1)
measurements = list(result.get_counts().keys())[0]
model = __measure_to_model(measurements, var_names)
if c_oracle(model):
break
# Steps 4-7
j = random.randint(1, m)
circ = circuit(copy.deepcopy(algorithm),
copy.deepcopy(q_oracle), j, inc, aux_qubits)
circs.append(circ)
result = exec_circuit(circ, shots=1)
measurements = list(result.get_counts().keys())[0]
model = __measure_to_model(measurements, var_names)
if c_oracle(model):
break
return (circs, iters, model)
|
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_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import torch
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
_ = torch.manual_seed(123456) # suppress output
import numpy as np
num_dim = 2
num_discrete_values = 8
num_qubits = num_dim * int(np.log2(num_discrete_values))
from scipy.stats import multivariate_normal
coords = np.linspace(-2, 2, num_discrete_values)
rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed)
grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))])
prob_data = rv.pdf(grid_elements)
prob_data = prob_data / np.sum(prob_data)
import matplotlib.pyplot as plt
from matplotlib import cm
mesh_x, mesh_y = np.meshgrid(coords, coords)
grid_shape = (num_discrete_values, num_discrete_values)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"})
prob_grid = np.reshape(prob_data, grid_shape)
surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
qc.decompose().draw("mpl")
qc.num_parameters
from qiskit.primitives import Sampler
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
from torch import nn
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
from torch.optim import Adam
lr = 0.01 # learning rate
b1 = 0.7 # first momentum parameter
b2 = 0.999 # second momentum parameter
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(
discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005
)
from IPython.display import clear_output
def plot_training_progress():
# we don't plot if we don't have enough data
if len(generator_loss_values) < 2:
return
clear_output(wait=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
# Generator Loss
ax1.set_title("Loss")
ax1.plot(generator_loss_values, label="generator loss", color="royalblue")
ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta")
ax1.legend(loc="best")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Loss")
ax1.grid()
# Relative Entropy
ax2.set_title("Relative entropy")
ax2.plot(entropy_values)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Relative entropy")
ax2.grid()
plt.show()
import time
from scipy.stats import multivariate_normal, entropy
n_epochs = 50
num_qnn_outputs = num_discrete_values**num_dim
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
start = time.time()
for epoch in range(n_epochs):
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Configure input
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Configure samples
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data)
entropy_values.append(entropy_value)
plot_training_progress()
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
with torch.no_grad():
generated_probabilities = generator().numpy()
fig = plt.figure(figsize=(18, 9))
# Generated CDF
gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape)
ax1 = fig.add_subplot(1, 3, 1, projection="3d")
ax1.set_title("Generated CDF")
ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax1.set_zlim(-0.05, 1.05)
# Real CDF
real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape)
ax2 = fig.add_subplot(1, 3, 2, projection="3d")
ax2.set_title("True CDF")
ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax2.set_zlim(-0.05, 1.05)
# Difference
ax3 = fig.add_subplot(1, 3, 3, projection="3d")
ax3.set_title("Difference between CDFs")
ax3.plot_surface(
mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm
)
ax3.set_zlim(-0.05, 0.1)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
import numpy as np
pi = np.pi
IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
def rz(rotation):
circuit = QuantumCircuit(q,c)
circuit.h(q[0]) # Hadamard gate
circuit.rz(rotation,q[0]) # RZ gate
circuit.h(q[0]) # Hadamard gate
circuit.measure(q,c) # Qubit Measurment
print(circuit)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
rotation = 0
rz(rotation)
rotation = pi/2
rz(rotation)
rotation = pi
rz(rotation)
|
https://github.com/entropicalabs/OpenQAOA-Challenge---Qiskit-Fall-Fest-2022-Mexico
|
entropicalabs
|
# Methods to use in the notebook
%load_ext autoreload
%autoreload 2
from IPython.display import clear_output
# Libaries to manipulate, print, plot, and save the data.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Random generator for the problem
from random import seed,randrange, randint
# OpenQAOA libraries to design, execute the algorithm in different backends and optimisers
from openqaoa.problems.problem import NumberPartition
from openqaoa.workflows.optimizer import QAOA
from openqaoa.devices import create_device
from openqaoa.optimizers.qaoa_optimizer import available_optimizers
from openqaoa.utilities import ground_state_hamiltonian
# To reproduce the code and make this a problem that has optimal states in the bipartition problem,
# the following seed is used
seed(9)
# Generate four random number with a range between (1,5) callend the variable in_list
in_list = [randrange(1, 5, 1) for i in range(4)]
in_list
qubo = NumberPartition(in_list).get_qubo_problem()
qubo.asdict()
# In OpenQAOA you can use different devices either local
# or from different cloud backends such as Qiskit, Pyquil.
sim = create_device(location='local', name='vectorized')
# Init the object QAOA and certain of its properties can be modified
q = QAOA()
q.set_device(sim)
q.compile(qubo)
# Execute the quantum algorithm
q.optimize()
print("solution bitstring: ",q.results.most_probable_states['solutions_bitstrings'])
print("ground state: ",ground_state_hamiltonian(q.cost_hamil)[1])
optimisers = available_optimizers()['scipy']+ available_optimizers()['custom_scipy_gradient']
optimisers
jac = ['finite_difference', 'param_shift','grad_spsa', 'stoch_param_shift']
hess = jac[0]
|
https://github.com/suvoooo/Qubits-Qiskit
|
suvoooo
|
!pip3 install qiskit
import qiskit as q
!pip3 install pylatexenc
import math
import numpy as np
statevec_sim = q.Aer.get_backend("statevector_simulator")
def statevec_exec(circ):
statevec = q.execute(circ, backend=statevec_sim).result().get_statevector()
return statevec
# qr = q.QuantumRegister(2, name="q")
# cr = q.ClassicalRegister(2, name="cr")
def build_circ(num_qbits, num_cbits):
qr = q.QuantumRegister(num_qbits)
cr = q.ClassicalRegister(num_cbits)
final_circ = q.QuantumCircuit(qr, cr)
return final_circ, qr, cr
# simple_circuit, qr, cr = build_circ(2)
# simple_circuit.draw()
def h_gates(qcirc, a, b): # 2 inputs and h gates in parallel
qcirc.h(a)
qcirc.h(b)
#### start of by applying a rotation around y axis
simple_circuit, qr, cr = build_circ(2, 2)
simple_circuit.ry(np.pi/6, qr[0])
simple_circuit.ry(np.pi/6, qr[1])
simple_circuit_statevec = statevec_exec(simple_circuit)
simple_circuit.measure([0,1], [0,1])
simple_circuit.draw()
q.visualization.plot_bloch_multivector(simple_circuit_statevec)
qasm_sim = q.Aer.get_backend('qasm_simulator')
orig_counts = q.execute(simple_circuit, backend=qasm_sim, shots=1024).result().get_counts()
q.visualization.plot_histogram([orig_counts], legend=['output: org qs'])
hadamard_front, qr1, cr1 = build_circ(2, 2)
hadamard_front.draw()
h_gates(hadamard_front, qr1[0], qr1[1])
hadamard_front.ry(math.pi/6, qr1[0])
hadamard_front.ry(math.pi/6, qr1[1])
hadamard_front_statevec = statevec_exec(hadamard_front)
hadamard_front.measure([0,1], [0,1])
hadamard_front.draw()
q.visualization.plot_bloch_multivector(hadamard_front_statevec)
#qasm_sim = q.Aer.get_backend('qasm_simulator')
hfront_counts = q.execute(hadamard_front, backend=qasm_sim, shots=1024).result().get_counts()
q.visualization.plot_histogram([hfront_counts], legend=['output: hfront qs'])
hadamard_front_back, qr2, cr2 = build_circ(2, 2)
h_gates(hadamard_front_back, qr2[0], qr2[1])
hadamard_front_back.ry(math.pi/6, [qr2[0]])
hadamard_front_back.ry(math.pi/6, [qr2[1]])
h_gates(hadamard_front_back, qr2[0], qr2[1])
#hadamard_front.barrier()
hadamard_front_back_statevec = statevec_exec(hadamard_front_back)
hadamard_front_back.measure([0,1], [0,1])
hadamard_front_back.draw()
q.visualization.plot_bloch_multivector(hadamard_front_back_statevec)
hfront_back_counts = q.execute(hadamard_front_back, backend=qasm_sim, shots=1024).result().get_counts()
q.visualization.plot_histogram([hfront_back_counts], legend=['output: hfront-back qs'])
num_input = 3
balanced_circuit = q.QuantumCircuit(num_input+1) # num_input + one more where qubit is initialized to |1>
### we can create the balanced oracle by applying CNOT gate to every input and/or by wrapping the second CNOT gate with X gates
x_str = "010" # this is for iterating over the string and add X gate when there's 1.
for n in range(len(x_str)):
if x_str[n]=="1":
balanced_circuit.x(n)
balanced_circuit.draw()
### add control not for all the inputs
balanced_circuit.barrier()
for i in range(num_input):
balanced_circuit.cx(i, num_input)
balanced_circuit.barrier()
balanced_circuit.draw()
### add another x gate
for n in range(len(x_str)):
if x_str[n]=="1":
balanced_circuit.x(n)
balanced_circuit.draw()
init_circuit, qr, cr = build_circ(num_input+1, num_input)
### all the input qubits are initialized to 0, while the target qubit is initialized to 1.
for n in range(num_input):
init_circuit.h(n)
init_circuit.x(qr[num_input]) # state is now initialized to |1>
init_circuit.h(qr[num_input])
init_circuit.draw()
complete_circuit = init_circuit.compose(balanced_circuit)
complete_circuit.draw()
## now we add h gates again to the input qubits
for n in range(num_input):
complete_circuit.h(n)
complete_circuit.barrier()
# Now we measure the input qubits
for n in range(num_input):
complete_circuit.measure(n, n)
complete_circuit.draw()
from google.colab import drive
drive.mount('/content/drive')
path = '/content/drive/My Drive/'
style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10}
complete_circuit.draw(output='mpl',scale=0.8, style=style, filename=path+'DJ_Circ_balanced.png')
qasm_sim = q.Aer.get_backend('qasm_simulator')
balanced_counts = q.execute(complete_circuit, backend=qasm_sim, shots=1024).result().get_counts()
q.visualization.plot_histogram([balanced_counts], legend=['output: balanced'])
### let's use IBM Quantum Computer to simulate this,
from qiskit import IBMQ
IBMQ.save_account('find your token')
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_athens') # check which computer has 0 jobs on queue
job = q.execute(complete_circuit, backend=qcomp)
q_result = job.result()
q.visualization.plot_histogram(q_result.get_counts(complete_circuit))
|
https://github.com/CapacitorSet/qiskit-fast-shor
|
CapacitorSet
|
"""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/QuantumComputingKorea/QiskitRuntime
|
QuantumComputingKorea
|
from IPython.display import Image
Image("runtime.png")
from IPython.display import HTML
HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/1kRfHNUbkrg?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>')
#!pip install 'qiskit[all]'
#!pip install qiskit-ibm-runtime
#!pip install matplotlib
#!pip install pylatexenc
from qiskit_ibm_runtime import IBMRuntimeService
# Save account on disk. if you need to overwrite the account info, please add overwrite=True)
IBMRuntimeService.save_account(auth="cloud", token="Your Token", instance="your_crn", overwrite=True)
service = IBMRuntimeService()
service.pprint_programs()
service.backends()
from qiskit.test.reference_circuits import ReferenceCircuits
program_inputs = {'iterations': 1}
options = {"backend_name": "ibmq_qasm_simulator"}
job = service.run(program_id="hello-world",
#options=options,
inputs=program_inputs
)
print(f"job id: {job.job_id}")
result = job.result()
print(result)
from qiskit import QuantumCircuit
N = 10
qc = QuantumCircuit(N)
qc.h(0)
for kk in range(0, N -1):
qc.cx(kk, kk + 1)
qc.measure_all()
qc.draw('mpl', fold=-1)
from qiskit import Aer, transpile
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend('aer_simulator_statevector')
circ = transpile(qc, simulator)
job_statevector = simulator.run(circ, shots=20000)
counts_statevector = job_statevector.result().get_counts(0)
plot_histogram(counts_statevector)
from qiskit.test.mock import FakeMontreal
fake_backend = FakeMontreal()
from qiskit.tools.jupyter import *
fake_backend
job_noisy = fake_backend.run(circ, shots=20000)
counts_moisy = job_noisy.result().get_counts(0)
plot_histogram(counts_moisy)
service = IBMRuntimeService()
# Specify the program inputs here.
program_inputs = {
"circuits": qc,
"circuit_indices": [0],
# "shots":20000
}
# Specify the backend name.
job = service.run(
program_id="sampler",
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
result = job.result()
print(result)
plot_histogram(result.get('quasi_dists'))
# Specify the program inputs here.
program_inputs = {
"circuits": qc,
"circuit_indices": [0],
# "shots":2048
}
# Specify the backend name.
options = {"backend_name": "ibmq_qasm_simulator"}
job = service.run(
program_id="sampler",
options=options,
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
qasm_result = job.result()
print(qasm_result)
plot_histogram(qasm_result.get('quasi_dists'))
IBMRuntimeService.save_account(auth="cloud", token="your token", instance="your _ crn", overwrite=True)
service = IBMRuntimeService()
service.backends()
# Specify the program inputs here.
program_inputs = {
"circuits": qc,
"circuit_indices": [0],
# "shots":10000
}
# Specify the backend name.
options = {"backend_name": "ibm_algiers"}
job = service.run(
program_id="sampler",
options=options,
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
real_result = job.result()
print(real_result)
plot_histogram(real_result.get('quasi_dists'))
|
https://github.com/ionq-samples/getting-started
|
ionq-samples
|
%%capture
# First, we install the essential libraries to our current Python runtime.
# "%%capture" (above) captures and in this case, hides the output of this
# cell, so you can comment it out if you need help debugging this step.
%pip install projectq
import os
from getpass import getpass
import projectq.setups.ionq
from projectq import MainEngine
from projectq.backends import IonQBackend
from projectq.libs.hist import histogram
from projectq.ops import H, CNOT, Measure
import matplotlib.pyplot as plt
# Before you begin, get your API key from https://cloud.ionq.com/settings/keys
# If your API key is stored as "IONQ_API_KEY" in your local environment, this
# should find it. Otherwise you'll be prompted to enter your API key manually.
token = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ')
# We need to specify the device where the circuit will be executed. In this
# case we're using the `ionq_simulator`, but if you have QPU access you can
# specify it here to run the job on a QPU directly.
device = 'ionq_simulator'
backend = IonQBackend(token=token, device=device)
compiler_engines = projectq.setups.ionq.get_engine_list(token=token, device=device)
eng = MainEngine(backend, engine_list=compiler_engines)
qubit1 = eng.allocate_qubit() # Allocate a quantum register with 1 qubit
qubit2 = eng.allocate_qubit()
H | qubit1 # Apply a Hadamard gate
CNOT | (qubit1, qubit2) # Entangle the qubits
Measure | qubit1 # Measure the qubit
Measure | qubit2
eng.flush() # Flush all gates (and execute measurements)
histogram(eng.backend, qubit1 + qubit2)
plt.show()
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
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
# 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")
# 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)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
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>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-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")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
job_ids = \
["624e8c85aacb9bd9c75f4da1",
"624e8c894b515208aa7c6ae2",
"624e8c8ba5d4eeac4977ccf3",
"624e8c8ccfe45c1d4ae5a357",
"624e8c8ef65d78307439029b",
"624e8c9173968c1c2307b2c9",
"624e8c93caa26524ecf199a9",
"624e8c95aacb9b60c25f4da3"]
# 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)
print('Job ID', cal_job.job_id())
jobs = []
for job_id in job_ids:
jobs.append(backend.retrieve_job(job_id))
cal_job_id = "624e8c97a5d4ee882477ccf4"
cal_job = backend.retrieve_job(cal_job_id)
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_results = cal_job.result()
print("retrieved cal_results")
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for i, job in enumerate(jobs):
mit_results.append( meas_fitter.filter.apply(job.result()) )
print("retrieved", i, "th 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^One^Zero).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
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)))
|
https://github.com/matheusvtna/Grover-Algorithm
|
matheusvtna
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
"""Performance Analysis of 3 Qubit Code under Bit Flip Error"""
import noise
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit import Aer, execute
from qiskit.quantum_info import partial_trace, state_fidelity
from qiskit.quantum_info import DensityMatrix, Kraus
from qiskit.visualization import plot_histogram, plot_bloch_vector
from three_qubit_code import ThreeQubitCode
# Parameters
error_prob = 0.05
theta = np.pi/3
phi = np.pi/4
# Initialize error correcting circuit, backend and noise model
qasm = Aer.get_backend('qasm_simulator')
svsm = Aer.get_backend('statevector_simulator')
unit = Aer.get_backend('unitary_simulator')
noise_model = noise.bit_flip_noise(error_prob)
qecc = ThreeQubitCode()
# Visualize parameters
print(noise_model)
qecc.visualize()
# Define test circuit and input state
output = ClassicalRegister(3)
circ = QuantumCircuit(qecc.code, qecc.syndrm, output)
circ.ry(theta, qecc.code[0])
circ.rz(phi, qecc.code[0])
plot_bloch_vector([np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi), np.cos(theta)], title="Input State")
plt.show()
# Define final measurement circuit
meas = QuantumCircuit(qecc.code, qecc.syndrm, output)
meas.measure(qecc.code, output)
# QASM simulation w/o error correction
job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + meas, backend=qasm, noise_model=noise_model,
basis_gates=noise_model.basis_gates)
counts_noisy = job.result().get_counts()
# QASM simulation with error correction
job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_model,
basis_gates=noise_model.basis_gates)
counts_corrected = job.result().get_counts()
# Plot QASM simulation data
plot_histogram([counts_noisy, counts_corrected],
title='3-Qubit Error Correction $(P_{error} = ' + str(error_prob) + ')$',
legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False)
plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15)
plt.show()
# Initialize fidelity simulation objects
job = execute(circ + qecc.encoder_ckt, backend=svsm)
init_state = DensityMatrix(job.result().get_statevector())
job = execute(qecc.syndrome_ckt, backend=unit)
syndrome_op = Kraus(job.result().get_unitary())
# Initialize fidelity simulation parameters
p_error = [0.05 * i for i in range(11)]
f1 = []
f2 = []
# Evolve initial state
for p in p_error:
# Build noise channel
bit_flip_channel = Kraus([[[0, np.sqrt(p)],
[np.sqrt(p), 0]],
[[np.sqrt(1-p), 0],
[0, np.sqrt(1-p)]]])
bit_flip_channel = bit_flip_channel.tensor(bit_flip_channel).tensor(bit_flip_channel)
bit_flip_channel = bit_flip_channel.expand(Kraus(np.eye(2))).expand(Kraus(np.eye(2)))
# Apply channels
corrupted_state = DensityMatrix(init_state.evolve(bit_flip_channel))
corrected_state = DensityMatrix(corrupted_state.evolve(syndrome_op))
corrected_state = DensityMatrix(corrected_state.evolve(qecc.correction_ckt))
# Trace out syndrome
ini = DensityMatrix(partial_trace(init_state, [3, 4]))
corrupted_state = DensityMatrix(partial_trace(corrupted_state, [3, 4]))
corrected_state = DensityMatrix(partial_trace(corrected_state, [3, 4]))
# Record results
f1.append(state_fidelity(ini, corrupted_state))
f2.append(state_fidelity(ini, corrected_state))
# Plot fidelity
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.plot(p_error, f1, label='w/o code')
ax.plot(p_error, f2, label='with code')
ax.set_title("$Fidelity$ vs $P_{error}$")
ax.set_xlabel('$P_{error}$')
ax.set_ylabel('$Fidelity$')
ax.set_ylabel('$Fidelity$')
ax.legend()
plt.xlim(0, 0.5)
plt.ylim(0, 1)
plt.grid()
plt.show()
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the decompose pass"""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler.passes import Decompose
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import HGate, CCXGate, U2Gate
from qiskit.quantum_info.operators import Operator
from qiskit.test import QiskitTestCase
class TestDecompose(QiskitTestCase):
"""Tests the decompose pass."""
def setUp(self):
super().setUp()
# example complex circuit
# ┌────────┐ ┌───┐┌─────────────┐
# q2_0: ┤0 ├────────────■──┤ H ├┤0 ├
# │ │ │ └───┘│ circuit-57 │
# q2_1: ┤1 gate1 ├────────────■───────┤1 ├
# │ │┌────────┐ │ └─────────────┘
# q2_2: ┤2 ├┤0 ├──■──────────────────────
# └────────┘│ │ │
# q2_3: ──────────┤1 gate2 ├──■──────────────────────
# │ │┌─┴─┐
# q2_4: ──────────┤2 ├┤ X ├────────────────────
# └────────┘└───┘
circ1 = QuantumCircuit(3)
circ1.h(0)
circ1.t(1)
circ1.x(2)
my_gate = circ1.to_gate(label="gate1")
circ2 = QuantumCircuit(3)
circ2.h(0)
circ2.cx(0, 1)
circ2.x(2)
my_gate2 = circ2.to_gate(label="gate2")
circ3 = QuantumCircuit(2)
circ3.x(0)
q_bits = QuantumRegister(5)
qc = QuantumCircuit(q_bits)
qc.append(my_gate, q_bits[:3])
qc.append(my_gate2, q_bits[2:])
qc.mct(q_bits[:4], q_bits[4])
qc.h(0)
qc.append(circ3, [0, 1])
self.complex_circuit = qc
def test_basic(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_none(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_only_h(self):
"""Test to decompose a single H, without the rest"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ["cx", "u2"])
def test_decompose_toffoli(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(CCXGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 1-qubit gates with a conditional."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag)
def test_decompose_oversized_instruction(self):
"""Test decompose on a single-op gate that doesn't use all qubits."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3440
qc1 = QuantumCircuit(2)
qc1.x(0)
gate = qc1.to_gate()
qc2 = QuantumCircuit(2)
qc2.append(gate, [0, 1])
output = qc2.decompose()
self.assertEqual(qc1, output)
def test_decomposition_preserves_qregs_order(self):
"""Test decomposing a gate preserves it's definition registers order"""
qr = QuantumRegister(2, "qr1")
qc1 = QuantumCircuit(qr)
qc1.cx(1, 0)
gate = qc1.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate, qr2)
expected = QuantumCircuit(qr2)
expected.cx(1, 0)
self.assertEqual(qc2.decompose(), expected)
def test_decompose_global_phase_1q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(1)
qc1.rz(0.1, 0)
qc1.ry(0.5, 0)
qc1.global_phase += pi / 4
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_2q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(2, global_phase=pi / 4)
qc1.rz(0.1, 0)
qc1.rxx(0.2, 0, 1)
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_1q_composite(self):
"""Test decomposition of circuit with global phase in a composite gate."""
circ = QuantumCircuit(1, global_phase=pi / 2)
circ.x(0)
circ.h(0)
v = circ.to_gate()
qc1 = QuantumCircuit(1)
qc1.append(v, [0])
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_only_h_gate(self):
"""Test decomposition parameters so that only a certain gate is decomposed."""
circ = QuantumCircuit(2, 1)
circ.h(0)
circ.cz(0, 1)
decom_circ = circ.decompose(["h"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 2)
self.assertEqual(dag.op_nodes()[0].name, "u2")
self.assertEqual(dag.op_nodes()[1].name, "cz")
def test_decompose_only_given_label(self):
"""Test decomposition parameters so that only a given label is decomposed."""
decom_circ = self.complex_circuit.decompose(["gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 7)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "mcx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertRegex(dag.op_nodes()[6].name, "circuit-")
def test_decompose_only_given_name(self):
"""Test decomposition parameters so that only given name is decomposed."""
decom_circ = self.complex_circuit.decompose(["mcx"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 13)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].op.label, "gate2")
self.assertEqual(dag.op_nodes()[2].name, "h")
self.assertEqual(dag.op_nodes()[3].name, "cu1")
self.assertEqual(dag.op_nodes()[4].name, "rcccx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertEqual(dag.op_nodes()[6].name, "h")
self.assertEqual(dag.op_nodes()[7].name, "cu1")
self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[9].name, "h")
self.assertEqual(dag.op_nodes()[10].name, "c3sx")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertRegex(dag.op_nodes()[12].name, "circuit-")
def test_decompose_mixture_of_names_and_labels(self):
"""Test decomposition parameters so that mixture of names and labels is decomposed"""
decom_circ = self.complex_circuit.decompose(["mcx", "gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 15)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "h")
self.assertEqual(dag.op_nodes()[5].name, "cu1")
self.assertEqual(dag.op_nodes()[6].name, "rcccx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "h")
self.assertEqual(dag.op_nodes()[9].name, "cu1")
self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertEqual(dag.op_nodes()[12].name, "c3sx")
self.assertEqual(dag.op_nodes()[13].name, "h")
self.assertRegex(dag.op_nodes()[14].name, "circuit-")
def test_decompose_name_wildcards(self):
"""Test decomposition parameters so that name wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["circuit-*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertRegex(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "x")
def test_decompose_label_wildcards(self):
"""Test decomposition parameters so that label wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["gate*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertEqual(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertRegex(dag.op_nodes()[8].name, "circuit-")
def test_decompose_empty_gate(self):
"""Test a gate where the definition is an empty circuit is decomposed."""
empty = QuantumCircuit(1)
circuit = QuantumCircuit(1)
circuit.append(empty.to_gate(), [0])
decomposed = circuit.decompose()
self.assertEqual(len(decomposed.data), 0)
def test_decompose_reps(self):
"""Test decompose reps function is decomposed correctly"""
decom_circ = self.complex_circuit.decompose(reps=2)
decomposed = self.complex_circuit.decompose().decompose()
self.assertEqual(decom_circ, decomposed)
def test_decompose_single_qubit_clbit(self):
"""Test the decomposition of a block with a single qubit and clbit works.
Regression test of Qiskit/qiskit-terra#8591.
"""
block = QuantumCircuit(1, 1)
block.h(0)
circuit = QuantumCircuit(1, 1)
circuit.append(block, [0], [0])
decomposed = circuit.decompose()
self.assertEqual(decomposed, block)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.