回路記述
import
from blueqat import Circuit
回路作成
Circuit().h[0] # hadamard
Circuit.rx(x)[i] # x-deg. Rx gate acts on i-th qubit
Circuit.cnot()[0,1] # c-not
Circuit().h[0].m[:] # hadamard+measure
回路の合成
subcircuit0 = data_encoding(data0)
subcircuit1 = data_encoding(data1).dagger()
circuit = subcircuit0 + subcircuit1 # add
回路実行
Circuit().h[0].n[:].run() # tensor-network simulator (returns samples)
Circuit().h[0].n[:].run(backend="numpy") # state-vector simulator (returns a vector)
Circuit().h[0].n[:].run(backend="draw") # circuit drawing
statevector(array)をケットベクトルで書く
import math
def print_Zbasis_expression(statevector):
nqubit = int(math.log2(np.size(statevector)))
for i in range(2**nqubit):
print('+({:.2f})*|{number:0{width}b}>'.format(statevector[i],number=i,width=nqubit),end='')
State_out = Circuit(1).h[0].run(backend="numpy")
print_Zbasis_expression(State_out)
+(0.71+0.00j)*|0>+(0.71+0.00j)*|1>
blueqat on qiskit simulator
circ.run_with_ibmq(returns='draw', output='mpl')
または以下の方法。
https://github.com/Blueqat/Blueqat-tutorials/blob/master/tutorial-ja/702_backend1_ja.ipynb
import warnings
from collections import Counter
from blueqat.backends.qasm_parser_backend_generator import generate_backend
def _qasm_runner_qiskit(qasm, qiskit_backend=None, shots=None, returns=None, **kwargs):
if returns is None:
returns = "shots"
elif returns not in ("shots", "draw", "_exception",
"qiskit_circuit", "qiskit_job", "qiskit_result"):
raise ValueError("`returns` shall be None, 'shots', 'draw', " +
"'qiskit_circuit', 'qiskit_job', 'qiskit_result' or '_exception'")
import_error = None
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from qiskit import Aer, QuantumCircuit, execute
except Exception as e:
import_error = e
if import_error:
if returns == "_exception":
return e
if isinstance(import_error, ImportError):
raise ImportError("Cannot import qiskit. To use this backend, please install qiskit." +
" `pip install qiskit`.")
else:
raise ValueError("Unknown error raised when importing qiskit. To get exception, " +
'run this backend with arg `returns="_exception"`')
else:
if returns == "_exception":
return None
qk_circuit = QuantumCircuit.from_qasm_str(qasm)
if returns == "qiskit_circuit":
return qk_circuit
if returns == "draw":
return qk_circuit.draw(**kwargs)
if shots is None:
shots = 1024
if qiskit_backend is None:
qiskit_backend = Aer.get_backend("qasm_simulator")
job = execute(qk_circuit, backend=qiskit_backend, shots=shots, **kwargs)
if returns == "qiskit_job":
return job
result = job.result()
if returns == "qiskit_result":
return result
counts = Counter({bits[::-1]: val for bits, val in result.get_counts().items()})
return counts
ibmq_backend = generate_backend(_qasm_runner_qiskit)
from blueqat import BlueqatGlobalSetting
BlueqatGlobalSetting.register_backend("myibmq", ibmq_backend)
Circuit().h[0].m[:].run(backend="myibmq",returns="draw",output='mpl')
plot histogram
プロットする
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
def myplot_histogram(sv,n,figsize=(20,10),fontsize=24):
probs = np.abs(sv)**2
## z方向に射影測定した時に得られる可能性があるビット列
z_basis = [format(i,"b").zfill(n) for i in range(probs.size)]
plt.figure(figsize=figsize)
plt.xlabel("states",fontsize=fontsize)
plt.ylabel("probability(%)",fontsize=fontsize)
plt.xticks(fontsize=fontsize)
plt.yticks(fontsize=fontsize)
plt.bar(z_basis, probs*100)
plt.show()
Applications
Quantum kernel
from blueqat import Circuit
import numpy as np
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
def data_encoding(data):
circuit = Circuit(2)
for i,x in enumerate(data):
circuit.rx(x)[i]
return circuit
def make_circuit(data0,data1):
subcircuit0 = data_encoding(data0)
subcircuit1 = data_encoding(data1).dagger()
circuit = subcircuit0 + subcircuit1
return circuit
def kernel(data0,data1,shots=1024):
circuit = make_circuit(data0,data1)
sv = circuit.run(backend="numpy")
prob = np.abs(sv)**2
kernel_value = prob[0]
return kernel_value
def kernel_matrix(A, B):
"""Compute the matrix whose entries are the kernel
evaluated on pairwise data from sets A and B."""
return np.array([[kernel(a, b) for b in B] for a in A])
np.random.seed(42)
X, y = load_iris(return_X_y=True)
# pick inputs and labels from the first two classes only,
# corresponding to the first 100 samples
X = X[0:100,0:2]
y = y[0:100]
# scaling the inputs is important since the embedding we use is periodic
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
# scaling the labels to -1, 1 is important for the SVM and the
# definition of a hinge loss
y_scaled = 2 * (y - 0.5)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled)
mat = kernel_matrix(X_train,X_train)
fig, ax = plt.subplots()
ax.imshow(mat)
plt.show()
svm = SVC(kernel=kernel_matrix).fit(X_train, y_train)
predictions = svm.predict(X_test)
accuracy_score(predictions, y_test)