repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
# Basis encoding example with PennyLane
import pandas as pd
import pennylane as qml
from pennylane import numpy as np
# import the template
from pennylane.templates.layers import StronglyEntanglingLayers
from sklearn.utils import shuffle
from sklearn.preprocessing import normalize
from pennylane.templates.embeddings import AngleEmbedding, BasisEmbedding, AmplitudeEmbedding, DisplacementEmbedding
from pennylane.init import strong_ent_layers_uniform
np.random.seed(42)
# Constants
DATA_PATH = "../../Data/Processed/data.csv"
num_qubits = 4
data = pd.read_csv(DATA_PATH)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
X = normalize(X)
print(X[:5])
device = qml.device("default.qubit", wires=num_qubits)
@qml.qnode(device)
def circuit(data):
for i in range(num_qubits):
# Create superposition
qml.Hadamard(wires=i)
AngleEmbedding(features=data, wires=range(num_qubits), rotation="Y")
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3))
circuit(X[0])
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
from qiskit.ml.datasets import *
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
# constants
n = 4
RANDOM_STATE = 42
LR = 1e-3
class_labels = ['yes', 'no']
def normalizeData(DATA_PATH = "../../Data/Processed/data.csv"):
"""
Normalizes the data
"""
# Reads the data
data = pd.read_csv(DATA_PATH)
data = shuffle(data, random_state=RANDOM_STATE)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
X = normalize(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE)
return X_train, X_test, Y_train, Y_test
X_train, X_test, Y_train, Y_test = normalizeData()
sv = Statevector.from_label('0' * n)
feature_map = ZZFeatureMap(n, reps=1)
var_form = RealAmplitudes(n, reps=1)
circuit = feature_map.combine(var_form)
circuit.draw(output='mpl', filename="overallcircuit.png")
def get_data_dict(params, x):
parameters = {}
for i, p in enumerate(feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(bit_string, class_labels):
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return class_labels[1]
else:
return class_labels[0]
def return_probabilities(counts, class_labels):
shots = sum(counts.values())
result = {class_labels[0]: 0,
class_labels[1]: 0}
for key, item in counts.items():
label = assign_label(key, class_labels)
result[label] += counts[key]/shots
return result
def classify(x_list, params, class_labels):
qc_list = []
for x in x_list:
circ_ = circuit.assign_parameters(get_data_dict(params, x))
qc = sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = return_probabilities(counts, class_labels)
probs += [prob]
return probs
def mse_cost(probs, expected_label):
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
return np.square(np.subtract(actual,pred)).mean()
cost_list = []
def cost_function(X, Y, class_labels, params, shots=100, print_value=False):
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [class_labels[0]]
elif label == 1:
training_labels += [class_labels[1]]
probs = classify(training_samples, params, class_labels)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
cost_list.append(cost)
return cost
cost_list = []
optimizer = ADAM(maxiter=100, )
# define objective function for training
objective_function = lambda params: cost_function(X_train, Y_train, class_labels, params, print_value=True)
# randomly initialize the parameters
np.random.seed(RANDOM_STATE)
init_params = 2*np.pi*np.random.rand(n*(1)*2)
# train classifier
opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
print()
print('opt_params:', opt_params)
print('opt_value: ', value)
fig = plt.figure()
plt.plot(range(0,901,1), cost_list)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title("ADAM Cost value against steps")
plt.show()
fig.savefig('../../Output/Figures/costvssteps.jpeg')
def test_model(X, Y, class_labels, params):
accuracy = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
probs = classify(training_samples, params, class_labels)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y_test[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y_test[i] == 1):
accuracy += 1
accuracy /= len(Y_test)
print("Test accuracy: {}\n".format(accuracy))
test_model(X_test, Y_test, class_labels, opt_params)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("../../Data/Processed/costs.csv")
df.columns = ['Spec', "CostValues"]
df.head(1)
df['Spec']
def check_lowest_cost():
"""
Checks the configs which attained the lowest sost
"""
cost = []
lowest_cost = []
for i in range(df.shape[0]):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
lowest_cost.append(data[len(data) - 1])
lowest_cost = sorted(lowest_cost)[:80]
# for m in lowest_cost:
for i in range(df.shape[0]):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
# if float(m) == float(data[len(data) - 1]):
# print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
cost.append(data[len(data) - 1])
print(len(cost))
df['exel'] = cost
df.to_excel("n.xlsx")
check_lowest_cost()
# Plotting all
for i in range(df.shape[0]):
fig = plt.figure()
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
plt.plot(range(0, len(data), 1), data)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(str(df['Spec'][i]))
plt.show()
path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
# fig.savefig(path)
def plot_individual_optimizers(Optimizers):
for opt in Optimizers:
max_iter = 0
fig = plt.figure(figsize=(20,20))
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
if len(data) >= max_iter:
max_iter = len(data)
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if max_iter >= len(data):
temp = np.full((max_iter, ), data[len(data) -1])
temp[:len(data)] = data
data = temp
plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(opt)
plt.legend()
plt.show()
plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])
def plot_increase_vdepth(optimizer, featuremap, reps, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
plt.show()
def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
plt.show()
plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")
plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 2, 4]:
plot_increase_vdepth(opt, fmap, fdepth, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 3, 5]:
plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
from qiskit.ml.datasets import *
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
# constants
n = 4
RANDOM_STATE = 42
LR = 1e-3
class_labels = ['yes', 'no']
def normalizeData(DATA_PATH = "../../Data/Processed/data.csv"):
"""
Normalizes the data
"""
# Reads the data
data = pd.read_csv(DATA_PATH)
data = shuffle(data, random_state=RANDOM_STATE)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
X = normalize(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE)
return X_train, X_test, Y_train, Y_test
X_train, X_test, Y_train, Y_test = normalizeData()
feature_map = ZZFeatureMap(n, reps=1)
feature_map.draw(output="mpl", filename="../../Output/Figures/ZZFeaturemap.png")
feature_map = ZFeatureMap(n, reps=1)
feature_map.draw(output="mpl", filename="../../Output/Figures/ZFeaturemap.png")
feature_map = PauliFeatureMap(n, reps=1)
feature_map.draw(output="mpl", filename="../../Output/Figures/PauliFeaturemap.png")
var_form = RealAmplitudes(n, reps=1)
var_form.draw(output="mpl", filename="../../Output/Figures/RealAmplitudes.png")
sv = Statevector.from_label('0' * n)
feature_map = ZZFeatureMap(n, reps=1)
feature_map.barrier()
var_form = RealAmplitudes(n, reps=1)
circuit = feature_map.combine(var_form)
circuit.draw(output="mpl", filename="../../Output/Figures/overallcircuit.png")
def get_data_dict(params, x):
parameters = {}
for i, p in enumerate(feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(bit_string, class_labels):
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return class_labels[1]
else:
return class_labels[0]
data = X_train[0]
params = np.array([0.1, 1.2, 0.02, 0.1, 0.1, 1.2, 0.02, 0.1])
circ_ = circuit.assign_parameters(get_data_dict(params, data))
circ_.draw(plot_barriers=True, output="mpl", filename="../../Output/Figures/parameterisedcircuit.png")
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as pp
from sklearn.datasets import load_wine
%matplotlib inline
# Constants
DATA_PATH = "../../Data/Raw/data.csv"
CLEAN_DATA_PATH = "../../Data/Processed/winedata.csv"
raw_data = load_wine()
features = pd.DataFrame(data=raw_data['data'],columns=raw_data['feature_names'])
data = features
data['target']=raw_data['target']
data['class']=data['target'].map(lambda ind: raw_data['target_names'][ind])
data.head()
data.shape
data.columns
print(raw_data['DESCR'])
data.info()
data.describe()
def check_unique(df):
""""
Checks the unique value in each column
:param df: The dataframe
"""
for col in df.columns:
unique = df[col].unique()
print("Column: {} has {} unique values\n".format(col, unique))
check_unique(data)
fig = plt.figure()
sns.countplot(x="target", data=data, palette="gist_rainbow_r")
plt.xlabel("Heart disease (0 = have, 1 = don't)")
plt.title("Target distribution")
plt.show()
fig.savefig("../../Output/Figures/targetdist.png", )
data = data[data['class'] != 'class_2']
data.duplicated().sum()
data.drop_duplicates(inplace=True)
data.drop('target', axis=1).corrwith(data['target']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target")
pp.ProfileReport(df=data, dark_mode=True, explorative=True)
data = data[['alcohol', 'flavanoids', 'color_intensity', 'proline', 'target']]
data.to_csv(CLEAN_DATA_PATH, index=False)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
from qiskit.ml.datasets import *
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
# constants
n = 4
RANDOM_STATE = 42
LR = 1e-3
class_labels = ['yes', 'no']
def normalizeData(DATA_PATH = "../../Data/Processed/winedata.csv"):
"""
Normalizes the data
"""
# Reads the data
data = pd.read_csv(DATA_PATH)
data = shuffle(data, random_state=RANDOM_STATE)
X, Y = data[['alcohol', 'flavanoids', 'color_intensity', 'proline']].values, data['target'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE)
return X_train, X_test, Y_train, Y_test
X_train, X_test, Y_train, Y_test = normalizeData()
sv = Statevector.from_label('0' * n)
feature_map = ZZFeatureMap(n, reps=1)
var_form = RealAmplitudes(n, reps=1)
circuit = feature_map.combine(var_form)
circuit.draw(output='mpl')
def get_data_dict(params, x):
parameters = {}
for i, p in enumerate(feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(bit_string, class_labels):
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return class_labels[1]
else:
return class_labels[0]
def return_probabilities(counts, class_labels):
shots = sum(counts.values())
result = {class_labels[0]: 0,
class_labels[1]: 0}
for key, item in counts.items():
label = assign_label(key, class_labels)
result[label] += counts[key]/shots
return result
def classify(x_list, params, class_labels):
qc_list = []
for x in x_list:
circ_ = circuit.assign_parameters(get_data_dict(params, x))
qc = sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = return_probabilities(counts, class_labels)
probs += [prob]
return probs
def mse_cost(probs, expected_label):
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
return np.square(np.subtract(actual,pred)).mean()
cost_list = []
def cost_function(X, Y, class_labels, params, shots=100, print_value=False):
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [class_labels[0]]
elif label == 1:
training_labels += [class_labels[1]]
probs = classify(training_samples, params, class_labels)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
cost_list.append(cost)
return cost
cost_list = []
optimizer = SPSA(maxiter=100)
# define objective function for training
objective_function = lambda params: cost_function(X_train, Y_train, class_labels, params, print_value=True)
# randomly initialize the parameters
np.random.seed(RANDOM_STATE)
init_params = 2*np.pi*np.random.rand(n*(1)*2)
# train classifier
opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
print()
print('opt_params:', opt_params)
print('opt_value: ', value)
fig = plt.figure()
plt.plot(range(0,len(cost_list),1), cost_list)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title("ADAM Cost value against steps")
plt.show()
def test_model(X, Y, class_labels, params):
accuracy = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
probs = classify(training_samples, params, class_labels)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y_test[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y_test[i] == 1):
accuracy += 1
accuracy /= len(Y_test)
print("Test accuracy: {}\n".format(accuracy))
test_model(X_test, Y_test, class_labels, opt_params)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as pp
from sklearn.datasets import load_wine, load_iris
%matplotlib inline
# Constants
CLEAN_DATA_PATH = "../../Data/Processed/iris_csv.csv"
raw_data = load_iris()
features = pd.DataFrame(data=raw_data['data'],columns=raw_data['feature_names'])
data = features
data['target']=raw_data['target']
data['class']=data['target'].map(lambda ind: raw_data['target_names'][ind])
data.head()
data.shape
data.columns
print(raw_data['DESCR'])
data.info()
data.describe()
def check_unique(df):
""""
Checks the unique value in each column
:param df: The dataframe
"""
for col in df.columns:
unique = df[col].unique()
print("Column: {} has {} unique values\n".format(col, unique))
check_unique(data)
fig = plt.figure()
sns.countplot(x="target", data=data, palette="gist_rainbow_r")
plt.xlabel("Classes(0 = setosa, 1 = versicolor, 2 = verginica)")
plt.title("Target distribution")
plt.show()
data = data[data['class'] != 'virginica']
data.duplicated().sum()
data.drop_duplicates(inplace=True)
data.drop('target', axis=1).corrwith(data['target']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target")
pp.ProfileReport(df=data, dark_mode=True, explorative=True)
data
data = data[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)', 'target']]
data.to_csv(CLEAN_DATA_PATH, index=False)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
from qiskit.ml.datasets import *
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
# constants
n = 4
RANDOM_STATE = 42
LR = 1e-3
class_labels = ['yes', 'no']
def normalizeData(DATA_PATH = "../../Data/Processed/iris_csv.csv"):
"""
Normalizes the data
"""
# Reads the data
data = pd.read_csv(DATA_PATH)
data = shuffle(data, random_state=RANDOM_STATE)
X, Y = data[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']].values, data['target'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=RANDOM_STATE)
return X_train, X_test, Y_train, Y_test
X_train, X_test, Y_train, Y_test = normalizeData()
sv = Statevector.from_label('0' * n)
feature_map = ZZFeatureMap(n, reps=1)
var_form = RealAmplitudes(n, reps=1)
circuit = feature_map.combine(var_form)
circuit.draw(output='mpl')
def get_data_dict(params, x):
parameters = {}
for i, p in enumerate(feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(bit_string, class_labels):
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return class_labels[1]
else:
return class_labels[0]
def return_probabilities(counts, class_labels):
shots = sum(counts.values())
result = {class_labels[0]: 0,
class_labels[1]: 0}
for key, item in counts.items():
label = assign_label(key, class_labels)
result[label] += counts[key]/shots
return result
def classify(x_list, params, class_labels):
qc_list = []
for x in x_list:
circ_ = circuit.assign_parameters(get_data_dict(params, x))
qc = sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = return_probabilities(counts, class_labels)
probs += [prob]
return probs
def mse_cost(probs, expected_label):
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
return np.square(np.subtract(actual,pred)).mean()
cost_list = []
def cost_function(X, Y, class_labels, params, shots=100, print_value=False):
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [class_labels[0]]
elif label == 1:
training_labels += [class_labels[1]]
probs = classify(training_samples, params, class_labels)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
cost_list.append(cost)
return cost
cost_list = []
optimizer = SPSA(maxiter=100)
# define objective function for training
objective_function = lambda params: cost_function(X_train, Y_train, class_labels, params, print_value=True)
# randomly initialize the parameters
np.random.seed(RANDOM_STATE)
init_params = 2*np.pi*np.random.rand(n*(1)*2)
# train classifier
opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
print()
print('opt_params:', opt_params)
print('opt_value: ', value)
fig = plt.figure()
plt.plot(range(0,len(cost_list),1), cost_list)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title("SPSA Cost value against steps")
plt.show()
def test_model(X, Y, class_labels, params):
accuracy = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
probs = classify(training_samples, params, class_labels)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y_test[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y_test[i] == 1):
accuracy += 1
accuracy /= len(Y_test)
print("Test accuracy: {}\n".format(accuracy))
test_model(X_test, Y_test, class_labels, opt_params)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("../../Data/Processed/winecosts.csv")
df.columns = ['Spec', "CostValues"]
df.head(1)
df['Spec']
def check_lowest_cost(df):
"""
Checks the configs which attained the lowest sost
"""
cost = []
lowest_cost = []
for i in range(df.shape[0]):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
lowest_cost.append(data[len(data) - 1])
lowest_cost = sorted(lowest_cost)[:10]
for m in lowest_cost:
for i in range(df.shape[0]):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if float(m) == float(data[len(data) - 1]):
print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
cost.append(data[len(data) - 1])
#df['CostValues'] = []
#df.to_excel("n.xlsx")
# print(df.head(80))
check_lowest_cost(df)
# Plotting all
for i in range(df.shape[0]):
fig = plt.figure()
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
plt.plot(range(0, len(data), 1), data)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(str(df['Spec'][i]))
plt.show()
path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
# fig.savefig(path)
def plot_individual_optimizers(Optimizers):
for opt in Optimizers:
max_iter = 0
fig = plt.figure(figsize=(20,20))
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
if len(data) >= max_iter:
max_iter = len(data)
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if max_iter >= len(data):
temp = np.full((max_iter, ), data[len(data) -1])
temp[:len(data)] = data
data = temp
plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(opt)
plt.legend()
plt.show()
plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])
def plot_increase_vdepth(optimizer, featuremap, reps, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
plt.show()
def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
plt.show()
plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")
plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 2, 4]:
plot_increase_vdepth(opt, fmap, fdepth, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 3, 5]:
plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("../../Data/Processed/iriscost.csv")
df.columns = ['Spec', "CostValues"]
df.head(1)
df['Spec']
def check_lowest_cost(df):
"""
Checks the configs which attained the lowest sost
"""
cost = []
lowest_cost = []
for i in range(df.shape[0]):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
lowest_cost.append(data[len(data) - 1])
lowest_cost = sorted(lowest_cost)[:10]
for m in lowest_cost:
for i in range(df.shape[0]):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if float(m) == float(data[len(data) - 1]):
print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
cost.append(data[len(data) - 1])
#df['CostValues'] = []
#df.to_excel("n.xlsx")
# print(df.head(80))
check_lowest_cost(df)
# Plotting all
for i in range(df.shape[0]):
fig = plt.figure()
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
plt.plot(range(0, len(data), 1), data)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(str(df['Spec'][i]))
plt.show()
path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
# fig.savefig(path)
def plot_individual_optimizers(Optimizers):
for opt in Optimizers:
max_iter = 0
fig = plt.figure(figsize=(20,20))
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
if len(data) >= max_iter:
max_iter = len(data)
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if max_iter >= len(data):
temp = np.full((max_iter, ), data[len(data) -1])
temp[:len(data)] = data
data = temp
plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(opt)
plt.legend()
plt.show()
plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])
def plot_increase_vdepth(optimizer, featuremap, reps, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
plt.show()
def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
plt.show()
plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")
plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 2, 4]:
plot_increase_vdepth(opt, fmap, fdepth, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 3, 5]:
plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
#!/usr/bin/env python
# coding: utf-8
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import csv
import warnings
warnings.filterwarnings("ignore")
class Benchmark:
"""
Benchmarking different optimizers, featuremaps and depth of variational circuits
"""
def __init__(self, optimizer, variational_depth, feature_map, X_train, X_test, Y_train, Y_test):
"""
Initial function
:param optimizer: The optimizer to benchmark
:param variational_depth: The depth of the variational circuit
:param feature_map: The featuremap that encodes data
:param X_train: The x data for training
:param X_test: The x data for testing
:param Y_train: The y data for training
:param Y_test: The y data for testing
"""
self.optimizer = optimizer
self.variational_depth = variational_depth
self.feature_map = feature_map
self.no_qubit = 4
self.random_state = 42
self.class_labels = ['yes', 'no']
self.circuit = None
self.var_form = RealAmplitudes(self.no_qubit, reps=self.variational_depth)
self.sv = Statevector.from_label('0' * self.no_qubit)
self.X_train, self.X_test, self.Y_train, self.Y_test = X_train, X_test, Y_train, Y_test
self.cost_list = []
def prepare_circuit(self):
"""
Prepares the circuit. Combines an encoding circuit, feature map, to a variational circuit, RealAmplitudes
:return:
"""
self.circuit = self.feature_map.combine(self.var_form)
# circuit.draw(output='mpl')
def get_data_dict(self, params, x):
"""
Assign the params to the variational circuit and the data to the featuremap
:param params: Parameter for training the variational circuit
:param x: The data
:return parameters:
"""
parameters = {}
for i, p in enumerate(self.feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(self.var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(self, bit_string):
"""
Based on the output from measurements assign no if it odd parity and yes if it is even parity
:param bit_string: The bit string eg 00100
:return class_label: Yes or No
"""
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return self.class_labels[1]
else:
return self.class_labels[0]
def return_probabilities(self, counts):
"""
Calculates the probabilities of the class label after assigning the label from the bit string measured
as output
:type counts: dict
:param counts: The counts from the measurement of the quantum circuit
:return result: The probability of each class
"""
shots = sum(counts.values())
result = {self.class_labels[0]: 0, self.class_labels[1]: 0}
for key, item in counts.items():
label = self.assign_label(key)
result[label] += counts[key] / shots
return result
def classify(self, x_list, params):
"""
Assigns the x and params to the quantum circuit the runs a measurement to return the probabilities
of each class
:type params: List
:type x_list: List
:param x_list: The x data
:param params: Parameters for optimizing the variational circuit
:return probs: The probabilities
"""
qc_list = []
for x in x_list:
circ_ = self.circuit.assign_parameters(self.get_data_dict(params, x))
qc = self.sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = self.return_probabilities(counts)
probs += [prob]
return probs
@staticmethod
def mse_cost(probs, expected_label):
"""
Calculates the mean squared error from the expected values and calculated values
:type expected_label: List
:type probs: List
:param probs: The expected values
:param expected_label: The real values
:return mse: The mean squared error
"""
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
mse = np.square(np.subtract(actual, pred)).mean()
return mse
def cost_function(self, X, Y, params, print_value=False):
"""
This is the cost function and returns cost for optimization
:type print_value: Boolean
:type params: List
:type Y: List
:type X: List
:param X: The x data
:param Y: The label
:param params: The parameters
:param print_value: If you want values to be printed
:return cost:
"""
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [self.class_labels[0]]
elif label == 1:
training_labels += [self.class_labels[1]]
probs = self.classify(training_samples, params)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += self.mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
self.cost_list.append(cost)
return cost
def test_model(self, X, Y, params):
"""
Test the model based on x test and y test
:type params: List
:type Y: List
:type X: List
:param X: The x test set
:param Y: The y test set
:param params: The parameters
:return:
"""
accuracy = 0
training_samples = []
for sample in X:
training_samples += [sample]
probs = self.classify(training_samples, params)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y[i] == 1):
accuracy += 1
accuracy /= len(Y)
print("Test accuracy: {}".format(accuracy))
def run(self):
"""
Runs the whole code
1. Prepares the circuit
2. define the objective function
3. Initialize the paramters
4. Optimize the paramters by training the classifier
:return:
"""
self.prepare_circuit()
# define objective function for training
objective_function = lambda params: self.cost_function(self.X_train, self.Y_train, params, print_value=False)
# randomly initialize the parameters
np.random.seed(self.random_state)
init_params = 2 * np.pi * np.random.rand(self.no_qubit * self.variational_depth * 2)
# train classifier
opt_params, value, _ = self.optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
# print()
# print('opt_params:', opt_params)
# print('opt_value: ', value)
self.test_model(self.X_test, self.Y_test, opt_params)
def get_cost_list(self):
"""
Return the cost list
:return cost list:
"""
return self.cost_list
def normalize_data(dataPath="../../Data/Processed/heartdata.csv"):
"""
Normalizes the data
:return X_train, X_test, Y_train, Y_test:
"""
# Reads the data
data = pd.read_csv(dataPath)
data = shuffle(data, random_state=42)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=42)
return X_train, X_test, Y_train, Y_test
def main():
data = {}
feature_maps = ['ZZFeatureMap(4, reps=1)', 'ZZFeatureMap(4, reps=2)', 'ZZFeatureMap(4, reps=4)',
'ZFeatureMap(4, reps=1)', 'ZFeatureMap(4, reps=2)', 'ZFeatureMap(4, reps=4)',
'PauliFeatureMap(4, reps=1)', 'PauliFeatureMap(4, reps=2)', 'PauliFeatureMap(4, reps=4)']
optimizers = ["COBYLA(maxiter=50)", "SPSA(max_trials=50)", "ADAM(maxiter=50)"]
x_train, x_test, y_train, y_test = normalize_data()
for fe in feature_maps:
for i in [1, 3, 5]:
for opt in optimizers:
print("FE: {}\tDepth: {}\tOpt: {}".format(fe, i, opt))
test_benchmark = Benchmark(optimizer=eval(opt), variational_depth=i, feature_map=eval(fe), X_train=x_train, X_test=x_test, Y_train=y_train, Y_test=y_test)
test_benchmark.run()
data_list = "{} {} vdepth {}".format(fe, opt, i)
data[data_list] = test_benchmark.get_cost_list()
w = csv.writer(open("../../Data/Processed/heartcosts.csv", "w"))
for key, val in data.items():
w.writerow([key, val])
if __name__ == "__main__":
main()
|
https://github.com/MuhammadMiqdadKhan/Quantum-Teleportation-Using-Qiskit-and-Real-Quantum-Computer-Tutorial
|
MuhammadMiqdadKhan
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical bits
crx = ClassicalRegister(1) # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
"""Creates a bell pair in qc using qubits a & b"""
qc.h(a) # Put qubit a into state |+>
qc.cx(a,b) # CNOT with a as control and b as target
# In our case, Eve entangles qubits q1 and q2
# Let's apply this to our circuit:
create_bell_pair(teleportation_circuit, 1, 2)
# And view the circuit so far:
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
# Let's apply this to our circuit:
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
# This function takes a QuantumCircuit (qc), integer (qubit)
# and ClassicalRegisters (crz & crx) to decide which gates to apply
def bob_gates(qc, qubit, crz, crx):
# Here we use c_if to control our gates with a classical
# bit instead of a qubit
qc.z(qubit).c_if(crz, 1) # Apply gates if the registers
qc.x(qubit).c_if(crx, 1) # are in the state '1'
# Let's apply this to our circuit:
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit_textbook.tools import random_state, vector2latex
# Create random 1-qubit state
psi = random_state(1)
# Display it nicely
vector2latex(psi, pretext="|\\psi\\rangle =")
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
from qiskit.extensions import Initialize
init_gate = Initialize(psi)
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
# Need to add a new ClassicalRegister
# to see the result
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
# First, see what devices we are allowed to use by loading our saved accounts
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# get the least-busy backend at IBM and run the quantum circuit there
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
# Get the results and display them
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
def python_commands(commands):
try:
result = subprocess.run(
['python', '-c', commands], check=True, capture_output=True, encoding='utf8'
)
except subprocess.CalledProcessError as err:
return err
return result
def basic_inits():
all_coms = []
for _compile in ("False", "True"):
for calljulia in ("pyjulia", "juliacall"):
for depot in ("False", "True"):
args = f"compile={_compile}, calljulia='{calljulia}', depot={depot}"
coms = f"import qiskit_alt; qiskit_alt.project.ensure_init({args})"
all_coms.append(coms)
if calljulia == "pyjulia":
other_calljulia = "juliacall"
else:
other_calljulia = "pyjulia"
args = f"compile={_compile}, calljulia='{other_calljulia}', depot={depot}"
coms = f"import qiskit_alt; qiskit_alt.project.ensure_init({args}); qiskit_alt.project.clean_all()"
all_coms.append(coms)
return all_coms
# def basic_inits():
# all_coms = ["import sys", "import os", "import sdsdff", "import sdsdff", "import shutil"]
# return all_coms
def run_tests(all_commands=None, verbose=False):
num_passed = 0
if all_commands is None:
all_commands = basic_inits()
for commands in all_commands:
print(f"running '{commands}'")
result = python_commands(commands)
if isinstance(result, subprocess.CalledProcessError):
print(f"**** Commands '{commands}' failed with error code {result}")
print(result.stderr)
else:
num_passed += 1
if verbose:
print(result)
msg = f"{num_passed} of {len(all_commands)} installation tests passed"
if num_passed < len(all_commands):
print("**** " + msg)
else:
print(msg)
if __name__ == '__main__':
run_tests()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt constructing Fermionic operators from pyscf integrals.
import qiskit_alt
qiskit_alt.project.ensure_init()
import timeit
def make_setup_code(basis, geometry):
return f"""
import qiskit_alt
h2_geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
h2o_geometry = [['O', [0., 0., 0.]],
['H', [0.757, 0.586, 0.]],
['H', [-0.757, 0.586, 0.]]]
from qiskit_alt.electronic_structure import fermionic_hamiltonian
fermionic_hamiltonian({geometry}, {basis})
#qiskit_alt.fermionic_hamiltonian({geometry}, {basis})
"""
def run_one_basis(basis, geometry, num_repetitions):
setup_code = make_setup_code(basis, geometry)
bench_code = f"fermionic_hamiltonian({geometry}, {basis})"
time = timeit.timeit(stmt=bench_code, setup=setup_code, number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"geometry={geometry}, basis={basis} {t:0.2f}", "ms")
return t
def run_benchmarks():
alt_times = []
for basis, geometry, num_repetitions in (("'sto3g'", "h2_geometry", 10), ("'631g'", "h2_geometry", 10),
("'631++g'", "h2_geometry", 10),
("'sto3g'", "h2o_geometry", 10), ("'631g'", "h2o_geometry", 5)):
t = run_one_basis(basis, geometry, num_repetitions)
alt_times.append(t)
return alt_times
if __name__ == '__main__':
alt_times = run_benchmarks()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt transforming an operator from the computational- to the Pauli basis.
import qiskit_alt
qiskit_alt.project.ensure_init()
import timeit
Main = qiskit_alt.project.julia.Main
def make_setup_code(nqubits):
return f"""
import qiskit_alt
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
QuantumOps = qiskit_alt.project.simple_import("QuantumOps")
import numpy as np
Main = qiskit_alt.project.julia.Main
m = np.random.rand(2**{nqubits}, 2**{nqubits})
"""
def run_one(nqubits, num_repetitions):
setup_code = make_setup_code(nqubits)
if qiskit_alt.project._calljulia_name == 'juliacall':
bench_code = "PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(Main.convert(Main.Matrix, m)))"
else:
bench_code = "PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(m))"
time = timeit.timeit(stmt=bench_code, setup=setup_code, number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"nqubits={nqubits}, {t:0.2f}", "ms")
return t
def run_benchmarks():
qk_alt_times = []
for nqubits, num_repetitions in ((2, 50), (3, 50), (4, 10), (5, 10), (6, 10),
(7, 10),
(8, 3)):
t = run_one(nqubits, num_repetitions)
qk_alt_times.append(t)
return qk_alt_times
if __name__ == '__main__':
qk_alt_times = run_benchmarks()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt peforming the Jordan-Wigner transform on a Fermi operator.
import qiskit_alt
qiskit_alt.project.ensure_init()
import timeit
def make_setup_code(basis, geometry):
return f"""
import qiskit_alt.electronic_structure
h2_geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
h2o_geometry = [['O', [0., 0., 0.]],
['H', [0.757, 0.586, 0.]],
['H', [-0.757, 0.586, 0.]]]
basis = {basis}
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian({geometry}, basis)
qiskit_alt.electronic_structure.jordan_wigner(fermi_op);
"""
def run_one_basis(basis, geometry, num_repetitions):
setup_code = make_setup_code(basis, geometry)
bench_code = "qiskit_alt.electronic_structure.jordan_wigner(fermi_op)"
time = timeit.timeit(stmt=bench_code, setup=setup_code, number=num_repetitions)
t = 1000 * time / num_repetitions
print(f"geometry={geometry}, basis={basis} {t:0.2f}", "ms")
return t
def run_benchmarks():
alt_times = []
for basis, geometry, num_repetitions in (("'sto3g'", "h2_geometry", 10), ("'631g'", "h2_geometry", 10),
("'631++g'", "h2_geometry", 10),
("'sto3g'", "h2o_geometry", 10), ("'631g'", "h2o_geometry", 5)):
t = run_one_basis(basis, geometry, num_repetitions)
alt_times.append(t)
return alt_times
if __name__ == '__main__':
alt_times = run_benchmarks()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
# Benchmark qiskit_alt creating a SparsePauliOp from a list of strings.
import sys
import qiskit_alt
qiskit_alt.project.ensure_init()
import random
from timeit import timeit
Main = qiskit_alt.project.julia.Main
QuantumOps = qiskit_alt.project.simple_import("QuantumOps")
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
random.seed(123)
def rand_label(k, n):
return ["".join(random.choices("IXYZ", k=k)) for _ in range(n)]
def run_benchmarks():
qkalt_times = []
for k in (10, 100):
for n in (10, 100, 1000, 5000, 10_000, 100_000):
label = rand_label(k, n)
if qiskit_alt.project._calljulia_name == 'juliacall':
label = Main.pyconvert_list(Main.String, label)
PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(label))
number = 20
t = timeit(lambda: PauliSum_to_SparsePauliOp(QuantumOps.PauliSum(label)), number=number)
t = t * 1000 / number
qkalt_times.append(t)
print(f'k={k}, n={n}, {t} ms')
return qkalt_times
if __name__ == '__main__':
qkalt_times = run_benchmarks()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
import shutil
import os
# Include these lines if we run all files in one process
import qiskit_alt
qiskit_alt.project.ensure_init()
bench_scripts = [
"fermionic_alt_time.py",
"fermionic_nature_time.py",
"from_matrix_alt.py",
"from_matrix_quantum_info.py",
"jordan_wigner_alt_time.py",
"jordan_wigner_nature_time.py",
"pauli_from_list_alt.py",
"pauli_from_list_qinfo.py",
]
_python = shutil.which("python")
## Run each benchmark script in a separate process
def run_bench(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
full = os.path.join(dirname, fname)
res = subprocess.run(
[_python, full], check=True, capture_output=True, encoding='utf8'
).stdout
print(res)
def exec_full_dir(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(dirname, fname)
exec_full(filepath)
def exec_full(filepath):
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
for fname in bench_scripts:
print(fname)
exec_full_dir(fname)
print()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
import shutil
import os
# Include these lines if we run all files in one process
import qiskit_alt
qiskit_alt.project.ensure_init()
bench_scripts = [
"fermionic_alt_time.py",
"from_matrix_alt.py",
"jordan_wigner_alt_time.py",
"pauli_from_list_alt.py"
]
_python = shutil.which("python")
## Run each benchmark script in a separate process
def run_bench(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
full = os.path.join(dirname, fname)
res = subprocess.run(
[_python, full], check=True, capture_output=True, encoding='utf8'
).stdout
print(res)
def exec_full_dir(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(dirname, fname)
exec_full(filepath)
def exec_full(filepath):
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
def run_all():
for fname in bench_scripts:
print(fname)
exec_full_dir(fname)
print()
if __name__ == '__main__':
run_all()
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init()
# The following line would also initialize qiskit_alt behind the scenes, but we have made it explicity above.
# import qiskit_alt.electronic_structure
from qiskit.providers import aer # make sure this is available
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
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit import Aer
from qiskit.algorithms.optimizers import COBYLA
import qiskit_alt, qiskit_alt.electronic_structure # already done above, but this does not hurt
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
from qiskit.opflow import PauliSumOp
geometry = [["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]]
basis="sto3g"
molecule = Molecule(
geometry=geometry, charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
second_q_op= es_problem.second_q_ops()
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
qubit_op = qubit_converter.convert(second_q_op[0])
# Print the underlying data stored backing qubit_op
qubit_op.primitive.simplify()
# Compute the Fermionic operator of the molecule
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
# Convert the Fermionic operator to a Pauli operator using the Jordan-Wigner transform
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
type(pauli_op)
pauli_op.simplify()
(pauli_op - qubit_op.primitive).simplify()
fermi_op[1] # In qiskit_alt, the Fermi operator carries the identity term
nuclear_energy_term = fermi_op[1].coeff
nuclear_energy_term
# Define the ansatz
ansatz = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500)
# Select the backend for the quantum_instance
backend = QuantumInstance(Aer.get_backend('statevector_simulator'),
seed_simulator=100,
seed_transpiler=100)
# Run VQE algorithm
vqe = VQE(ansatz = ansatz,
optimizer = optimizer,
quantum_instance = backend)
# Compute the ground-state energy of the molecule
nature_result = vqe.compute_minimum_eigenvalue(operator=qubit_op)
nature_energy = nature_result.eigenvalue.real + nuclear_energy_term # Include constant term that is normally thrown away
print("The ground-state energy of the Hydrogen molecule is {} Hatree".format(round(nature_energy,3)))
# Convert the Pauli operator into a sum of Pauli operators, the required input format
pauli_sum_op = PauliSumOp(pauli_op)
# Compute the ground-state energy of the molecule
alt_result = vqe.compute_minimum_eigenvalue(operator=pauli_sum_op)
print("The ground-state energy of the Hydrogen molecule is {} Hatree".format(round(alt_result.eigenvalue.real,3)))
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init(calljulia="pyjulia", compile=False, depot=True)
julia = qiskit_alt.project.julia
julia.Main.zeros(10)
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# Specify the geometry of the H_2 molecule
geometry = [['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]]
basis = 'sto3g'
molecule = Molecule(geometry=geometry,
charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
fermionic_hamiltonian = second_q_op[0]
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
nature_qubit_op = qubit_converter.convert(fermionic_hamiltonian)
nature_qubit_op.primitive
import qiskit_alt.electronic_structure
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
pauli_op.simplify() # The Julia Pauli operators use a different sorting convention; we sort again for comparison.
%run ../bench/jordan_wigner_nature_time.py
nature_times
%run ../bench/jordan_wigner_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
%run ../bench/fermionic_nature_time.py
nature_times
%run ../bench/fermionic_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
from qiskit_alt.pauli_operators import QuantumOps, PauliSum_to_SparsePauliOp
import numpy as np
m = np.random.rand(2**3, 2**3) # 3-qubit operator
pauli_sum = QuantumOps.PauliSum(m) # This is a wrapped Julia object
PauliSum_to_SparsePauliOp(pauli_sum) # Convert to qiskit.quantum_info.SparsePauliOp
%run ../bench/from_matrix_quantum_info.py
%run ../bench/from_matrix_alt.py
[t_pyqk / t_qk_alt for t_pyqk, t_qk_alt in zip(pyqk_times, qk_alt_times)]
%run ../bench/pauli_from_list_qinfo.py
%run ../bench/pauli_from_list_alt.py
[x / y for x,y in zip(quantum_info_times, qkalt_times)]
%load_ext julia.magic
%julia using Random: randstring
%julia pauli_strings = [randstring("IXYZ", 10) for _ in 1:1000]
None;
%julia import Pkg; Pkg.add("BenchmarkTools")
%julia using BenchmarkTools: @btime
%julia @btime QuantumOps.PauliSum($pauli_strings)
None;
%julia pauli_sum = QuantumOps.PauliSum(pauli_strings);
%julia println(length(pauli_sum))
%julia println(pauli_sum[1])
6.9 * 2.29 / .343 # Ratio of time to construct PauliSum via qiskit_alt to time in pure Julia
import qiskit.tools.jupyter
d = qiskit.__qiskit_version__._version_dict
d['qiskit_alt'] = qiskit_alt.__version__
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init(calljulia="juliacall", compile=False)
julia = qiskit_alt.project.julia
Main = julia.Main
julia.Main.zeros(3)
type(julia.Main.zeros(3))
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureDriverType, ElectronicStructureMoleculeDriver
# Specify the geometry of the H_2 molecule
geometry = [['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]]
basis = 'sto3g'
molecule = Molecule(geometry=geometry,
charge=0, multiplicity=1)
driver = ElectronicStructureMoleculeDriver(molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
es_problem = ElectronicStructureProblem(driver)
second_q_op = es_problem.second_q_ops()
fermionic_hamiltonian = second_q_op[0]
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
nature_qubit_op = qubit_converter.convert(fermionic_hamiltonian)
nature_qubit_op.primitive
import qiskit_alt.electronic_structure
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
pauli_op.simplify() # The Julia Pauli operators use a different sorting convention; we sort again for comparison.
%run ../bench/jordan_wigner_nature_time.py
nature_times
%run ../bench/jordan_wigner_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
%run ../bench/fermionic_nature_time.py
nature_times
%run ../bench/fermionic_alt_time.py
alt_times
[t_nature / t_qk_alt for t_nature, t_qk_alt in zip(nature_times, alt_times)]
from qiskit_alt.pauli_operators import QuantumOps, PauliSum_to_SparsePauliOp
import numpy as np
m = np.random.rand(2**3, 2**3) # 3-qubit operator
m = Main.convert(Main.Matrix, m) # Convert PythonCall.PyArray to a native Julia type
pauli_sum = QuantumOps.PauliSum(m) # This is a wrapped Julia object
PauliSum_to_SparsePauliOp(pauli_sum) # Convert to qiskit.quantum_info.SparsePauliOp
%run ../bench/from_matrix_quantum_info.py
%run ../bench/from_matrix_alt.py
[t_pyqk / t_qk_alt for t_pyqk, t_qk_alt in zip(pyqk_times, qk_alt_times)]
%run ../bench/pauli_from_list_qinfo.py
%run ../bench/pauli_from_list_alt.py
[x / y for x,y in zip(quantum_info_times, qkalt_times)]
import qiskit.tools.jupyter
d = qiskit.__qiskit_version__._version_dict
d['qiskit_alt'] = qiskit_alt.__version__
%qiskit_version_table
# %load_ext julia.magic
# %julia using Random: randstring
#%julia pauli_strings = [randstring("IXYZ", 10) for _ in 1:1000]
# None;
# %julia import Pkg; Pkg.add("BenchmarkTools")
#%julia using BenchmarkTools: @btime
#%julia @btime QuantumOps.PauliSum($pauli_strings)
#None;
#%julia pauli_sum = QuantumOps.PauliSum(pauli_strings);
#%julia println(length(pauli_sum))
#%julia println(pauli_sum[1])
#6.9 * 2.29 / .343 # Ratio of time to construct PauliSum via qiskit_alt to time in pure Julia
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.opflow import X, Y, Z, I, PauliSumOp
from qiskit.circuit.library import TwoLocal
from qiskit import Aer
import numpy as np
import qiskit_alt, qiskit_alt.electronic_structure
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
from qiskit.opflow import PauliSumOp
# Describe the Hydrogen molecule by fixing the location of each nucleus
geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.739]]]
basis = 'sto3g'
# Compute the Fermionic operator of the molecule
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
# Convert the Fermionic operator to a Pauli operator using the Jordan-Wigner transform
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op);
# Convert the Pauli operator into a sum of Pauli operators
# input to the VQE algorithm to compute the minimum eigenvalue
pauli_sum_op = PauliSumOp(pauli_op)
print(pauli_sum_op)
# Set up the ansatz of type TwoLOcal
ansatz = TwoLocal(num_qubits=4,
rotation_blocks=['ry'],
entanglement_blocks='cx',
reps=1,
entanglement='linear',
skip_final_rotation_layer= False)
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500)
# Select the backend for the quantum_instance
backend = Aer.get_backend('aer_simulator_statevector')
# Run VQE algorithm
vqe = VQE(ansatz = ansatz,
optimizer = optimizer,
quantum_instance = backend)
# Compute the ground-state energy of the molecule
result = vqe.compute_minimum_eigenvalue(operator=pauli_sum_op)
print("The ground-state energy of the Hydrogen molecule is {} Hatree".format(round(result.eigenvalue.real,3)))
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
#basis = 'sto3g'
basis = '631++g'
fermi_op = qiskit_alt.fermionic_hamiltonian(geometry, basis)
pauli_op = qiskit_alt.jordan_wigner(fermi_op)
#basis = '631g'
#basis = 'dzvp'
# Too big
#basis = 'dzp'
#basis = 'dzvp2'
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
def do_jw_problem():
# qiskit_alt.Main.eval('include("examples/jw_example.jl")')
qiskit_alt.Main.eval('include("jw_example.jl")')
pauli_op = qiskit_alt.Main.eval("pauli_op")
spop_jl = qiskit_alt.QiskitQuantumInfo.SparsePauliOp(pauli_op)
spop = qiskit_alt.jlSparsePauliOp(spop_jl)
return spop
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
#geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
geometry = [['O', [0., 0., 0.]],
['H', [0.757, 0.586, 0.]],
['H', [-0.757, 0.586, 0.]]]
#basis = 'sto3g'
#basis = '631g'
basis = 'dzvp2'
pauli_op = qiskit_alt.jordan_wigner(geometry, basis)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import pytest
import qiskit_alt
project = qiskit_alt.project
project.ensure_init() # calljulia="pyjulia"
import qiskit_alt.electronic_structure
Main = project.julia.Main
def test_always_passes():
assert True
def test_interface_lib():
assert qiskit_alt.project.julia.__name__ == 'julia'
def test_import_QuantumOps():
project.simple_import("QuantumOps")
assert True
def test_import_ElectronicStructure():
project.simple_import("ElectronicStructure")
assert True
def test_import_QiskitQuantumInfo():
project.simple_import("QiskitQuantumInfo")
assert True
@pytest.fixture
def conv_geometry():
geometry = [['H', [0., 0., 0.]], ['H', [0., 0., 0.7414]]]
# geometry = [['O', [0., 0., 0.]],
# ['H', [0.757, 0.586, 0.]],
# ['H', [-0.757, 0.586, 0.]]]
return qiskit_alt.electronic_structure.Geometry(geometry)
def test_Geometry_length(conv_geometry):
assert Main.length(conv_geometry) == 2
def test_Geometry_atom(conv_geometry):
atom = Main.getindex(conv_geometry, 1)
assert atom.coords == (0.0, 0.0, 0.0)
def test_fermionic_hamiltonian(conv_geometry):
fermi_op = Main.fermionic_hamiltonian(conv_geometry, "sto3g")
assert Main.length(fermi_op) == 25
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import pytest
import qiskit_alt
project = qiskit_alt.project
project.ensure_init(calljulia="juliacall")
def test_always_passes():
assert True
def test_interface_lib():
assert qiskit_alt.project.julia.__name__ == 'juliacall'
def test_Main():
Main = qiskit_alt.project.julia.Main
assert Main.sind(90) == 1.0
|
https://github.com/BryceFuller/qiskit_camp
|
BryceFuller
|
# Python
import logging
from copy import deepcopy
from functools import partial
from contextlib import contextmanager
import time
from multideterminant_prep import PrepareMultiDeterminantState as pmds
# Local
# External
import pandas as pd
import numpy as np
import xarray as xr
import xyzpy as xy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, tools
from qiskit.aqua.components.optimizers import SPSA, SLSQP
def build_model_from_parameters(circuit, theta):
layers, num_qubits, rotations = theta.shape
assert rotations == 3, "Expected a 3-sized vector for each theta."
# Combine all the qubits in the circuit into one flat list
all_qubits = [(reg, qubit) for register in circuit.qregs for reg, qubit in register]
assert len(all_qubits) == num_qubits, \
"There are {} qubits but expected same as parameter's shape ({})!".format(len(all_qubits), num_qubits)
for l in range(layers):
# Add layer of (pseudo)random single qubit rotations
for n, (reg, qubit_idx) in enumerate(all_qubits):
circuit.u3(theta[l][n][0], theta[l][n][1], theta[l][n][2], reg[qubit_idx])
# Pattern with 2-qubit gates
# change the step size in range to affect density of cx layer
for n in range(0, num_qubits, 2):
if (n + 1) + (l % 2) < num_qubits: # Out-of-bounds check
reg_1, qubit_idx_1 = all_qubits[n + (l % 2)]
reg_2, qubit_idx_2 = all_qubits[(n + 1) + (l % 2)]
circuit.cx(reg_1[qubit_idx_1], reg_2[qubit_idx_2])
def build_compression_model(registers, model_parameters):
""" Given a set of input registers, builds a parametrised model of random
gate operations which seek to approximate some other (equally-sized) target
circuit.
Returns:
QuantumCircuit: a circuit consisting of random operations on the given
registers.
"""
model_circuit = QuantumCircuit(*registers)
# Reshape model parameters so they make sense
n_layers = int(len(model_parameters) / 3 / model_circuit.width())
model_parameters = np.array(model_parameters).reshape((n_layers, model_circuit.width(), 3))
# TODO: Store some internal parametrization that can be optimised over.
# TODO: Create random set of gate operations based on parametrization.
build_model_from_parameters(model_circuit, model_parameters)
return model_circuit
def swap_test_with_compression_model(target_circuit, model_parameters):
""" Given a circuit, builds a parametrised sub-circuit that runs in
parallel with and approximately models (with compression) the original
circuit.
Return:
QuantumCircuit: new combined circuit consisting of the original circuit
and the model circuit.
"""
# We assume all quantum registers of the original circuit are to be
# modelled.
new_registers = [reg.__class__(reg.size, '{}_model'.format(reg.name))
for reg in target_circuit.qregs]
# TODO: Build the model's compression circuit here.
model_circuit = build_compression_model(new_registers, model_parameters)
# Append the two circuits together.
top_circuit = target_circuit + model_circuit
# Synchronisation barrier just so we know where the original circuits ends.
top_circuit.barrier()
# Performs a swap test between the compression model and original circuit.
# ------------------------------------------------------------------------
# Firstly, create an ancillary in superposition to store the swap test result.
swap_tester = QuantumRegister(1, 'swap_tester')
top_circuit.add_register(swap_tester)
top_circuit.h(swap_tester)
# Next, we perform controlled SWAPs using the swap tester.
for orig_reg, model_reg in zip(target_circuit.qregs, model_circuit.qregs):
for i in range(orig_reg.size):
top_circuit.cswap(swap_tester[0], orig_reg[i], model_reg[i])
# Finally, we re-interfere the branches and measure the swap tester.
top_circuit.h(swap_tester)
top_circuit.x(swap_tester) # Make it so test measurement is P(model == target).
swap_test_result = ClassicalRegister(1, 'swap_test_result')
top_circuit.add_register(swap_test_result)
top_circuit.measure(swap_tester, swap_test_result)
return top_circuit
def compute_approximation_fidelity(target_circuit, backend='qasm_simulator', n_shots=1000, results_fidelity_list=[], model_parameters=[]):
""" Performs a set of runs on the target circuit and an approximation model
to compute the approximation's fidelity.
Returns:
float: a measure of fidelity in [0, 1], where 1 represents the maximum
achievable approximation of the target circuit.
"""
final_circuit = swap_test_with_compression_model(target_circuit, model_parameters)
# Execute the SWAP test circuit
simulator = Aer.get_backend(backend)
job = execute(final_circuit, backend=simulator, shots=n_shots)
# Return a measurement of fidelity
result_counts = job.result().get_counts(final_circuit)
fidelity = result_counts.get('1', n_shots) / n_shots
results_fidelity_list.append(fidelity)
logging.critical("Fidelity: {}".format(fidelity))
return fidelity
def cross_validate_qnn_depth(target_circuit, n_shots, n_iters, n_layers, run=0):
""" Runs a single cross-validation experiment with the given parameters.
Returns:
xr.Dataset: an xarray Dataset consisting of any number of DataArrays of
data regarding the results of this experiment. This Dataset will be merged
with all other experiment datasets, so in theory every experiment
should return a fairly consistent set of data.
"""
# TODO: Compile the circuit to determine a measure of optimised circuit depth
# tools.compiler.compile(target_circuit, backend)
# logging.critical("Circuit depth (compiled): {}".format(compiled_depth))
# Configuration
n_params = target_circuit.width() * n_layers * 3
# Build variable bounds
variable_bounds_single = (0., 2*np.pi)
variable_bounds = [variable_bounds_single] * n_params
initial_point = np.random.uniform(low=variable_bounds_single[0],
high=variable_bounds_single[1],
size=(n_params,)).tolist()
# logging.critical("Initial point: {}".format(initial_point))
# Store resulting information
results_fidelity_list = []
# Partially define the objective function
maximisation_function = partial(compute_approximation_fidelity, target_circuit, "qasm_simulator", n_shots, results_fidelity_list)
minimization_function = lambda params: -maximisation_function(params)
# Call the optimiser
optimizer = SPSA(max_trials=n_iters, save_steps=1)
result = optimizer.optimize(n_params, minimization_function,
variable_bounds=variable_bounds, initial_point=initial_point)
last_params, last_score, _ = result
logging.critical("FINAL SCORE: {}".format(-last_score))
# Ignore the first set of fidelities (calibration) and very last one (equal to last_score)
results_fidelity_list = results_fidelity_list[-((n_iters * 2) + 1):-1]
# TODO calculate compiled depth (for simulator this is always 2*l)
# Output results
return xr.Dataset({
"fidelity": xr.DataArray(np.array(results_fidelity_list).reshape((n_iters, 2)), coords={"iteration": range(n_iters), "plusminus": range(2)}, dims=["iteration", "plusminus"]),
"last_theta": xr.DataArray(np.array(last_params).reshape((n_layers, target_circuit.width(), 3)), coords={"layer": range(n_layers), "qubit": range(target_circuit.width()), "angle": ["theta", "phi", "lambda"]}, dims=["layer", "qubit", "angle"]),
"uncompiled_target_depth": xr.DataArray(target_circuit.depth()),
# "compiled_target_depth": xr.DataArray(compiled_depth),
"uncompiled_model_depth": xr.DataArray(2 * n_layers),
})
@contextmanager
def experiment_crop(fn, experiment_name):
""" Defines how to run a crop of experiments (i.e. all the experiments in
the grid) in parallel and store results in a file.
"""
experiment_runner = xy.Runner(fn, var_names=None)
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "experiment_results/{}_{}.h5".format(experiment_name, timestr)
logging.critical("Running experiments: {}".format(filename))
experiment_harvester = xy.Harvester(experiment_runner, data_name=filename)
experiment = experiment_harvester.Crop()
yield experiment
experiment.grow_missing(parallel=True)
results = experiment.reap(wait=True, overwrite=True)
logging.critical(results)
logging.critical("Saved experiments: {}".format(filename))
if __name__ == "__main__":
"""
Example which defines a circuit and then runs a set of experiments, defined
by the grid_search parameters, across a parallel set of processes.
"""
logging.critical("Creating the circuit...")
in_strings = ["0101", "0011"]
in_weights = [4, 7]
target_circuit = pmds(in_weights, in_strings, mode='noancilla')
logging.critical("Circuit depth (uncompiled): {}".format(target_circuit.depth()))
logging.critical("Running the experiments...")
with experiment_crop(cross_validate_qnn_depth, "experiments") as experiment:
grid_search = {
'n_shots': [1000],
'n_iters': [200],
'n_layers': [2, 3, 4, 5],
'run': range(50),
}
constants = {
'target_circuit': target_circuit
}
experiment.sow_combos(grid_search, constants=constants)
|
https://github.com/BryceFuller/qiskit_camp
|
BryceFuller
|
#!/usr/bin/env python
# coding: utf-8
# Python
import math
# Local
# External
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
import qiskit.aqua
def PrepareMultiDeterminantState(weights, determinants, normalize=True, mode='basic'):
'''
Constructs multideterminant state : a linear superposition of many fermionic determinants.
Appropriate for us as an input state for VQE.
Input: np.array of REAL weights, and list of determinants.
Each determinant is a bitstring of length n.
Output: a QuantumCircuit object.
If mode == basic, acting on 2n qubits (n logical, n ancillas).
Otherwise, acting on n+1 qubits.
The depth of the circuit goes like O(n L) where L = len(weights), in basic mode,
and exponentially in n when only 1 ancilla.
This is an implementation of the circuit in https://arxiv.org/abs/1809.05523
'''
# number of determinants in the state
L = len(weights)
if L != len(determinants):
raise Exception('# weights != # determinants')
# Check normalization
norm = np.linalg.norm(weights)
# print('Norm is: {}'.format(norm))
if normalize:
weights /= norm
elif abs(norm-1) > 10**-5:
raise Exception('Weights do not produce a normalized vector.')
# TODO: check that weights are normalized
# number of orbitals that determinants can be made of
n = len(determinants[0])
# the first n qubits will be used for orbitals, the next as the controlled rotation ancilla,
# the last n as ancillas will be used for the n-Toffoli
qubits = QuantumRegister(n, 'q')
cqub = QuantumRegister(1, 'c')
if mode == 'noancilla':
# no ancillas
registers = [qubits, cqub]
else:
ancillas = QuantumRegister(n-1, 'a')
registers = [qubits, cqub, ancillas]
# initialize
circ = QuantumCircuit(*registers)
for i in range(n):
if determinants[0][i] == 1:
circ.x(qubits[i])
circ.x(cqub)
b = 1 # the beta
a = 0
# iterate over all determinants that must be in the final state
for step in range(L-1):
# choose first qubit on which D_l and D_{l+1} differ
old_det = determinants[step]
new_det = determinants[step+1]
a = weights[step]
# Find first bit of difference
different_qubit = 0
while different_qubit <= n:
if old_det[different_qubit] != new_det[different_qubit]:
break
else:
different_qubit += 1
if different_qubit == n:
raise Exception('Determinants {} and {} are the same.'.format(old_det, new_det))
# Compute the rotation angle
# Equation is cos(g) beta_l = alpha_l
angle = math.acos(a/b)
# print('Step {} angle is {}'.format(step, angle))
# beta_{l+1} is
b = b * math.sin(angle)
if old_det[different_qubit] == 1:
b = -b
# print('Flipped beta sign.')
# want a controlled-Y rotation, but can do controlled-Z, so map Y basis to Z basis.
# 1) first map Y to X (with U1(-pi/2) gate)
# 2) X to Z, with Hadamard
# 3) apply z-rotation
# 4) undo this
# ---
# circ.u1(-math.pi/2, qubits[different_qubit])
# circ.h(qubits[different_qubit])
# circ.crz(angle, cqub, qubits[different_qubit])
# circ.h(qubits[different_qubit])
# circ.u1(-math.pi/2, qubits[different_qubit])
circ.cu3(2 * angle, 0, 0, cqub, qubits[different_qubit])
# Now must do an n-qubit Toffoli to change the |1> to |0>
# but controlled on the |D_l> bitstring
flip_all(circ, qubits, old_det)
if mode == 'noancilla':
# no ancillas
circ.mct(qubits, cqub[0], None, mode='noancilla')
else:
circ.mct(qubits, cqub[0], ancillas, mode='basic')
# nToffoliAncillas(circ, qubits, ancillas, cqub)
flip_all(circ, qubits, old_det) # undo
# if step > 0:
# break
# If b not same sign as weight, flip sign
# if b * weights[step+1]:
# circ.z(cqub)
# b = -b
# Now continue flipping the rest of the bits
for i in range(different_qubit+1, n):
if old_det[i] != new_det[i]:
circ.cx(cqub, qubits[i])
circ.barrier()
# Finally check that the sign of the last weight is correct
# and set the ancilla to zero.
if b * weights[-1] < 0:
# must flip sign
circ.z(cqub)
# Remove the |1>
flip_all(circ, qubits, new_det)
if mode == 'noancilla':
# no ancillas
circ.mct(qubits, cqub[0], None, mode='noancilla')
else:
circ.mct(qubits, cqub[0], ancillas, mode='basic')
# nToffoliAncillas(circ, qubits, ancillas, cqub)
flip_all(circ, qubits, new_det) # undo
return circ
def flip_all(circ, tgt, bits):
'''
Flips the qubits of tgt where the bit in the bitstring is 0.
'''
for i in range(len(bits)):
if bits[i] == 0:
# flip
circ.x(tgt[i])
def nToffoliAncillas(circ, ctrl, anc, tgt):
'''
Returns a circuit that implements an n-qubit Toffoli using n ancillas.
'''
n = len(ctrl)
# compute
circ.ccx(ctrl[0], ctrl[1], anc[0])
for i in range(2, n):
circ.ccx(ctrl[i], anc[i-2], anc[i-1])
# copy
circ.cx(anc[n-2], tgt[0])
# uncompute
for i in range(n-1, 1, -1):
circ.ccx(ctrl[i], anc[i-2], anc[i-1])
circ.ccx(ctrl[0], ctrl[1], anc[0])
return circ
|
https://github.com/BryceFuller/qiskit_camp
|
BryceFuller
|
%matplotlib inline
import xarray as xr
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('pylab', 'inline')
#sns.set_style("darkgrid")
pylab.rcParams['figure.figsize'] = (16, 8)
pylab.rcParams.update({'font.size': 10})
df = xr.open_dataset("../experiment_results/experiments_20190301-052407.h5").squeeze()
df
sns.lineplot(x='iteration', y='fidelity', hue='n_layers', data=df.fidelity.sel(n_shots=1000).to_dataframe().reset_index())
plt.legend(df.n_layers.values)
plt.title("Fidelity improvement with optimiser iterations. (Two determinants with four qubits)")
df.fidelity.max(dim="iteration").mean(dim='run')#.mean(dim='n_layers')
sns.boxenplot(orient='h', x='fidelity', y='n_layers', data=df.fidelity.max(dim='iteration').squeeze().to_dataframe().reset_index())
df.fidelity.max(dim='iteration').squeeze()
|
https://github.com/BryceFuller/qiskit_camp
|
BryceFuller
|
%matplotlib inline
import sys
sys.path.append("..")
import compress
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
import numpy as np
from functools import partial
from qiskit.aqua.components.optimizers import SPSA
from multideterminant_prep import PrepareMultiDeterminantState as pmds
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('pylab', 'inline')
pylab.rcParams['figure.figsize'] = (12, 6)
pylab.rcParams.update({'font.size': 10})
in_strings = ["101", "011", "110"]
in_weights = [4, 7, 2]
circuit = pmds(in_weights, in_strings)
circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
# Configuration
n_shots = 1000
n_trials = 300
n_layers = 3
n_params = circuit.width() * n_layers * 3
# Build variable bounds
variable_bounds_single = (0., 2*np.pi)
variable_bounds = [variable_bounds_single] * n_params
initial_point = np.random.uniform(low=variable_bounds_single[0],
high=variable_bounds_single[1],
size=(n_params,)).tolist()
circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
print("Circuit has a depth of: {}".format(circuit.depth()))
final_circuit = compress.swap_test_with_compression_model(circuit, initial_point)
final_circuit.draw(scale=0.5, style={'fold':100}, output='mpl')
results = compress.cross_validate_qnn_depth(circuit, n_shots, n_trials, n_layers, run=0)
results
sns.lineplot(x='iteration', y='fidelity', data=results.fidelity.to_dataframe().reset_index())
plt.title("Fidelity improvement with optimiser iterations")
|
https://github.com/BryceFuller/qiskit_camp
|
BryceFuller
|
# Python
import logging
# Local
import compress
# External
import pytest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
def test_compression_model():
# Create a simple circuit that applies one simple flip.
q0 = QuantumRegister(1, 'q0')
circuit = QuantumCircuit(q0)
fidelity = compress.compute_approximation_fidelity(circuit)
assert fidelity == 1.0, "Fidelity should be 100% for the same circuit!"
circuit.h(q0)
fidelity = compress.compute_approximation_fidelity(circuit)
assert np.isclose(fidelity, 0.75, rtol=1e-1) # XXX: Very loose test :3
# Optimise a random compression circuit and ensure it converges to fidelity=1.0
results = compress.cross_validate_qnn_depth(circuit, n_shots=100, n_iters=30, n_layers=3)
assert np.isclose(results.fidelity.isel(iteration=-1).max(dim='plusminus').squeeze(), 1.0, rtol=1e-1)
|
https://github.com/HayleySummer/Qiskit_Hackathon_Europe
|
HayleySummer
|
import numpy
from PIL import Image
from IPython.display import Image as dispImage
#Generate initial image
data = numpy.zeros((8, 8, 3), dtype=numpy.uint8)
white = [255, 255, 255]
grey = [128, 128, 128]
black = [0,0,0]
boardRows = 8
boardColumns = 8
for i in range(boardRows):
for j in range(boardColumns):
if (i == 3 and j == 3) or (i == 4 and j == 4):
data[i, j] = white
elif (i == 3 and j == 4) or (i == 4 and j == 3):
data[i, j] = black
else:
data[i, j] = grey
image = Image.fromarray(data)
image.show()
image = image.save("prueba.jpg")
dispImage("prueba.jpg", width=100, height=100)
#Path to the file 15x10_w.txt
with open('/content/drive/MyDrive/Colab Notebooks/Hackathon/Board_To_Image/Data/Training Set/15x10_w.txt') as f:
lines = f.readlines()
f.close()
auxParams = lines[0].split("\n")
params = auxParams[0].split(" ")
print(params)
#0 5 4 ==>
#First 0 == black - 1 == white
#Second parameter column index (from 0 to 7)
#Third parameter row index (from 0 to 7)
#Print first movement
#FROM THIS POINTS, THE FIRST PARAMETER "i" IS THE ROW AND THE SECOND "j" THE COLUMN
if params[0] == "0":
color = black
else:
color = white
i = int(params[2])
j = int(params[1])
data[i,j] = color
print(i,j)
#Print all movements (WITHOUT FLIPPLIG SPOTS)
"""
for line in lines:
auxParams = line.split("\n")
params = auxParams[0].split(" ")
if params[0] == "0":
color = black
else:
color = white
i = int(params[2]) #rows
j = int(params[1]) #colummns
data[i,j] = color
print(data)
"""
#Save image with movement
image = Image.fromarray(data)
image.show()
image = image.save("prueba.jpg")
dispImage("prueba.jpg", width=100, height=100)
|
https://github.com/HayleySummer/Qiskit_Hackathon_Europe
|
HayleySummer
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Board A. Only valid move is first Tile
# 011
# 111
# 111
boardA = [ 0, 1, 1, 1, 1, 1, 1, 1, 1]
# Board B. Has Seven Valid moves
#000
#010
#010
boardB = [ 0, 0, 0, 0, 1, 0, 0, 1, 0]
# Board C. Has 5 Valid moves
# 000
# 000
# 010
boardC = [ 0, 0, 0, 0, 0, 0, 0, 1, 0]
# Board D. Has 2 Valid moves
# 001
# 111
# 111
boardD = [ 0, 0, 1, 1, 1, 1, 1, 1, 1]
# Params : circuit, BoardState, Auxillary Qubits, oracle
def othello_3x3_oracle(qc, boardQ, auxillary, oracle):
#Compute the search for the valid moves
# Start with contrived solution, Use a board with only 1 free space. The only valid answer is of the form 100 000 000
#qc.cx(auxillary[0],boardQ[0])
qc.cx(auxillary,boardQ)
qc.mct(boardQ, oracle) ### If the board is solved flip the output bit.
#Phase kickback because output_qubit is in superposition
#Uncompute the search for the valid moves
#qc.cx(auxillary[0],boardQ[0])
qc.cx(auxillary,boardQ)
return
def diffuser(nqubits):
qcDiff = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qcDiff.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qcDiff.x(qubit)
# Do multi-controlled-Z gate
qcDiff.h(nqubits-1)
qcDiff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qcDiff.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qcDiff.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qcDiff.h(qubit)
# We will return the diffuser as a gate
U_s = qcDiff.to_gate()
U_s.name = "$U_s$"
return U_s
def othelloMoveSearch ( boardRepresentation ):
# Create a 9 Qubit Register for the Quantum represntation of the board.
boardQ = QuantumRegister(9)
# Create a 9 Qubit Register for Auxillary Qubits for Grover Search
auxillary = QuantumRegister(9)
# Create a single Qubit Register for the Grover Search Oracle
oracle = QuantumRegister(1)
# Create a 2 Qubit Quantum Register [Not used yet]
qr = QuantumRegister(2)
# Create a 9 Bit Classical Register for the output
cr = ClassicalRegister(9)
# Create a quantum circuit containing the registers above
qc = QuantumCircuit(boardQ, auxillary, oracle, qr, cr)
# Put the Auxillary Qubits into SuperPosition of the Results.
qc.h(auxillary[:])
# Prepare the Oracle Qubit
qc.x(oracle[0])
qc.h(oracle[0])
# Set up the Quantum Representation of the board to match the current state of the board
for x in range(len( boardRepresentation )):
if boardRepresentation[x] > 0 :
qc.x(boardQ[x])
# Call the Grover Algorithm and Diffuser 16 times [Number of iterations varies according to search]
for i in range (16) :
othello_3x3_oracle(qc, boardQ, auxillary, oracle)
qc.append(diffuser(9), [9,10,11,12,13,14,15,16,17])
# Measure the status of the Quantum Board to verify the setup has worked.
qc.measure(auxillary,cr)
# Change the endian
qc = qc.reverse_bits()
#print ("Diagnostic Log 001")
return qc
# Create the circuit and print it on screen
qc1 = othelloMoveSearch( boardA )
qc1.draw(output="mpl")
#backend = BasicAer.get_backend('qasm_simulator')
backend = Aer.get_backend('qasm_simulator')
shots = 1024
results = execute(qc1, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer, number_to_keep=6)
|
https://github.com/jhlee29/quantum-meets-hangul
|
jhlee29
|
from PIL import Image, ImageOps
import os, glob
import numpy as np
from sklearn import model_selection #cross_validation
# from keras.utils import np_utils
# General imports
import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
from pylab import cm
import warnings
warnings.filterwarnings("ignore")
# scikit-learn imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Qiskit imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# input
classes = ["g", "h"]
# image size of 28 x 28
image_size = 28
# Maximum number of sheets to read
max_read = 75
num_classes = len(classes)
# load the image
X = []
Y = []
for index, classlabel in enumerate(classes):
images_dir = "./hangul_characters/" + classlabel
files = glob.glob(images_dir + "/*.jpg")
for i, file in enumerate(files):
# Stop if you read more than max_read to make the number of sheets for each class
if i >= max_read: break
# open the file, read as data, add to X
# Repeatedly add labels with the same index to Y
image = Image.open(file)
image = ImageOps.invert(image)
image = image.convert("L")
image = image.resize((image_size, image_size))
data = np.asarray(image)
X.append(data)
Y.append(index)
X = np.array(X)
Y = np.array(Y)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=0.2, random_state=42)
X_train = X_train.reshape(len(X_train), -1).astype(np.float64)
X_test = X_test.reshape(len(X_test), -1).astype(np.float64)
fig = plt.figure()
LABELS = [0, 1]
num_labels = len(LABELS)
for i in range(num_labels):
ax = fig.add_subplot(1, num_labels, i+1)
img = X[Y==LABELS[i]][0].reshape((28,28))
ax.imshow(img, cmap="Greys")
# Standardize
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
# Reduce dimensions
N_DIM = 5
pca = PCA(n_components=N_DIM)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=5, reps=1, entanglement='linear')
map_zz.decompose().draw('mpl')
zz_kernel = QuantumKernel(feature_map=map_zz, quantum_instance=Aer.get_backend('statevector_simulator'))
matrix_train = zz_kernel.evaluate(x_vec=X_train)
matrix_val = zz_kernel.evaluate(x_vec=X_test, y_vec=X_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_val),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("validation kernel matrix")
plt.show()
zz_svc = SVC(kernel='precomputed')
zz_svc.fit(matrix_train, y_train)
zz_score = zz_svc.score(matrix_val, y_test)
print(f'Precomputed kernel classification test score: {zz_score}')
|
https://github.com/jhlee29/quantum-meets-hangul
|
jhlee29
|
# from PIL import Image
from PIL import Image, ImageOps
import os, glob
import numpy as np
from sklearn import model_selection #cross_validation
# from keras.utils import np_utils
# General imports
import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
from pylab import cm
import warnings
# input
classes = ["a", "b"]
# image size of 28 x 28
image_size = 28
# image_size = 8
# Maximum number of sheets to read
max_read = 100
num_classes = len(classes)
# load the image
X = []
Y = []
for index, classlabel in enumerate(classes):
images_dir = "./hangul_characters/" + classlabel
files = glob.glob(images_dir + "/*.jpg")
for i, file in enumerate(files):
# Stop if you read more than max_read to make the number of sheets for each class
if i >= max_read: break
# open the file, read as data, add to X
# Repeatedly add labels with the same index to Y
image = Image.open(file)
image = ImageOps.invert(image)
image = image.convert("L")
image = image.resize((image_size, image_size))
data = np.asarray(image)
X.append(data)
Y.append(index)
X = np.array(X)
Y = np.array(Y)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=0.2, random_state=42)
X_train = X_train.reshape(len(X_train), -1).astype(np.float64)
X_test = X_test.reshape(len(X_test), -1).astype(np.float64)
fig = plt.figure()
LABELS = [0, 1]
num_labels = len(LABELS)
for i in range(num_labels):
ax = fig.add_subplot(1, num_labels, i+1)
img = X[Y==LABELS[i]][0].reshape((28,28))
ax.imshow(img, cmap="Greys")
print(Y)
print(X_train[0])
warnings.filterwarnings("ignore")
# scikit-learn imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Qiskit imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Standardize
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
#sample_test = ss.transform(sample_test)
# Reduce dimensions
N_DIM = 5
pca = PCA(n_components=N_DIM)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
#sample_test = mms.transform(sample_test)
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=5, reps=1, entanglement='linear')
map_zz.decompose().draw('mpl')
zz_kernel = QuantumKernel(feature_map=map_zz, quantum_instance=Aer.get_backend('statevector_simulator'))
matrix_train = zz_kernel.evaluate(x_vec=X_train)
matrix_val = zz_kernel.evaluate(x_vec=X_test, y_vec=X_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_val),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("validation kernel matrix")
plt.show()
zz_svc = SVC(kernel='precomputed')
zz_svc.fit(matrix_train, y_train)
zz_score = zz_svc.score(matrix_val, y_test)
print(f'Precomputed kernel classification test score: {zz_score}')
|
https://github.com/jhlee29/quantum-meets-hangul
|
jhlee29
|
# from PIL import Image
from PIL import Image, ImageOps
import os, glob
import numpy as np
from sklearn import model_selection #cross_validation
# General imports
import os
import gzip
import numpy as np
import matplotlib.pyplot as plt
from pylab import cm
import warnings
# input
classes = ["bul", "pul", "ppul"]
# image size of 28 x 28
image_size = 28
# Maximum number of sheets to read
max_read = 60
num_classes = len(classes)
# load the image
X = []
Y = []
T = []
for index, classlabel in enumerate(classes):
images_dir = "./triple/" + classlabel
files = glob.glob(images_dir + "/*.jpg")
for i, file in enumerate(files):
# Stop if you read more than max_read to make the number of sheets for each class
if i >= max_read: break
# open the file, read as data, add to X
# Repeatedly add labels with the same index to Y
image = Image.open(file)
image = ImageOps.invert(image)
image = image.convert("L")
image = image.resize((image_size, image_size))
data = np.asarray(image)
X.append(data)
Y.append(index)
images_dir = "./triple"
files = glob.glob(images_dir + "/*.jpg")
for i, file in enumerate(files):
# open the file, read as data, add to X
# Repeatedly add labels with the same index to Y
if i >= 36: break
image = Image.open(file)
image = ImageOps.invert(image)
image = image.convert("L")
image = image.resize((image_size, image_size))
data = np.asarray(image)
T.append(data)
X = np.array(X)
Y = np.array(Y)
T = np.array(T)
print(X.shape,T.shape)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y, test_size=0.2, random_state=42)
X_train = X_train.reshape(len(X_train), -1).astype(np.float64)
X_test = X_test.reshape(len(X_test), -1).astype(np.float64)
T = T.reshape(len(T), -1).astype(np.float64)
fig = plt.figure()
LABELS = [0, 1, 2]
num_labels = len(LABELS)
for i in range(num_labels):
ax = fig.add_subplot(1, num_labels, i+1)
img = X[Y==LABELS[i]][0].reshape((28,28))
ax.imshow(img, cmap="Greys")
print(Y)
print(X_train[0])
warnings.filterwarnings("ignore")
# scikit-learn imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Qiskit imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Standardize
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
sample_test = ss.transform(T)
print(sample_test)
# Reduce dimensions
N_DIM = 5
pca = PCA(n_components=N_DIM)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
sample_test = pca.transform(sample_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
sample_test = mms.transform(sample_test)
# label 0
labels_train_0 = np.where(y_train==0, 1, 0)
labels_val_0 = np.where(y_test==0, 1, 0)
print(f'Original validation labels: {y_test}')
print(f'Validation labels for 0 vs Rest: {labels_val_0}')
pauli_map_0 = PauliFeatureMap(feature_dimension=N_DIM, reps=2, paulis = ['X', 'Y', 'ZZ'])
pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator'))
pauli_svc_0 = SVC(kernel='precomputed', probability=True)
matrix_train_0 = pauli_kernel_0.evaluate(x_vec=X_train)
pauli_svc_0.fit(matrix_train_0, labels_train_0)
matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=X_train)
pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0)
print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%')
matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=X_train)
pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1]
print(f'Probability of label 0: {np.round(pred_0, 2)}')
# label 1
labels_train_1 = np.where(y_train==1, 1, 0)
labels_val_1 = np.where(y_test==1, 1, 0)
print(f'Original validation labels: {y_test}')
print(f'Validation labels for 0 vs Rest: {labels_val_1}')
zz_map_1 = ZZFeatureMap(feature_dimension=N_DIM, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel_1 = QuantumKernel(feature_map=zz_map_1, quantum_instance=Aer.get_backend('statevector_simulator'))
zzpc_svc_1 = SVC(kernel='precomputed', probability=True)
matrix_train_1 = zz_kernel_1.evaluate(x_vec=X_train)
zzpc_svc_1.fit(matrix_train_1, labels_train_1)
matrix_val_1 = zz_kernel_1.evaluate(x_vec=X_test, y_vec=X_train)
zzpc_score_1 = zzpc_svc_1.score(matrix_val_1, labels_val_1)
print(f'Accuracy for validation dataset: {zzpc_score_1}')
matrix_test_1 = zz_kernel_1.evaluate(x_vec=sample_test, y_vec=X_train)
pred_1 = zzpc_svc_1.predict_proba(matrix_test_1)[:, 1]
print(pred_1)
# label 2
labels_train_2 = np.where(y_train==2, 1, 0)
labels_val_2 = np.where(y_test==2, 1, 0)
print(f'Original validation labels: {y_test}')
print(f'Validation labels for 0 vs Rest: {labels_val_2}')
zz_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel_2 = QuantumKernel(feature_map=zz_map_2, quantum_instance=Aer.get_backend('statevector_simulator'))
zzpc_svc_2 = SVC(kernel='precomputed', probability=True)
matrix_train_2 = zz_kernel_2.evaluate(x_vec=X_train)
zzpc_svc_2.fit(matrix_train_2, labels_train_2)
matrix_val_2 = zz_kernel_2.evaluate(x_vec=X_test, y_vec=X_train)
zzpc_score_2 = zzpc_svc_2.score(matrix_val_2, labels_val_2)
print(f'Accuracy for validation dataset: {zzpc_score_2}')
matrix_test_2 = zz_kernel_2.evaluate(x_vec=sample_test, y_vec=X_train)
pred_2 = zzpc_svc_2.predict_proba(matrix_test_2)[:, 1]
print(pred_2)
# prediction
pred_test = np.where((pred_0 > pred_1) & (pred_0 > pred_2),
0, np.where(pred_1 > pred_2, 1, 2))
print(f'Prediction: {pred_test}')
|
https://github.com/andre-juan/qiskit_certificate_sample_test
|
andre-juan
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# main classes and functions
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, BasicAer, execute
# visualization stuff
from qiskit.visualization import (plot_histogram, plot_bloch_multivector,
plot_state_city, plot_state_hinton,
plot_state_qsphere,
plot_state_paulivec,
plot_bloch_multivector,
plot_bloch_vector,
plot_gate_map,
plot_error_map)
# gates
from qiskit.circuit.library import CXGate, MCMT, XGate
# quantum info theory stuff
from qiskit.quantum_info import Operator, Statevector, state_fidelity, process_fidelity, average_gate_fidelity
# other tools
from qiskit.tools import job_monitor
from qiskit import IBMQ
def show_figure(fig):
'''
auxiliar function to display plot
even if it's not the last command of the cell
from: https://github.com/Qiskit/qiskit-terra/issues/1682
'''
new_fig = plt.figure()
new_mngr = new_fig.canvas.manager
new_mngr.canvas.figure = fig
fig.set_canvas(new_mngr.canvas)
plt.show(fig)
def test_circuit_qasm(qc):
'''
auxiliar function, used to run a given quantum circuit with the qasm simulator.
measurement is added in this function, so you must pass a circuit
with no classical registers and measurements.
'''
qc.measure_all()
#################################
backend = Aer.get_backend("qasm_simulator")
job = execute(qc, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
return plot_histogram(counts, title="Results", figsize=(12, 4))
def test_circuit_sv(qc, print_stuff=True):
'''
auxiliar function, used to run a given quantum circuit with the statevector simulator.
it optinally prints the state vector components and respective probabilities.
'''
backend = Aer.get_backend("statevector_simulator")
job = execute(qc, backend, seed_simulator=42)
results = job.result()
counts = results.get_counts()
if print_stuff:
sv = results.data(0)['statevector']
probs = sv**2
print(f"Statevector:\t{sv}\n")
print(f"Probabilities:\t{probs}")
return plot_histogram(counts, title="Results", figsize=(12, 4))
# 1 - A)
qc = QuantumCircuit(4, 4)
qc.qregs, qc.cregs
# 2 - C)
qc = QuantumCircuit(1)
qc.ry(3*np.pi/4, 0)
test_circuit_sv(qc)
# 3 - A), B) & D) are possible
inp_reg = QuantumRegister(2, name="inp")
ancilla = QuantumRegister(1, name="anc")
qc = QuantumCircuit(inp_reg, ancilla)
qc.h(inp_reg)
qc.x(ancilla)
qc.barrier()
qc.h(inp_reg[0])
qc.h(inp_reg[1])
qc.x(ancilla)
qc.barrier()
qc.h(inp_reg[0:2])
qc.x(ancilla[0])
qc.draw("mpl")
# 4 - A)
inp = QuantumRegister(3, name="q")
meas = ClassicalRegister(3, name="c")
qc = QuantumCircuit(inp, meas)
# # this would also be possible, but it's not in options
# qc.measure(inp, meas)
qc.measure([0, 1, 2], [0, 1, 2])
qc.draw("mpl")
# 5 - A)
bell = QuantumCircuit(2)
# this makes |01> + |10>
bell.h(0)
bell.x(1)
bell.cx(0, 1)
show_figure(bell.draw("mpl"))
test_circuit_sv(bell)
# 6 - A) & C)
qc = QuantumCircuit(1, 1)
# # both below are equivalent
# qc.h(0)
qc.ry(np.pi/2, 0)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
job = execute(qc, simulator)
results = job.result()
outputstate = results.get_statevector(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# 7 - B)
# S gate induces a pi/2 phase! (is a P gate with \theta = pi/2, i.e., it's a Rz gate with \theta = pi/2)
# tip: S = T^2, hence the "S" stands for "T Squared" (not sure if that's the actual reason for the name, but it's a mnemonic)
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
job = execute(qc, simulator)
results = job.result()
outputstate = results.get_statevector(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# another way to get the statevector, using the Statevector class
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
show_figure(qc.draw("mpl"))
outputstate = Statevector.from_label("0").evolve(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# 8 - A), B)
qc = QuantumCircuit(2)
# # both options below work
# v = [1/np.sqrt(2), 0, 0, 1/np.sqrt(2)]
# qc.initialize(v, [0, 1])
qc.h(0)
qc.cx(0, 1)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
result = execute(qc, simulator).result()
statevector = result.get_statevector(qc)
print(f"\nState:\t{statevector}\n")
# 9 - D)
# notice how the first tree are equivalent to cnot
# the last one is the only multi-qubit gate OTHER THAN a cnot ;)
qc = QuantumCircuit(2)
################################
qc.cx(0, 1)
qc.barrier()
################################
qc.cnot(0, 1)
qc.barrier()
################################
# that's nice! multi-controlled x
qc.mct([0], 1)
qc.barrier()
################################
qc.cz(0, 1)
qc.barrier()
################################
qc.draw("mpl")
# 10 - D)
# notice how the first tree are equivalent to the toffoli gate
# the last one is the only multi-qubit gate OTHER THAN a toffoli ;)
qc = QuantumCircuit(3)
################################
qc.ccx(0, 1, 2)
qc.barrier()
################################
qc.mct([0, 1], 2)
qc.barrier()
################################
# very nice construction!
ccx = CXGate().control()
qc.append(ccx, [0, 1, 2])
qc.barrier()
################################
qc.cry(0, 1, 2)
qc.barrier()
################################
qc.draw("mpl")
# another nice way to do toffoli
qc = QuantumCircuit(3)
mct = MCMT(gate='x', num_ctrl_qubits = 2, num_target_qubits = 1)
qc.append(mct, [0,1,2])
qc = qc.decompose()
qc.draw("mpl")
# 11 - B) & C)
qc = QuantumCircuit(3, 3)
qc.barrier()
qc.barrier([0, 1, 2])
qc.draw("mpl")
# 12 - A)
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.t(0)
qc.t(0)
qc.h(0)
qc.measure(0, 0)
show_figure(qc.draw("mpl"))
print("\nSince S = T^2, the circuit above is equivalent to:")
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.measure(0, 0)
show_figure(qc.draw("mpl"))
# 13 - A)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.barrier(0)
qc.cx(0, 1)
qc.barrier([0, 1])
# take a look in the docstring!
print(f"\nDepth of the circuit: {qc.depth()}")
qc.draw("mpl")
# 14 - A)
qc = QuantumCircuit(3)
qasm_sim = Aer.get_backend("qasm_simulator")
# coupling map connecting 3 qubits linearly
couple_map = [[0, 1], [1, 2]]
job = execute(qc, qasm_sim, shots=1024, coupling_map=couple_map)
result = job.result()
# 15 - A)
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(3)
execute(qc, backend, shots=1024, coupling_map=[[0, 1], [1, 2]])
# 16 - A), C) & D)
# answer here: https://qiskit.org/documentation/apidoc/providers_basicaer.html#simulators
qasm = BasicAer.get_backend("qasm_simulator")
sv = BasicAer.get_backend("statevector_simulator")
unitary = BasicAer.get_backend("unitary_simulator")
# 17 - B)
backend = BasicAer.get_backend("statevector_simulator")
# 18 - C)
# info: https://qiskit.org/documentation/stubs/qiskit.quantum_info.Operator.html
# # i think the following is possible:
# op = Operator([[0, 1], [1, 0]])
qc = QuantumCircuit(1)
qc.x(0)
op = Operator(qc)
op
# 19 - C)
# info here: https://qiskit.org/documentation/tutorials/circuits_advanced/02_operators_overview.html#Process-Fidelity
# namely:
# "We may also compare operators using the process_fidelity function from the Quantum Information module.
# This is an information theoretic quantity for how close two quantum channels are to each other,
# and in the case of unitary operators it does not depend on global phase."
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
pF = process_fidelity(op_a, op_b)
print(f'\nProcess fidelity pF = {pF}')
agF = average_gate_fidelity(op_a, op_b)
print(f'\nAverage gate fidelity agF = {agF}')
# # code below returns an error, because, of course, op_a and op_b are not states,
# # but operators (processes, gates)
# sF = state_fidelity(op_a, op_b)
# print(f'\nState fidelity sF = {sF}')
# 20 - B)
# BE VERY CAREFUL WITH THE ENDIANNESS!!!
qc = QuantumCircuit(2, 2)
qc.x(0)
# better to visualize order of measurements
qc.barrier()
qc.measure([0, 1], [0, 1])
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("qasm_simulator")
result = execute(qc, simulator, shots=1000).result()
counts = result.get_counts(qc)
print(counts)
# openqasm string
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cnot(0, 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
####################################
show_figure(qc.draw("mpl"))
####################################
print(qc.qasm())
print("\n")
print(qc.qasm(formatted=True))
qasm_str = qc.qasm(filename="qasm_test")
qc_test_str = QuantumCircuit.from_qasm_str(qasm_str)
qc_test_str.draw("mpl")
qc_test_file = QuantumCircuit.from_qasm_file("qasm_test")
qc_test_file.draw("mpl")
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cnot(0, 1)
qc.barrier()
##########################
backend = Aer.get_backend("unitary_simulator")
unitary = execute(qc, backend).result().get_unitary()
unitary
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
sns.heatmap(np.real(unitary), annot=True, ax=ax[0])
ax[0].set_title("Real part")
sns.heatmap(np.imag(unitary), annot=True, ax=ax[1])
ax[1].set_title("Imaginary part")
plt.tight_layout()
plt.show()
qc = QuantumCircuit(3)
qc.h(0)
qc.cnot(0, 1)
qc.cnot(0, 2)
show_figure(qc.draw("mpl"))
####################################
sv = Statevector.from_label("000")
sv = sv.evolve(qc)
print(f'Statevector:\n\n{sv.data}')
show_figure(plot_state_hinton(sv))
####################################
gate = qc.to_gate()
gate.name = "my_gate"
####################################
qc2 = QuantumCircuit(3)
qc2.append(gate, [0, 1, 2])
print("Gate in the circuit:")
show_figure(qc2.draw("mpl"))
print("Decomposed gate in the circuit:")
show_figure(qc2.decompose().draw("mpl"))
# that's more useful when "backend" is a real hardware, of course
job = execute(qc, backend)
job_monitor(job)
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
circ = bell.compose(meas)
show_figure(bell.draw("mpl"))
show_figure(meas.draw("mpl"))
show_figure(circ.draw("mpl"))
backend = Aer.get_backend("qasm_simulator")
job = execute(circ, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
plot_histogram(counts, title="Results", figsize=(6, 4))
simulator = Aer.get_backend("statevector_simulator")
job = execute(bell, simulator)
results = job.result()
psi = results.get_statevector(bell)
print(psi)
# "here we see that there is no information about the quantum state in the single qubit space as all vectors are zero."
# if it was a separable state, it would be shown!
show_figure(plot_bloch_multivector(psi))
show_figure(plot_state_city(psi))
show_figure(plot_state_hinton(psi))
show_figure(plot_state_qsphere(psi))
show_figure(plot_bloch_vector([1,0,0], figsize=(2, 2)))
show_figure(plot_bloch_vector([0,1,0], figsize=(2, 2)))
show_figure(plot_bloch_vector([0,0,1], figsize=(2, 2)))
# already saved my token!
# for more info: https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(simulator=False)
for bcknd in provider.backends(simulator=False):
print(f"\nBackend: {bcknd.name()}")
backend = provider.get_backend(bcknd.name())
show_figure(plot_gate_map(backend, figsize=(3, 3)))
print(f"Coupling map:\n\n{bcknd._configuration.coupling_map}\n")
print("="*50)
print("="*50)
for bcknd in provider.backends(simulator=False):
print(f"\nBackend: {bcknd.name()}")
backend = provider.get_backend(bcknd.name())
show_figure(plot_error_map(backend))
print("="*50)
print("="*50)
|
https://github.com/mberna/qce22-qiskit-runtime-tutorial
|
mberna
|
# define Hamiltonian
from qiskit.opflow import PauliSumOp
H = PauliSumOp.from_list([('XYII', 1), ('IYZI', 2), ('IIZX', 3), ('XIII', 4), ('IYII', 5)])
print(H)
from qiskit.circuit.library import EfficientSU2
qc = EfficientSU2(num_qubits=H.num_qubits, reps=1)
qc_with_meas = qc.measure_all(inplace=False)
qc_with_meas.decompose().draw(fold=120)
# define a set of (random) parameter values for the ansatz circuit
import numpy as np
theta = np.random.rand(qc.num_parameters)
# use the Sampler to sample from this circuit
from qiskit.primitives import Sampler
sampler = Sampler([qc_with_meas])
s_result = sampler([qc_with_meas], [theta])
print(s_result)
from qiskit.primitives import Estimator
estimator = Estimator([qc], [H])
e_result = estimator([qc], [H], [theta])
print(e_result)
from qiskit.algorithms import NumPyEigensolver
exact_solver = NumPyEigensolver(k=2) # find the first two '2' eigenvalues
exact_result = exact_solver.compute_eigenvalues(H)
print(exact_result.eigenvalues)
# define objective as expectation value of Hamiltonian with circuit ansatz
objective = lambda x: estimator([qc], [H], [x]).values[0]
# instantiate optimizer
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(maxiter=500)
# define initial values for our circuit parameters
x0 = np.random.rand(qc.num_parameters)
# minimize the objective function
result = optimizer.minimize(objective, x0=x0)
# store ground state parameters for later
ground_state_params = result.x
# print the resulting ground state energy
print(result.fun)
from qiskit.algorithms import MinimumEigensolver, VQEResult
class CustomVQE(MinimumEigensolver):
def __init__(self, estimator, circuit, optimizer, callback=None):
self._estimator = estimator
self._circuit = circuit
self._optimizer = optimizer
self._callback = callback
def compute_minimum_eigenvalue(self, operator, aux_operators=None):
# define objective
def objective(x):
e_job = self._estimator([self._circuit], [operator], [x])
value = e_job.values[0]
if self._callback:
self._callback(value)
return value
# run optimization
x0 = np.random.rand(self._circuit.num_parameters)
res = self._optimizer.minimize(objective, x0=x0)
# populate results
result = VQEResult()
result.cost_function_evals = res.nfev
result.eigenvalue = res.fun
result.optimal_parameters = res.x
return result
# run the custom VQE function
custom_vqe = CustomVQE(estimator, qc, optimizer)
result = custom_vqe.compute_minimum_eigenvalue(H)
print(result)
from qiskit.circuit import ParameterVector
class Fidelity():
def __init__(self, sampler):
""" Instantiate fidelity estimator. """
#self._sampler = sampler
def run(self, circuit_1, circuit_2, param_values_1, param_values_2):
""" Estimate fidelity between two states defined by given parameter values."""
# prepare circuit
circuit_1_ = circuit_1.remove_final_measurements(inplace=False)
circuit_2_ = circuit_2.remove_final_measurements(inplace=False)
x = ParameterVector("x", circuit_1_.num_parameters)
y = ParameterVector("y", circuit_2_.num_parameters)
circuit = circuit_1_.assign_parameters(x).compose(circuit_2_.inverse().assign_parameters(y))
circuit.measure_all()
# run circuit and get probabilities
param_values = np.append(param_values_1, param_values_2)
sampler = Sampler([circuit])
s_job = sampler([circuit], [param_values])
probabilities = s_job.quasi_dists[0]
# estimate fidelity: |<0|U_1^dag U_2|0>|^2 clipped to [0, 1]
fidelity = np.minimum(1.0, np.maximum(0.0, probabilities.get(0, 0.0)))
return fidelity
# instantiate fidelity
fidelity = Fidelity(sampler)
# interpolation between parameters
ts = np.linspace(0, 1)
fidelities = [fidelity.run(qc, qc, ground_state_params, ground_state_params + t*theta) for t in ts]
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 4))
plt.plot(ts, fidelities)
plt.xlabel('t', fontsize=20)
plt.ylabel('fidelity', fontsize=20)
plt.show()
# set penalty weight for overlap term
penalty = 25
# define objective for VQD
vqd_objective = lambda x: objective(x) + penalty*fidelity.run(qc, qc, ground_state_params, x)
# run optimization to get first excited state
result = optimizer.minimize(vqd_objective, ground_state_params)
print(result)
# determine energy
e_job = estimator([qc], [H], [result.x])
print(e_job)
fid = fidelity.run(qc, qc, result.x, ground_state_params);
print(fid)
from qiskit.algorithms import Eigensolver, EigensolverResult
class VQD(Eigensolver):
def __init__(self, estimator, fidelity, circuit, optimizer, penalty=25, callback=None):
# self._estimator = estimator
self._fidelity = fidelity
self._circuit = circuit
self._optimizer = optimizer
self._penalty = penalty
self._callback = callback
def compute_eigenvalues(self, operator, aux_operators=None):
# compute ground state
estimator = Estimator([self._circuit], [operator])
energy = lambda x: estimator([self._circuit], [operator], [x]).values[0]
x0 = np.random.rand(self._circuit.num_parameters)
res_1 = self._optimizer.minimize(energy, x0)
# compute first excited states
overlap = lambda x: self._fidelity.run(self._circuit, self._circuit, res_1.x, x)
def objective(x):
value = energy(x) + self._penalty * overlap(x)
if self._callback:
self._callback(value)
return value
res_2 = self._optimizer.minimize(objective, res_1.x)
# populate results
result = EigensolverResult()
result.eigenvalues = [estimator([self._circuit], [operator], [res_1.x]),
estimator([self._circuit], [operator], [res_2.x])]
return result
vqd = VQD(estimator, fidelity, qc, optimizer=SPSA(maxiter=1000))
result = vqd.compute_eigenvalues(H)
print(result)
from qiskit_ibm_runtime import (Session, Options, QiskitRuntimeService,
Sampler as RuntimeSampler,
Estimator as RuntimeEstimator)
service = QiskitRuntimeService(channel='ibm_quantum')
from qiskit.algorithms.optimizers import COBYLA
optimizer = COBYLA(maxiter=400)
with Session(service=service, backend='ibmq_qasm_simulator') as session:
# prepare primitives
rt_estimator = RuntimeEstimator(session=session)
rt_sampler = RuntimeSampler(session=session)
rt_fidelity = Fidelity(rt_sampler)
# set up algorithm
rt_vqd = VQD(rt_estimator, rt_fidelity, qc, optimizer)
# run algorithm
result = rt_vqd.compute_eigenvalues(H)
print(result)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mberna/qce22-qiskit-runtime-tutorial
|
mberna
|
# instantiate runtime service
from qiskit_ibm_runtime import QiskitRuntimeService
QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN")
service = QiskitRuntimeService(channel="ibm_quantum")
# import required libraries and instantiate runtime service
from qiskit_ibm_runtime import Session, Estimator, Options
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
# create circuits and observables
psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
psi1.decompose().draw(output='mpl')
psi2.decompose().draw(output='mpl')
import numpy as np
# generate random theta params
np.random.seed(0)
theta1 = np.random.rand(6) * np.pi
theta2 = np.random.rand(8) * np.pi
theta3 = np.random.rand(6) * np.pi
print(theta1)
print(theta2)
print(theta3)
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session)
from qiskit_ibm_runtime import Options
options = Options(optimization_level=1)
options.execution.shots = 1024
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session, options=options)
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1],
parameter_values=[theta1])
print(psi1_H1.result())
# You can invoke run() multiple times!
# calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ]
psi1_H23 = estimator.run(circuits=[psi1, psi1], observables=[H2, H3],
parameter_values=[theta1]*2)
print(psi1_H23.result())
# Ex. 1: Calculate [ <psi2(theta2)|H2|psi2(theta2)> ]
# psi2_H2 = ...
# Ex. 2 calculate [ <psi1(theta1)|H1|psi1(theta1)>,
# <psi2(theta2)|H2|psi2(theta2)>,
# <psi1(theta3)|H3|psi1(theta3)> ]
# psi12_H23 = ...
# Ex. 3: use optimization_level 3
options = Options()
# options... # hint: use autocomplete
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session, options=options)
theta4 = [0, 1, 1, 2, 3, 5]
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4])
print(psi1_H1.result())
# Ex. 4: Apply REM to the following example
# Remeber REM is enabled when resilience level is 1
options = Options()
# options... # hint: use autocomplete
with Session(service=service, backend="ibmq_qasm_simulator",) as session:
estimator = Estimator(session=session, options=options)
theta4 = [0, 1, 1, 2, 3, 5]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4])
print(psi1_H1.result())
from qiskit import QuantumCircuit
from qiskit_ibm_runtime import Sampler
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
with Session(service=service, backend="ibmq_qasm_simulator") as session:
sampler = Sampler(session=session, options=options)
job = sampler.run(circuits=bell)
print(job.result())
# You can invoke run() multiple times.
job = sampler.run(circuits=bell)
print(job.result())
## REM sampler
from qiskit import QuantumCircuit
from qiskit_ibm_runtime import Sampler, Options, Session
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
options_rem = Options(resilience_level=1)
with Session(service=service, backend="ibmq_qasm_simulator") as session:
sampler = Sampler(session=session)
job = sampler.run(circuits=bell)
sampler_rem = Sampler(session=session, options=options_rem)
job_rem = sampler_rem.run(circuits=bell)
print(f"Quasi_dist without EM {job.result().quasi_dists}")
print(f"Quasi_dist with EM {job_rem.result().quasi_dists}")
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import numpy as np
from qiskit import *
def Qand(First_bool,Second_bool):
#input two booleans into the function
a = int(First_bool)
b = int(Second_bool)
#quantum circuit that applies a Toffoli gate
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
# Code for giving a True if the 3rd qubit is 1 and False if the 3rd qubit is 0
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
Q_and = bool(int(np.real(outputstate[7])))
return Q_and
def Qor(First_bool,Second_bool):
#input two booleans into the function
a = int(First_bool)
b = int(Second_bool)
#quantum circuit that applies a Toffoli gate
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
# Code for giving a True at least one of the two control qubits are in state 1
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
if a is 1 and b is 0:
Q_or = bool(int(np.real(outputstate[1])))
elif a is 0 and b is 1:
Q_or = bool(int(np.real(outputstate[2])))
else:
Q_or = bool(int(np.real(outputstate[7])))
return(Q_or)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
%matplotlib notebook
import pew
pew.init()
screen=pew.Pix()
# First we set variables of the game:
# The snake will be represented by a list of (x,y) coordinates. The last element of the list (snake[-1]) will
# represent the head of the snake. The 0th element of the list will be the last pixel of the tail.
# Let's create the list by setting the initial position of the head at (3,3):
snake=[(3,3)]
# Now we create a variable to store the speed of the movement:
game_speed=5
# We also have to define the initial velocity of the snake. Let's set it to move in the x direction by 1 pixel.
dx, dy= 1, 0
# First we create and endless loop for the movement of the snake
while True:
x,y=snake[-1] # We store the current position of the head in two variables x and y.
screen.pixel(x, y, 3) # This command turns on the pixel (x,y) with the maximum brightnes (3) to print on
# on the screen the current position of the head
pew.show(screen) # Lights up the active pixels on the screen. We need to pew.show(screen) each frame of the game.
pew.tick(1/game_speed) # Sets the refresh rate. When bigger "game_speed" the lower the refresh rate and the game
# runs faster
# Now we have to check for user input by looking which keys are pressed. Depending on which keys are pressed the velocity of
# of the snake will change.
keys=pew.keys() # Return a number telling which keys (or buttons) have been pressed since the
# last check. The number can then be filtered with the ``&`` operator and
# the ``K_X``, ``K_DOWN``, ``K_LEFT``, ``K_RIGHT``, ``K_UP``, and ``K_O``
# constants to see whether any of the keys was pressed.
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
# When the snake is moving in x and wee press UP the velocity of the snake changes to go up in the screen.
# Note that in the pew-pew screen the index of the top row is 0 and the index of the bottom row is 7.
# This explains why we have dy=-1 when we press UP. The rest of the keys follow a similar logic.
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
# Now we calculate the next position of the snake's head:
x=(x+dx)%8
y=(y+dy)%8
# We insert %8 to apply mod 8 to the coordinates, so when we pass through one of the walls we restart the counting and
# appear in the other side of the screen.
# We add to the list representing our snake a the next position of the head.
snake.append((x,y))
#We delete from the list the last position of the snake (in this case the head) and turn of that pixel
(x,y)=snake.pop(0)
screen.pixel(x,y,0)
import pew
pew.init()
screen=pew.Pix()
snake=[(3,3)]
game_speed=5
dx, dy= 1, 0
while True:
x,y=snake[-1]
screen.pixel(x, y, 3)
pew.show(screen)
pew.tick(1/game_speed)
keys=pew.keys()
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
#To implement the crashing mechanism we first have to get rid from the periodic screen, so we remove %8
x=(x+dx)
y=(y+dy)
#Now add an if condition that breaks the while loop if any of the coordinates for the new head goes out from the grid.
if x >7 or y > 7 or x < 0 or y < 0:
# We create a loop for turning of all the pixels that forms the screen.
for (i,j) in snake:
screen.pixel(i,j,0)
break
snake.append((x,y))
(x,y)=snake.pop(0)
screen.pixel(x,y,0)
# Now that we are out the loop we show the "Game Over" screen:
text = pew.Pix.from_text("Game over!")
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
from aether import QuantumCircuit, simulate
def qrand(nbits):
# We import the necessary elements form the aether library
circ= QuantumCircuit(1,1) # We create a circuit with 1 qubit register and 1 classical bit register
circ.h(0) # We apply the Hadamard gate to the qubit (note that by default the qubits are already intializated at 0)
circ.measure(0, 0) # We make a measurement in the qubit and we store the result in the classical bit
val = simulate(circ, shots=nbits, get='memory') # We simulate three times the circuit and we store the results in a list
# We create a string with the binary number to use the function int() to obtain the integer
b=''
for i in range(nbits):
b+= str(val[i])
# Trnsform the string into an int
integ=int(b,2)
# Return the integer
return integ
import pew
from aether import QuantumCircuit, simulate
# We define the function that we just created at the beginning of our code
def qrand(nbits):
circ= QuantumCircuit(1,1)
circ.h(0)
circ.measure(0, 0)
val = simulate(circ, shots=nbits, get='memory')
b=''
for i in range(nbits):
b+= str(val[i])
integ=int(b,2)
return integ
pew.init()
screen=pew.Pix()
snake=[(3,3)]
game_speed=5
dx, dy= 1, 0
# We must define the initial position of the apple:
apple_x, apple_y = 6, 6
screen.pixel(apple_x, apple_y, 3)
while True:
x,y=snake[-1]
screen.pixel(x, y, 3)
pew.show(screen)
pew.tick(1/game_speed)
keys=pew.keys()
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
x=(x+dx)
y=(y+dy)
# We need to add the condition that if the next position of the snake's head is in the snake's body the player dies
if (x,y) in snake or x >7 or y > 7 or x < 0 or y < 0:
# We create a loop for turning of all the pixels that forms the screen.
for (i,j) in snake:
screen.pixel(i,j,0)
break
snake.append((x,y))
# In this loop we implement the generation of the apples each time the next position of the snake's head
# lies into the current position of the apple
if x == apple_x and y == apple_y:
screen.pixel(apple_x, apple_y, 0)
# We try the random generation of the apple until the apple appears out of the snake
apple_x, apple_y = snake[0]
while (apple_x, apple_y) in snake:
apple_x=qrand(3)
apple_y=qrand(3)
screen.pixel(apple_x, apple_y, 2)
# We also increase the velocity of the game each time the snake eats an apple
gm_sp += 0.2
# Otherwise we remove the tail of the snake
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!")
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
import pew
from aether import QuantumCircuit, simulate
def qrand(nbits):
circ= QuantumCircuit(1,1)
circ.h(0)
circ.measure(0, 0)
val = simulate(circ, shots=nbits, get='memory')
b=''
for i in range(nbits):
b+= str(val[i])
integ=int(b,2)
return integ
pew.init()
screen=pew.Pix()
l=True # We initialize a boolean that will help us to reset the initial conditions of the game
while True:
#Now we put the condition of reseting the initial variables only if l=True
if l:
game_speed=5
points=0 # We initialize a variable to count the points
snake = [(3,3)]
dx, dy = 1, 0
apple_x, apple_y = 6, 6
screen.pixel(apple_x, apple_y, 3)
l=False
while True:
x,y=snake[-1]
screen.pixel(x, y, 3)
pew.show(screen)
pew.tick(1/game_speed)
keys=pew.keys()
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
x=(x+dx)
y=(y+dy)
if (x,y) in snake or x >7 or y > 7 or x < 0 or y < 0:
for (i,j) in snake:
screen.pixel(i,j,0)
break
snake.append((x,y))
if x == apple_x and y == apple_y:
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while (apple_x, apple_y) in snake:
apple_x=qrand(3)
apple_y=qrand(3)
screen.pixel(apple_x, apple_y, 2)
game_speed += 0.2
# We add one to the points counter each time we eat an apple
points=points+1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
l=True # We set l to True to restart to the initial variables in the next iteration
#Now let's display the points in the screen:
text = pew.Pix.from_text('Points: ' + str(points))
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Game over!")
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import random
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('statevector_simulator')
#################################################################
###################
#IBMQ real backends
###################
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
# Load local account information
provider = IBMQ.load_account()
def ibmq_qrand(nbits, N):
# Get the least busy real quantum system
backend = least_busy(provider.backends(simulator=False))
print(backend, backend.status().pending_jobs)
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
job = execute(circ, backend, memory=True, shots=int(N*nbits))
res = job.result()
val = res.get_memory()
print(val)
integ = np.zeros(N)
for k in range(N):
#convert val array into bitstring b and then into integer
b = ''
shift = int(nbits * k)
for i in range(nbits):
b += str(val[i+shift])
integ[k] = int(b, 2)
return integ
def get_rand_from_list(counter, list):
return list[counter]
###############################################################
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
val = np.zeros(nbits)
for i in range(nbits):
job=execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val[i] = vec[0] * 1 + vec[1] * 0
#convert val array into bitstring b and then into integer
b = ''
for i in range(nbits):
b += str(int(val[i]))
integ = int(b, 2)
return integ
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
#qcirc
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val = vec[0] * 1 + vec[1] * 0
if val == 1:
return 0
else:
return 1
#r= random.randint(0, 1)
#return round(r)
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 2)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
num_list = ibmq_qrand(3, 250) #list of random numbers for ibmq function
num_list_x = num_list[:125]
num_list_y = num_list[125:]
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 1)
screen.pixel(ds-1, i, 1)
screen.pixel(i, 0, 1)
screen.pixel(i, ds-1, 1)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
x = (x + dx) % 8
y = (y + dy) % 8
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=2
elif headtunnel>=2:
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=0
##TUNNELING PROCESS
#snake tail tunnels
if tunnel>0 and snakepos<=len(snake):
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if tunnel>0 and snakepos==(len(snake)+1):
tunnel=0
snakepos=1
#snake head tunnels
if headtunnel==0 and (x, y) in bar:
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnel==0 and len(snake) != 1: #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif headtunnel==1 and (x, y) in bar:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if x == apple_x and y == apple_y:
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while (apple_x, apple_y) in snake or (apple_x, apple_y) in bar:
apple_x = get_rand_from_list(howmanyapples, num_list_x) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = get_rand_from_list(howmanyapples, num_list_y) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 2)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import random
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('statevector_simulator')
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
val = np.zeros(nbits)
for i in range(nbits):
job=execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val[i] = vec[0] * 1 + vec[1] * 0
#convert val array into bitstring b and then into integer
b = ''
for i in range(nbits):
b += str(int(val[i]))
integ= int(b, 2)
return integ
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
#qcirc
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val = vec[0] * 1 + vec[1] * 0
if val == 1:
return 0
else:
return 1
#r= random.randint(0, 1)
#return round(r)
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 2)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 1)
screen.pixel(ds-1, i, 1)
screen.pixel(i, 0, 1)
screen.pixel(i, ds-1, 1)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
x = (x + dx) % 8
y = (y + dy) % 8
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=2
elif headtunnel>=2:
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=0
##TUNNELING PROCESS
#snake tail tunnels
if tunnel>0 and snakepos<=len(snake):
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if tunnel>0 and snakepos==(len(snake)+1):
tunnel=0
snakepos=1
#snake head tunnels
if headtunnel==0 and (x, y) in bar:
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnel==0 and len(snake) != 1: #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif headtunnel==1 and (x, y) in bar:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if x == apple_x and y == apple_y:
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while (apple_x, apple_y) in snake or (apple_x, apple_y) in bar:
apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = qrand(bits) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 2)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import random
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('statevector_simulator')
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
val = np.zeros(nbits)
for i in range(nbits):
job=execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val[i] = vec[0] * 1 + vec[1] * 0
#convert val array into bitstring b and then into integer
b = ''
for i in range(nbits):
b += str(int(val[i]))
integ= int(b, 2)
return integ
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
#qcirc
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator)
res = job.result()
vec = res.get_statevector()
val = vec[0] * 1 + vec[1] * 0
if val == 1:
return 0
else:
return 1
#r= random.randint(0, 1)
#return round(r)
def Qand(First_bool,Second_bool):
a = int(First_bool)
b = int(Second_bool)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
qc.draw()
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
Q_and = bool(int(np.real(outputstate[7])))
return Q_and
def Qor(First_bool,Second_bool):
a = int(First_bool)
b = int(Second_bool)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
qc.draw()
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
if a is 1 and b is 0:
Q_or = bool(int(np.real(outputstate[1])))
elif a is 0 and b is 1:
Q_or = bool(int(np.real(outputstate[2])))
else:
Q_or = bool(int(np.real(outputstate[7])))
return(Q_or)
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 2)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 1)
screen.pixel(ds-1, i, 1)
screen.pixel(i, 0, 1)
screen.pixel(i, ds-1, 1)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if Qand(bool(int(keys & pew.K_UP)),dy == 0) is True:
dx, dy = 0, -1
#print(bool(int(keys & pew.K_UP)))
#print(dy == 0)
#print(Qand(bool(int(keys & pew.K_UP)),dy == 0))
elif Qand(bool(int(keys & pew.K_LEFT)),dx == 0) is True:
#print(str(keys & pew.K_LEFT) + 'right')
dx, dy = -1, 0
elif Qand(bool(int(keys & pew.K_RIGHT)),dx == 0) is True:
#print(str(keys & pew.K_RIGHT) + 'right')
dx, dy = 1, 0
elif Qand(bool(int(keys & pew.K_DOWN)),dy == 0) is True:
#print(str(keys & pew.K_DOWN) + 'down')
dx, dy = 0, 1
x = (x + dx) % 8
y = (y + dy) % 8
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=2
elif headtunnel>=2:
x = (x + dx) % 8
y = (y + dy) % 8
headtunnel=0
##TUNNELING PROCESS
#snake tail tunnels
if Qand(tunnel>0,snakepos<=len(snake)) is True:
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if Qand(tunnel>0, snakepos==(len(snake)+1)) is True:
tunnel=0
snakepos=1
#snake head tunnels
if Qand(headtunnel==0, (x, y) in bar) is True:
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if Qand(tunnel==0, len(snake) != 1) is True: #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif Qand(headtunnel==1, (x, y) in bar) is True:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if Qand(x == apple_x, y == apple_y) is True:
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while Qor((apple_x, apple_y) in snake, (apple_x, apple_y) in bar) is True:
apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = qrand(bits) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 2)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_tunnel as pew
import pygame
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
import numpy as np
#########################################################################
#FUNCTIONS
#########################################################################
simulator = Aer.get_backend('qasm_simulator')
shot=1
def Qand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qnand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.x(2)
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qor(First_bool,Second_bool):
return Qnand(Qnand(First_bool,First_bool),Qnand(Second_bool,Second_bool))
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
b=''#string holder
for i in range(nbits):
job=execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1] #find the measured state, this is a list
b=b+state[0] #state[0] is a string
return int(b, 2)
def Pt(U0, E, L, betac, gamma_sqc):
"""return tunneling probability for square barrier"""
return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
def beta(U0, E):
"""supply function for Pt"""
return np.sqrt(2* (U0 - E))
def gamma_sq(U0, E):
"""supply function for Pt"""
return 0.25 * ((1 - E/U0)/(E/U0) + (E/U0)/(1-E/U0) - 2)
def theta(p_tunnel):
"""returns rotation angle corresponding to tunneling prob. p_tunnel"""
return 2 * np.arcsin(np.sqrt(p_tunnel))
def tunnelres(U0, length_snake, L, betac, gamma_sqc):
"""returns 0 if tunnel, returns 1 if no tunnel"""
P_t = Pt(U0, length_snake, L, betac, gamma_sqc) #get tunneling prob depending on current snake length
theta_rot = theta(P_t) #get rot angle
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circ = QuantumCircuit(qr, cr)
circ.rx(theta_rot, qr[0])
circ.measure(qr, cr)
job = execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1]
return int(state[0])
##########################################################################
#MAIN
##########################################################################
#initialize pew
dis = pew.init()
screen = pew.Pix()
#set size
bits = 3
ds= 2**bits #displazsize
#set game starting parameters
game_speed = 4
snake = [(2, 4)]
dx, dy = 1, 0
apple_x, apple_y = 6, 5
screen.pixel(apple_x, apple_y, 1)
howmanyapples = 1 #marker for total number of eaten apples, used for scoring
#set graphics for probability display
pygame.font.init()
#gate backkgorund
font1 = pygame.font.Font(None, 33)
text = font1.render('Probability for tunneling is', True, (255, 0, 0))
dis.blit(text, (20, 330))
font2 = pygame.font.Font(None, 45)
text2 = font2.render('100%', True, (255, 0, 0))
dis.blit(text2, (130, 360))
ima = pygame.image.load('pewblack.jpg')
#tunneling parameters
U0=37 #max snake length = 6x6 = 36
E=1
L=0.05 #optimal barrier size for nice tunneling probabilities
#initialize tunneling tracker
tunnel=0 #don't see other side as second barrier
snakepos=1 #marker of snakepos, 1=head, increase towards tail
headtunnel=0 #let the head tunnel again through other even if tail still in process
while True: #snake runs
#create barrier
bar= []
for i in range(ds):
screen.pixel(0, i, 2)
screen.pixel(ds-1, i, 2)
screen.pixel(i, 0, 2)
screen.pixel(i, ds-1, 2)
bar.append((0, i))
bar.append((ds-1, i))
bar.append((i, 0))
bar.append((i, ds-1))
#find the head
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3) #color the head yellow
pew.show(screen)
pew.tick(1 / game_speed)
#get commands
keys = pew.keys()
if headtunnel==0:
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
elif headtunnel==1: #steering not allowed during tunneling of the head (during two rounds)
headtunnel=2
elif headtunnel>=2:
headtunnel=0
x = (x + dx) % 8
y = (y + dy) % 8
##TUNNELING PROCESS
#snake tail tunnels
if Qand(tunnel>0 ,snakepos<=len(snake)):
#get segment for tunneling
sx, sy = snake[-snakepos]
E=len(snake)/2 #divide by two for lower tunnel prob for tail (lower mass->lower energy)
tunnels = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if tunnels==1: #tunnels
snakepos+=1
else: #does not tunnel
del snake[-snakepos]
screen.pixel(sx, sy, 0)
#reset if last segment tunneled
if Qand(tunnel>0 ,snakepos==(len(snake)+1)):
tunnel=0
snakepos=1
#snake head tunnels
if Qand(headtunnel==0, (x, y) in bar):
E=len(snake)
tunnel = tunnelres(U0, E, L, beta(U0, E), gamma_sq(U0, E))
if Qand(tunnel==0, len(snake) != 1): #head doesn't tunnel --> game over
break
else:
snakepos+=1
headtunnel+=1
elif headtunnel==1 and (x, y) in bar:
headtunnel=0
#display tunneling prob.
E = len(snake)
if E > 1:
prob = Pt(U0, E, L, beta(U0, E), gamma_sq(U0, E))
text3 = font2.render(str(int(round(prob * 100))) + '%', True, (255, 0, 0))
dis.blit(ima, (130, 360))
dis.blit(text3, (130, 360))
else: #if length of snake ==1 (only head), tunneling prob = 100%
dis.blit(ima, (130, 360)) #cover the ultimate prob. display
dis.blit(text2, (130, 360)) #text2 = '100%'
#####TUNNEL END
if (x, y) in snake: #exit, game over condition
break
snake.append((x, y))
#apple generation
if Qand(x == apple_x, y == apple_y):
screen.pixel(apple_x, apple_y, 0)
apple_x, apple_y = snake[0]
while Qor((apple_x, apple_y) in snake , (apple_x, apple_y) in bar):
apple_x = qrand(bits) #random.getrandbits(3) #use this for pseudo random number gen, no qiskit needed
apple_y = qrand(bits) #random.getrandbits(3)
screen.pixel(apple_x, apple_y, 1)
game_speed += 0.2 #increase game speed
howmanyapples += 1 #increase number of eaten apples, score +1
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
text = pew.Pix.from_text("Game over!") #Game over message and closing
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
text = pew.Pix.from_text("Score:" + str(int(howmanyapples))) #Score message
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_circuit as pew
from qiskit import QuantumCircuit, execute, Aer
#from aether import QuantumCircuit, simulate
import pygame
import numpy as np
simulator = Aer.get_backend('qasm_simulator')
shot=1
def Qand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qnand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.x(2)
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qor(First_bool,Second_bool):
return Qnand(Qnand(First_bool,First_bool),Qnand(Second_bool,Second_bool))
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
b=''#string holder
for i in range(nbits):
job=execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1] #find the measured state, this is a list
b=b+state[0] #state[0] is a string
return int(b, 2)
dis = pew.init()
screen = pew.Pix()
#Selecting game speed
init_speed =3
game_speed = init_speed
#circuit graphics
pygame.font.init()
#add backgorund
pygame.draw.rect(dis,(255,255,255),(0,320,320,100))
#gate backkgorund
#add gate, change from H to Z to Meas by key stroke
font1 = pygame.font.Font(None, 70)
text = font1.render('H', True, (255, 0, 0))
dis.blit(text, (10, 330))
g=0
#add gate, change from H to Z to Meas by key stroke
gates = np.zeros(3, dtype=str)
gates[0] = 'H'
gates[1] = 'Z'
gates[2] = 'M'
corr = [0, 1, 0, 2] #correct sequence of gates
images = {}
for i in range(4):
imag_ = pygame.image.load(str(i+1) + 'c.png')
x_size = int((i+1)*65)
images[i] = imag_#pygame.transform.scale(imag_,(x_size,85))
g=0 #tracks selected gate
currg=0 #tracks current position in circuit
success=False #tracks whether or not circuit is successfully constructed
ima3 = pygame.image.load('1c.png')
#ima3 = pygame.transform.scale(ima3,(65,50))
dis.blit(ima3, (45, 325))
#Selecting initial position of the snake
snake = [(3,3)]
#Selecting initial velocity of the snake
dx, dy = 1, 0
#Selecting initial position of the apple
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 1)
#Selecting the initial position of the first noise
nx=3
ny=4
noise=[(nx, ny)]
while True:
screen.pixel(noise[0][0], noise[0][1],2)
#Here we print the head of the snake
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3)
pew.show(screen)
pew.tick(1 / game_speed)
#Here we change the velocity of the snake depending on the key input
keys = pew.keys()
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
#Gate switch
if keys & pew.K_O:
pygame.draw.rect(dis,(255,255,255),(0,320,50,50))
g = (g+1) % 3 #cycle between gates
font1 = pygame.font.Font(None, 70)
text = font1.render(gates[g], True, (255, 0, 0))
dis.blit(text, (10, 330))
#Now are going to update the position of the head of the snake
#We define the next position of the head depending on the velocity
x = (x + dx) %8
y = (y + dy) %8
#Now we define a loop to end the loop (and the game) if the next position
# of the head is in the snake or it goes out of the grid
if Qor((x, y) in snake, (x,y) in noise):
#Here we turn of all the pixles from the snake and the apple
for (i,j) in snake:
screen.pixel(i,j,0)
screen.pixel(apple_x,apple_y,0)
for (i,j) in noise:
screen.pixel(i,j,0)
break
#If none of those thing happens the head of the snake gets updated to the new position
snake.append((x, y))
#Now we create a conditional loop for changing the size and spawning new apples depending
# on if the snake eats the apple or not
if Qand(x == apple_x, y == apple_y):
if g != corr[currg]:
break
else:
if currg == len(corr)-1: #if the required sequence is accomplished
success=True
break
dis.blit(images[currg+1], (45, 325))
currg+=1
#If the snake eats the apple we turn of the pixel of the apple
screen.pixel(apple_x, apple_y, 0)
#Now we define the coordinates of the apple to lie inside the snake for the loop
apple_x, apple_y = snake[0]
#We create a loop to generate an apple ouside the snake
while (apple_x, apple_y) in snake or (apple_x, apple_y) in noise:
apple_x=qrand(3)
apple_y=qrand(3)
#We light the pixels of the new apple
screen.pixel(apple_x, apple_y, 1)
# k=k+1
nx=snake[0][0]
ny=snake[0][1]
while Qor(Qor(Qor((nx,ny) in snake, (Qand(nx==apple_x, ny==apple_y))) ,(nx,ny) in noise) , (nx,ny)==(x,y)):
nx=qrand(3) #as opposed to random.getrandbits(3)
ny=qrand(3)
noise.append((nx,ny))
screen.pixel(nx, ny,2)
#We increase the speed of the game
game_speed += 0.2
#If the snake eats the apple we don't delete the last pixel of the snake. Otherwise we remove
# the last pixel to not increase the size of the snake
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
def blit_screen(screen,text):
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
#When the loop is finished we print the game over screen
#turn off all pixels
if success == True:
text = pew.Pix.from_text("You win!")
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
else:
text = pew.Pix.from_text("Game over!")
blit_screen(screen,text)
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import numpy as np
from qiskit import *
q = QuantumRegister(1)
# Create a Quantum Circuit acting on a quantum register of n qubits
qc = QuantumCircuit(q)
qc.draw(filename="0.png")
qc.h(0)
qc.draw()
qc.z(0)
qc.draw()
qc.h(0)
qc.draw()
qc.measure(0,0)
qc.draw()
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,0,1], title='Intial state')
plot_bloch_vector([1,0,0], title='H gate')
plot_bloch_vector([-1,0,0], title='Z gate')
plot_bloch_vector([0,0,-1], title='H gate')
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import numpy as np
from qiskit import *
q = QuantumRegister(1)
# Create a Quantum Circuit acting on a quantum register of n qubits
qc = QuantumCircuit(q)
diag = qc.draw(output="mpl")
diag.savefig("1.png", format="png")
qc.h(0)
diag = qc.draw(output="mpl")
diag.savefig("2.png", format="png")
qc.z(0)
diag = qc.draw(output="mpl")
diag.savefig("3.png", format="png")
qc.h(0)
diag = qc.draw(output="mpl")
diag.savefig("4.png", format="png")
#Cropping images
!pip3 install Pillow
crp = [0,7,17,25]
from PIL import Image
for i in range(1,5):
image = Image.open(str(i)+".png")
w,h = image.size
image.crop((20+crp[i-1],20,w,h-20)).save(str(i)+"c.png")
qc.measure(0,0)
qc.draw()
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,0,1], title='Intial state')
plot_bloch_vector([1,0,0], title='H gate')
plot_bloch_vector([-1,0,0], title='Z gate')
plot_bloch_vector([0,0,-1], title='H gate')
|
https://github.com/GlazeDonuts/QSVM
|
GlazeDonuts
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import Aer
from qiskit.ml.datasets import ad_hoc_data, sample_ad_hoc_data, breast_cancer
from qiskit.circuit.library import ZZFeatureMap
from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QSVM
feature_dim = 2 # Number of input features
sample_total, train_data, test_data, labels = ad_hoc_data(training_size=20, test_size=10,
n=feature_dim, gap=0.3, plot_data=True)
sample_test_data = sample_ad_hoc_data(sample_total, 10, n=feature_dim)
data_pts, class2label = split_dataset_to_data_and_labels(sample_test_data)
print("Classes and corresponding labels are:")
for c in class2label:
print(f"Class: {c}, Label: {class2label[c]}")
seed = 10598 # Setting seed to ensure reproducable results
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')
qsvm = QSVM(feature_map, train_data, test_data, data_pts[0])
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
result = qsvm.run(quantum_instance)
print(f"Testing Accuracy: {result['testing_accuracy'] * 100}%")
print("Prediction on Datapoints:")
print(f"Ground Truth: {map_label_to_class_name(data_pts[1], qsvm.label_to_class)}")
print(f"Predictions: {result['predicted_classes']}")
print("Trained Kernel Matrix:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
feature_dim = 2 # Number of input features
sample_total_bc, train_data_bc, test_data_bc, labels_bc = breast_cancer(training_size=20, test_size=10,
n=feature_dim, plot_data=True)
seed = 10598 # Setting seed to ensure reproducable results
feature_map_bc = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')
qsvm_bc = QSVM(feature_map_bc, train_data_bc, test_data_bc)
backend = Aer.get_backend('qasm_simulator')
quantum_instance_bc = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
result_bc = qsvm_bc.run(quantum_instance_bc)
print(f"Testing Accuracy: {result_bc['testing_accuracy'] * 100}%")
print("Trained Kernel Matrix:")
kernel_matrix_bc = result_bc['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix_bc),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/petr-ivashkov/qiskit-cert-workbook
|
petr-ivashkov
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
#ignore deprecation warnings because they are annoying (not recommened generally)
from warnings import simplefilter
simplefilter(action='ignore', category=DeprecationWarning)
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import *
from ibm_quantum_widgets import *
NUM_QUBITS = 2
# let's construct a multi-qubit quantum register
qr = QuantumRegister(NUM_QUBITS, 'q')
qc = QuantumCircuit(qr, name='my-circuit')
# let's create a Bell's state
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()
# let's construct a multi-bit classical register
cr = ClassicalRegister(NUM_QUBITS, 'c')
qc = QuantumCircuit(qr, cr, name='my-circuit')
# explicitly measure qubits [0,1] into classical bits [0,1]
qc.measure(qr, cr)
# alternatively: qc.measure([0,1], [0,1])
qc.draw()
# Bell state 0
bell_0 = QuantumCircuit(2)
bell_0.h(0)
bell_0.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell1 = sv.evolve(bell_0)
sv_bell1.draw('latex')
# Bell state 1
bell_1 = QuantumCircuit(2)
bell_1.x(0)
bell_1.h(0)
bell_1.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell2 = sv.evolve(bell_1)
sv_bell2.draw('latex')
# Bell state 2
bell_2 = QuantumCircuit(2)
bell_2.x(0)
bell_2.h(1)
bell_2.cx(1,0)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_2)
sv_bell3.draw('latex')
# create the last remaining Bell state on your own
bell_3 = QuantumCircuit(2)
### ADD CODE BELOW
### DON'T ADD CODE BELOW
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_3)
sv_bell3.draw('latex')
# state of equal superposition of basis states
max_sp = QuantumCircuit(2)
max_sp.h(0)
max_sp.h(1)
sv = Statevector.from_label('00')
# evolve the initial state through the circuit
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
# try it out yourself with different gates: instead of Hadamard, try Pauili gates
my_qc = QuantumCircuit(1)
### ADD CODE BELOW
### DON'T ADD CODE BELOW
transpile(my_qc, backend=backend).draw('mpl')
# did you get what you expected?
qc = QuantumCircuit(1)
qc.x(0)
qc.depth()
qc = QuantumCircuit(2)
qc.x([0,1])
qc.x(1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qc = QuantumCircuit(2)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.cx(0,1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
# hint: the longest path is not always the lenth of the longest sequence along one channel
qc.draw('mpl')
# the second qubit only has a CX gate applied to it, but has to "wait" for the first qubit to provide the control
# also, barier doesn't count
# in the following we will use the implementation of Grover's algorithm in Qiskit
from qiskit.algorithms import Grover, AmplificationProblem
# let's construct an oracle with a single solution
sv = Statevector.from_label('010')
problem = AmplificationProblem(oracle=sv)
grover = Grover(iterations=2).construct_circuit(problem=problem)
# the original circuit contains unitaries
# transpile the circuit in terms of basis gates to see what it is "made of"
t_grover = transpile(grover, basis_gates=['cx', 'u3'])
t_grover.draw('mpl', fold=-1)
# draw the original cicuit yourself
grover.draw('mpl', fold=-1)
# lets's try to evolve the initial state through the circuit like we have done for Bell states
sv = Statevector.from_label('000')
sv_ev = sv.evolve(grover)
sv_ev.draw('latex')
# it is obvious from statevector evolutions, that the state 010
# has the best chances to be measured, as desired
# now let's obtain the same result from the QASM simulation
# for that we need to measure the qubits in the end of our circuit
grover.measure_all()
backend= BasicAer.get_backend('qasm_simulator')
job = execute(grover, backend, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# finally let's see how our circuit performs on actual hardware
# you will need your IBM Quantum account
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
# sometimes you might need to wait when running on real devices
# let's monitor the status of our job
from qiskit.tools import job_monitor
# to call a real backend let's pick the least busy one, which satisfies out requirments
from qiskit.providers.ibmq import least_busy
suitable_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 3
and not b.configuration().simulator
and b.status().operational==True)
backend = least_busy(backends=suitable_devices)
print("We are runnig our circuit on ", backend)
job = execute(grover, backend=backend)
job_monitor(job)
# we see that results from a real device also match our expectations
# the algorithm successfully finds the marked string
result = job.result()
counts = result.get_counts()
# plot the histogramm yourself
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# let's again use our transpiled Grover circuit to demonstarte the idea
# Notice: QASM doesn't look "nice". This is a low-level language which can be understood by quantum hardware.
# If you want to take a look at the QASM code make sure to specify 'formatted=True' which makes the code readable by a human being.
t_grover.qasm(formatted=True)
# store the circuit to a file in the follwing way
qasm_code = t_grover.qasm(filename='grover.qasm')
# to get the circuit back from QASM file execute the following
my_qc = QuantumCircuit.from_qasm_file('grover.qasm')
my_qc.draw('mpl', fold=-1)
# let's create an arbitrary Operator from a matrix
A = np.array([[0,1,0], [1,0,0], [0,1,1]])
op = Operator(A)
# Operator contains information about its matrix representation and input and output dimensions
op
# create an Operator from a circuit yourself
qc = QuantumCircuit(2)
qc.h([0,1])
qc.cx(0,1)
op = Operator(qc)
op
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.expand(B) # B x A
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.tensor(B) # result A x B
III = Operator(np.eye(2 ** 3))
XX = Operator(Pauli(label='XX'))
XIX = III.compose(XX, qargs=[0,2])
XIX # the resulting operator is X x I x X
# compose an XIXZ Operator from IIII and XX and Z Operators
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# with Qiskit you can find the state fidelity between two quantum states
# let's investigate Bell states
state_fidelity(sv_bell3, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell3)
# let's find process fidelity of X and H Operators
op_1 = Operator([[0,1],[0,1]])
op_2 = Operator([[1,1],[1,-1]])/np.sqrt(2)
F = process_fidelity(op_1, op_2)
F
# what about fidelity of X Operator with itself multiplied with a complex phase
op_1 = Operator([[0,1],[0,1]])
op_2 = op_1*np.exp(0.5j)
# calculate the process fidelity yourself
### ADD CODE BELOW
### DON'T ADD CODE BELOW
# as you expected, the fidelity is independent of global phase
# encountered a compatibility error? Check which version of Qiskit you are using
import qiskit
qiskit.__qiskit_version__
# display the entire version table
%qiskit_version_table
# Let's have an overview information on all the IBMQ backends that are available
%qiskit_backend_overview
# now let's pick one device and investigate it
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_bogota')
plot_gate_map(backend, plot_directed=True)
plot_error_map(backend)
# let's plot the layout of our Bell state circuit transpiled for our target backend
transpiled_bell = transpile(bell_0, backend=backend)
plot_circuit_layout(transpiled_bell, backend=backend)
# display the layout of transpiled Grover's circuit on our target backend
transpiled_grover = transpile(grover, backend=backend)
plot_circuit_layout(transpiled_grover, backend=backend)
# what if we want to specify a custom mapping of our circuit qubits to device qubits?
# let's create an initial layout
initial_layout = [2,3,4] # virtual to physical: virtual qubits are ordered
transpiled_qc = transpile(grover, backend=backend, initial_layout=initial_layout)
plot_circuit_layout(transpiled_qc, backend=backend)
# for example, let's draw our Bell's state circuit in text mode
bell_0.draw('text')
# qubits in reversed order
bell_0.draw('mpl', reverse_bits=True)
# More customization
style = {'linecolor': 'red', 'backgroundcolor': 'grey'}
bell_0.draw('mpl',scale = 1.2, style=style, fold=-1)
plot_bloch_vector([0,1,0])
plot_state_city(bell_0)
# to understand why the 'city' looks like this consider the density matrix of this state
plot_state_hinton(bell_0)
plot_state_qsphere(bell_0)
plot_state_paulivec(bell_0)
plot_bloch_multivector(bell_0)
# here, the bloch spheres represent maximally entangled qubits as zero-length vectors. Hence, no arrows.
# a more informative example
psi = Statevector.from_label('+1')
plot_bloch_multivector(psi)
# the first qubit is in state |1>
# the second qubit is in the superposition of |0> and |1>
rho = DensityMatrix.from_instruction(bell_0)
rho.draw('latex', prefix='\\rho_{Bell_0} = ')
plot_state_city(rho.data, title='Density Matrix')
# prepare a density matrix for the state of the equal superposition of 2 basis states
my_qc = QuantumCircuit(2)
my_qc.h([0,1])
my_rho = DensityMatrix.from_instruction(my_qc)
my_rho.draw('latex', prefix='\\rho_{equal} = ')
# prepare a density matrix for a mixed one-qubit state in an equal mixture of |0> and |1>
### ADD CODE BELOW
### DON'T ADD CODE BELOW
qr = QuantumRegister(3, name='q')
qc = QuantumCircuit(qr)
qc.ccx(control_qubit1=qr[1], control_qubit2=qr[2], target_qubit=qr[0])
qc.draw('mpl')
# Toffoli gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
array_to_latex(matrix, prefix="CCX = ")
qr = QuantumRegister(2, name='q')
qc = QuantumCircuit(qr)
qc.swap(qubit1=qr[0], qubit2=[1])
qc.draw('mpl')
# SWAP gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
# display the matrix in latex
array_to_latex(matrix, prefix="SWAP = ")
|
https://github.com/petr-ivashkov/qiskit-cert-workbook
|
petr-ivashkov
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
#ignore deprecation warnings because they are annoying (not recommened generally)
from warnings import simplefilter
simplefilter(action='ignore', category=DeprecationWarning)
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import *
from ibm_quantum_widgets import *
NUM_QUBITS = 2
# let's construct a multi-qubit quantum register
qr = QuantumRegister(NUM_QUBITS, 'q')
qc = QuantumCircuit(qr, name='my-circuit')
# let's create a Bell's state
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()
# let's construct a multi-bit classical register
cr = ClassicalRegister(NUM_QUBITS, 'c')
qc = QuantumCircuit(qr, cr, name='my-circuit')
# explicitly measure qubits [0,1] into classical bits [0,1]
qc.measure(qr, cr)
# alternatively: qc.measure([0,1], [0,1])
qc.draw()
# Bell state 0
bell_0 = QuantumCircuit(2)
bell_0.h(0)
bell_0.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell1 = sv.evolve(bell_0)
sv_bell1.draw('latex')
# Bell state 1
bell_1 = QuantumCircuit(2)
bell_1.x(0)
bell_1.h(0)
bell_1.cx(0,1)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell2 = sv.evolve(bell_1)
sv_bell2.draw('latex')
# Bell state 2
bell_2 = QuantumCircuit(2)
bell_2.x(0)
bell_2.h(1)
bell_2.cx(1,0)
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_2)
sv_bell3.draw('latex')
# create the last remaining Bell state on your own
bell_3 = QuantumCircuit(2)
### ADD CODE BELOW
bell_3.x(0)
bell_3.x(1)
bell_3.h(1)
bell_3.cx(1,0)
### DON'T ADD CODE BELOW
sv = Statevector.from_label('00')
#evolve the initial state through the circuit
sv_bell3 = sv.evolve(bell_3)
sv_bell3.draw('latex')
# state of equal superposition of basis states
max_sp = QuantumCircuit(2)
max_sp.h(0)
max_sp.h(1)
sv = Statevector.from_label('00')
# evolve the initial state through the circuit
### ADD CODE BELOW
sv_ev = sv.evolve(max_sp)
sv_ev.draw('latex')
### DON'T ADD CODE BELOW
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(1)
qc.h(0)
qc.barrier()
qc.h(0)
transpile(qc, backend=backend).draw('mpl')
# try it out yourself with different gates: instead of Hadamard, try Pauili gates
my_qc = QuantumCircuit(1)
### ADD CODE BELOW
my_qc.x(0)
my_qc.barrier()
my_qc.x(0)
### DON'T ADD CODE BELOW
transpile(my_qc, backend=backend).draw('mpl')
# did you get what you expected?
qc = QuantumCircuit(1)
qc.x(0)
qc.depth()
qc = QuantumCircuit(2)
qc.x([0,1])
qc.x(1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
### ADD CODE BELOW
qc.draw()
### DON'T ADD CODE BELOW
qc = QuantumCircuit(2)
qc.x(0)
qc.barrier(0)
qc.h(0)
qc.cx(0,1)
qc.depth()
# draw the circuit yourself to see why the depth has increased now
# hint: the longest path is not always the lenth of the longest sequence along one channel
qc.draw('mpl')
# the second qubit only has a CX gate applied to it, but has to "wait" for the first qubit to provide the control
# also, barier doesn't count
# in the following we will use the implementation of Grover's algorithm in Qiskit
from qiskit.algorithms import Grover, AmplificationProblem
# let's construct an oracle with a single solution
sv = Statevector.from_label('010')
problem = AmplificationProblem(oracle=sv)
grover = Grover(iterations=2).construct_circuit(problem=problem)
# the original circuit contains unitaries
# transpile the circuit in terms of basis gates to see what it is "made of"
t_grover = transpile(grover, basis_gates=['cx', 'u3'])
t_grover.draw('mpl', fold=-1)
# draw the original cicuit yourself
grover.draw('mpl', fold=-1)
# lets's try to evolve the initial state through the circuit like we have done for Bell states
sv = Statevector.from_label('000')
sv_ev = sv.evolve(grover)
sv_ev.draw('latex')
# it is obvious from statevector evolutions, that the state 010
# has the best chances to be measured, as desired
# now let's obtain the same result from the QASM simulation
# for that we need to measure the qubits in the end of our circuit
grover.measure_all()
backend= BasicAer.get_backend('qasm_simulator')
job = execute(grover, backend, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# finally let's see how our circuit performs on actual hardware
# you will need your IBM Quantum account
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
# sometimes you might need to wait when running on real devices
# let's monitor the status of our job
from qiskit.tools import job_monitor
# to call a real backend let's pick the least busy one, which satisfies out requirments
from qiskit.providers.ibmq import least_busy
suitable_devices = provider.backends(filters = lambda b: b.configuration().n_qubits >= 3
and not b.configuration().simulator
and b.status().operational==True)
backend = least_busy(backends=suitable_devices)
print("We are runnig our circuit on ", backend)
#job = execute(grover, backend=backend)
#job_monitor(job)
# we see that results from a real device also match our expectations
# the algorithm successfully finds the marked string
result = job.result()
counts = result.get_counts()
### ADD CODE BELOW
# plot the histogramm yourself
plot_histogram(counts)
### DON'T ADD CODE BELOW
# let's again use our transpiled Grover circuit to demonstarte the idea
# Notice: QASM doesn't look "nice". This is a low-level language which can be understood by quantum hardware.
# If you want to take a look at the QASM code make sure to specify 'formatted=True' which makes the code readable by a human being.
t_grover.qasm(formatted=True)
# store the circuit to a file in the follwing way
qasm_code = t_grover.qasm(filename='grover.qasm')
# to get the circuit back from QASM file execute the following
my_qc = QuantumCircuit.from_qasm_file('grover.qasm')
my_qc.draw('mpl', fold=-1)
# let's create an arbitrary Operator from a matrix
A = np.array([[0,1,0], [1,0,0], [0,1,1]])
op = Operator(A)
# Operator contains information about its matrix representation and input and output dimensions
op
# create an Operator from a circuit yourself
qc = QuantumCircuit(2)
qc.h([0,1])
qc.cx(0,1)
op = Operator(qc)
op
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.expand(B) # B x A
A = Operator(Pauli(label='X'))
B = Operator(Pauli(label='Z'))
A.tensor(B) # result A x B
III = Operator(np.eye(2 ** 3))
XX = Operator(Pauli(label='XX'))
XIX = III.compose(XX, qargs=[0,2])
XIX # the resulting operator is X x I x X
# compose an XIXZ Operator from IIII and XX and Z Operators
### ADD CODE BELOW
IIII = Operator(np.eye(2 ** 4))
XX = Operator(Pauli(label='XX'))
Z = Operator(Pauli('Z'))
XIXI = IIII.compose(XX, qargs=[1,3])
XIXZ = XIXI.compose(Z, qargs=[0])
### DON'T ADD CODE BELOW
print(XIXZ)
# with Qiskit you can find the state fidelity between two quantum states
# let's investigate Bell states
state_fidelity(sv_bell3, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell1)
basis_state_00 = Statevector.from_label('00')
state_fidelity(basis_state_00, sv_bell3)
# let's find process fidelity of X and H Operators
op_1 = Operator([[0,1],[0,1]])
op_2 = Operator([[1,1],[1,-1]])/np.sqrt(2)
F = process_fidelity(op_1, op_2)
F
# what about fidelity of X Operator with itself multiplied with a complex phase
op_1 = Operator([[0,1],[0,1]])
op_2 = op_1*np.exp(0.5j)
# calculate the process fidelity yourself
### ADD CODE BELOW
F = process_fidelity(op_1, op_2)
F
### DON'T ADD CODE BELOW
# as you expected, the fidelity is independent of global phase
# encountered a compatibility error? Check which version of Qiskit you are using
import qiskit
qiskit.__qiskit_version__
# display the entire version table
%qiskit_version_table
# Let's have an overview information on all the IBMQ backends that are available
%qiskit_backend_overview
# now let's pick one device and investigate it
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_bogota')
plot_gate_map(backend, plot_directed=True)
plot_error_map(backend)
# let's plot the layout of our Bell state circuit transpiled for our target backend
transpiled_bell = transpile(bell_0, backend=backend)
plot_circuit_layout(transpiled_bell, backend=backend)
# display the layout of transpiled Grover's circuit on our target backend
transpiled_grover = transpile(grover, backend=backend)
plot_circuit_layout(transpiled_grover, backend=backend)
# what if we want to specify a custom mapping of our circuit qubits to device qubits?
# let's create an initial layout
initial_layout = [2,3,4] # virtual to physical: virtual qubits are ordered
transpiled_qc = transpile(grover, backend=backend, initial_layout=initial_layout)
plot_circuit_layout(transpiled_qc, backend=backend)
# for example, let's draw our Bell's state circuit in text mode
bell_0.draw('text')
# qubits in reversed order
bell_0.draw('mpl', reverse_bits=True)
# More customization
style = {'linecolor': 'red', 'backgroundcolor': 'grey'}
bell_0.draw('mpl',scale = 1.2, style=style, fold=-1)
plot_bloch_vector([0,1,0])
plot_state_city(bell_0)
# to understand why the 'city' looks like this consider the density matrix of this state
plot_state_hinton(bell_0)
plot_state_qsphere(bell_0)
plot_state_paulivec(bell_0)
plot_bloch_multivector(bell_0)
# here, the bloch spheres represent maximally entangled qubits as zero-length vectors. Hence, no arrows.
# a more informative example
psi = Statevector.from_label('+1')
plot_bloch_multivector(psi)
# the first qubit is in state |1>
# the second qubit is in the superposition of |0> and |1>
rho = DensityMatrix.from_instruction(bell_0)
rho.draw('latex', prefix='\\rho_{Bell_0} = ')
plot_state_city(rho.data, title='Density Matrix')
# prepare a density matrix for the state of the equal superposition of 2 basis states
my_qc = QuantumCircuit(2)
my_qc.h([0,1])
my_rho = DensityMatrix.from_instruction(my_qc)
my_rho.draw('latex', prefix='\\rho_{equal} = ')
# prepare a density matrix for a mixed one-qubit state in an equal mixture of |0> and |1>
### ADD CODE BELOW
my_rho_M = np.array([[0.5, 0], [0, 0.5]])
my_rho = DensityMatrix(my_rho_M)
my_rho.draw('latex', prefix='\\rho_{mixture} = ')
### DON'T ADD CODE BELOW
qr = QuantumRegister(3, name='q')
qc = QuantumCircuit(qr)
qc.ccx(control_qubit1=qr[1], control_qubit2=qr[2], target_qubit=qr[0])
qc.draw('mpl')
# Toffoli gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
array_to_latex(matrix, prefix="CCX = ")
qr = QuantumRegister(2, name='q')
qc = QuantumCircuit(qr)
qc.swap(qubit1=qr[0], qubit2=[1])
qc.draw('mpl')
# SWAP gate has the following matrix representation for the above configuration
matrix = Operator(qc).data
# display the matrix in latex
array_to_latex(matrix, prefix="SWAP = ")
|
https://github.com/qclib/qclib
|
qclib
|
# 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-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
# pylint: disable=unused-argument
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.compiler import transpile
from qiskit.quantum_info.random import random_unitary
class IsometryTranspileBench:
params = ([0, 1, 2, 3], [3, 4, 5, 6])
param_names = ["number of input qubits", "number of output qubits"]
def setup(self, m, n):
q = QuantumRegister(n)
qc = QuantumCircuit(q)
if not hasattr(qc, "iso"):
raise NotImplementedError
iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m]
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
qc.iso(iso, q[:m], q[m:])
self.circuit = qc
def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused):
coupling = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
self.circuit,
basis_gates=["u1", "u3", "u2", "cx"],
coupling_map=coupling,
seed_transpiler=0,
)
counts = circuit.count_ops()
cnot_count = counts.get("cx", 0)
return cnot_count
|
https://github.com/qclib/qclib
|
qclib
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Arbitrary unitary circuit instruction.
"""
import numpy
from qiskit.circuit import Gate, ControlledGate
from qiskit.circuit import QuantumCircuit
from qiskit.circuit import QuantumRegister, Qubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit._utils import _compute_control_matrix
from qiskit.circuit.library.standard_gates import UGate
from qiskit.extensions.quantum_initializer import isometry
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info.operators.predicates import is_unitary_matrix
from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer
from qiskit.quantum_info.synthesis.two_qubit_decompose import two_qubit_cnot_decompose
from qiskit.extensions.exceptions import ExtensionError
_DECOMPOSER1Q = OneQubitEulerDecomposer("U")
class UnitaryGate(Gate):
"""Class quantum gates specified by a unitary matrix.
Example:
We can create a unitary gate from a unitary matrix then add it to a
quantum circuit. The matrix can also be directly applied to the quantum
circuit, see :meth:`.QuantumCircuit.unitary`.
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.extensions import UnitaryGate
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
gate = UnitaryGate(matrix)
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1])
"""
def __init__(self, data, label=None):
"""Create a gate from a numeric unitary matrix.
Args:
data (matrix or Operator): unitary operator.
label (str): unitary name for backend [Default: None].
Raises:
ExtensionError: if input data is not an N-qubit unitary operator.
"""
if hasattr(data, "to_matrix"):
# If input is Gate subclass or some other class object that has
# a to_matrix method this will call that method.
data = data.to_matrix()
elif hasattr(data, "to_operator"):
# If input is a BaseOperator subclass this attempts to convert
# the object to an Operator so that we can extract the underlying
# numpy matrix from `Operator.data`.
data = data.to_operator().data
# Convert to numpy array in case not already an array
data = numpy.array(data, dtype=complex)
# Check input is unitary
if not is_unitary_matrix(data):
raise ExtensionError("Input matrix is not unitary.")
# Check input is N-qubit matrix
input_dim, output_dim = data.shape
num_qubits = int(numpy.log2(input_dim))
if input_dim != output_dim or 2**num_qubits != input_dim:
raise ExtensionError("Input matrix is not an N-qubit operator.")
# Store instruction params
super().__init__("unitary", num_qubits, [data], label=label)
def __eq__(self, other):
if not isinstance(other, UnitaryGate):
return False
if self.label != other.label:
return False
# Should we match unitaries as equal if they are equal
# up to global phase?
return matrix_equal(self.params[0], other.params[0], ignore_phase=True)
def __array__(self, dtype=None):
"""Return matrix for the unitary."""
# pylint: disable=unused-argument
return self.params[0]
def inverse(self):
"""Return the adjoint of the unitary."""
return self.adjoint()
def conjugate(self):
"""Return the conjugate of the unitary."""
return UnitaryGate(numpy.conj(self.to_matrix()))
def adjoint(self):
"""Return the adjoint of the unitary."""
return self.transpose().conjugate()
def transpose(self):
"""Return the transpose of the unitary."""
return UnitaryGate(numpy.transpose(self.to_matrix()))
def _define(self):
"""Calculate a subcircuit that implements this unitary."""
if self.num_qubits == 1:
q = QuantumRegister(1, "q")
qc = QuantumCircuit(q, name=self.name)
theta, phi, lam, global_phase = _DECOMPOSER1Q.angles_and_phase(self.to_matrix())
qc._append(UGate(theta, phi, lam), [q[0]], [])
qc.global_phase = global_phase
self.definition = qc
elif self.num_qubits == 2:
self.definition = two_qubit_cnot_decompose(self.to_matrix())
else:
from qiskit.quantum_info.synthesis.qsd import ( # pylint: disable=cyclic-import
qs_decomposition,
)
self.definition = qs_decomposition(self.to_matrix())
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):
"""Return controlled version of gate
Args:
num_ctrl_qubits (int): number of controls to add to gate (default=1)
label (str): optional gate label
ctrl_state (int or str or None): The control state in decimal or as a
bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1.
Returns:
UnitaryGate: controlled version of gate.
Raises:
QiskitError: Invalid ctrl_state.
ExtensionError: Non-unitary controlled unitary.
"""
mat = self.to_matrix()
cmat = _compute_control_matrix(mat, num_ctrl_qubits, ctrl_state=None)
iso = isometry.Isometry(cmat, 0, 0)
return ControlledGate(
"c-unitary",
num_qubits=self.num_qubits + num_ctrl_qubits,
params=[mat],
label=label,
num_ctrl_qubits=num_ctrl_qubits,
definition=iso.definition,
ctrl_state=ctrl_state,
base_gate=self.copy(),
)
def _qasm2_decomposition(self):
"""Return an unparameterized version of ourselves, so the OQ2 exporter doesn't choke on the
non-standard things in our `params` field."""
out = self.definition.to_gate()
out.name = self.name
return out
def validate_parameter(self, parameter):
"""Unitary gate parameter has to be an ndarray."""
if isinstance(parameter, numpy.ndarray):
return parameter
else:
raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}")
def unitary(self, obj, qubits, label=None):
"""Apply unitary gate specified by ``obj`` to ``qubits``.
Args:
obj (matrix or Operator): unitary operator.
qubits (Union[int, Tuple[int]]): The circuit qubits to apply the
transformation to.
label (str): unitary name for backend [Default: None].
Returns:
QuantumCircuit: The quantum circuit.
Raises:
ExtensionError: if input data is not an N-qubit unitary operator.
Example:
Apply a gate specified by a unitary matrix to a quantum circuit
.. code-block:: python
from qiskit import QuantumCircuit
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
circuit = QuantumCircuit(2)
circuit.unitary(matrix, [0, 1])
"""
gate = UnitaryGate(obj, label=label)
if isinstance(qubits, QuantumRegister):
qubits = qubits[:]
# for single qubit unitary gate, allow an 'int' or a 'list of ints' as qubits.
if gate.num_qubits == 1:
if isinstance(qubits, (int, Qubit)) or len(qubits) > 1:
qubits = [qubits]
return self.append(gate, qubits, [])
QuantumCircuit.unitary = unitary
|
https://github.com/qclib/qclib
|
qclib
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Linear-depth Multicontrolled Special Unitary
"""
from typing import Union, List
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RZGate, RYGate
from qiskit.circuit.library import UnitaryGate
from qiskit.synthesis import OneQubitEulerDecomposer
from qiskit.circuit import Gate, Qubit
from qclib.gates.mcx import LinearMcx, McxVchainDirty
from qclib.gates.util import check_su2, apply_ctrl_state, isclose
# pylint: disable=protected-access
class Ldmcsu(Gate):
"""
Linear depth Multi-Controlled Gate for Special Unitary
------------------------------------------------
Multicontrolled gate decomposition with linear cost.
`unitary` must be a SU(2) matrix.
"""
def __init__(self, unitary, num_controls, ctrl_state: str = None):
check_su2(unitary)
self.unitary = unitary
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(1)
self.num_controls = num_controls + 1
self.ctrl_state = ctrl_state
super().__init__("ldmcsu", self.num_controls, [], "ldmcsu")
def _define(self):
self.definition = QuantumCircuit(self.controls, self.target)
is_main_diag_real = isclose(self.unitary[0, 0].imag, 0.0) and isclose(
self.unitary[1, 1].imag, 0.0
)
is_secondary_diag_real = isclose(self.unitary[0, 1].imag, 0.0) and isclose(
self.unitary[1, 0].imag, 0.0
)
if not is_main_diag_real and not is_secondary_diag_real:
# U = V D V^-1, where the entries of the diagonal D are the eigenvalues
# `eig_vals` of U and the column vectors of V are the eigenvectors
# `eig_vecs` of U. These columns are orthonormal and the main diagonal
# of V is real-valued.
eig_vals, eig_vecs = np.linalg.eig(self.unitary)
x_vecs, z_vecs = self._get_x_z(eig_vecs)
self.half_linear_depth_mcv(
x_vecs,
z_vecs,
self.controls,
self.target,
self.ctrl_state,
inverse=True,
)
self.linear_depth_mcv(
np.diag(eig_vals),
self.controls,
self.target,
self.ctrl_state,
general_su2_optimization=True,
)
self.half_linear_depth_mcv(
x_vecs, z_vecs, self.controls, self.target, self.ctrl_state
)
else:
if not is_secondary_diag_real:
self.definition.h(self.target)
self.linear_depth_mcv(self.unitary, self.controls, self.target, self.ctrl_state)
if not is_secondary_diag_real:
self.definition.h(self.target)
@staticmethod
def _get_x_z(su2):
is_secondary_diag_real = isclose(su2[0, 1].imag, 0.0) and isclose(
su2[1, 0].imag, 0.0
)
if is_secondary_diag_real:
x_value = su2[0, 1]
z_value = su2[1, 1]
else:
x_value = -su2[0, 1].real
z_value = su2[1, 1] - su2[0, 1].imag * 1.0j
return x_value, z_value
@staticmethod
def _compute_gate_a(x_value, z_value):
if x_value == 0:
alpha = (z_value + 0j) ** (1 / 4)
beta = 0.0
else:
alpha_r = np.sqrt((np.sqrt((z_value.real + 1.0) / 2.0) + 1.0) / 2.0)
alpha_i = z_value.imag / (
2.0 * np.sqrt((z_value.real + 1.0) *
(np.sqrt((z_value.real + 1.0) / 2.0) + 1.0))
)
alpha = alpha_r + 1.0j * alpha_i
beta = x_value / (
2.0 * np.sqrt((z_value.real + 1.0) *
(np.sqrt((z_value.real + 1.0) / 2.0) + 1.0))
)
s_op = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]])
return s_op
def linear_depth_mcv(
self,
su2_unitary,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str = None,
general_su2_optimization=False,
):
"""
Theorem 1 - https://arxiv.org/pdf/2302.06377.pdf
"""
# S gate definition
x_value, z_value = self._get_x_z(su2_unitary)
op_a = Ldmcsu._compute_gate_a(x_value, z_value)
gate_a = UnitaryGate(op_a)
num_ctrl = len(controls)
k_1 = int(np.ceil(num_ctrl / 2.0))
k_2 = int(np.floor(num_ctrl / 2.0))
ctrl_state_k_1 = None
ctrl_state_k_2 = None
if ctrl_state is not None:
ctrl_state_k_1 = ctrl_state[::-1][:k_1][::-1]
ctrl_state_k_2 = ctrl_state[::-1][k_1:][::-1]
if not general_su2_optimization:
mcx_1 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition
self.definition.append(
mcx_1, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target]
)
self.definition.append(gate_a, [target])
mcx_2 = McxVchainDirty(
k_2, ctrl_state=ctrl_state_k_2, action_only=general_su2_optimization
).definition
self.definition.append(
mcx_2.inverse(), controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target]
)
self.definition.append(gate_a.inverse(), [target])
mcx_3 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition
self.definition.append(
mcx_3, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target]
)
self.definition.append(gate_a, [target])
mcx_4 = McxVchainDirty(k_2, ctrl_state=ctrl_state_k_2).definition
self.definition.append(
mcx_4, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target]
)
self.definition.append(gate_a.inverse(), [target])
def half_linear_depth_mcv(
self,
x_value,
z_value,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str = None,
inverse: bool = False,
):
"""
Theorem 4 - https://arxiv.org/pdf/2302.06377.pdf
"""
alpha_r = np.sqrt((z_value.real + 1.0) / 2.0)
alpha_i = z_value.imag / np.sqrt(2 * (z_value.real + 1.0))
alpha = alpha_r + 1.0j * alpha_i
beta = x_value / np.sqrt(2 * (z_value.real + 1.0))
s_op = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]])
# S gate definition
s_gate = UnitaryGate(s_op)
# Hadamard equivalent definition
h_gate = UnitaryGate(np.array([[-1, 1], [1, 1]]) * 1 / np.sqrt(2))
num_ctrl = len(controls)
k_1 = int(np.ceil(num_ctrl / 2.0))
k_2 = int(np.floor(num_ctrl / 2.0))
ctrl_state_k_1 = None
ctrl_state_k_2 = None
if ctrl_state is not None:
ctrl_state_k_1 = ctrl_state[::-1][:k_1][::-1]
ctrl_state_k_2 = ctrl_state[::-1][k_1:][::-1]
if inverse:
self.definition.h(target)
self.definition.append(s_gate, [target])
mcx_2 = McxVchainDirty(
k_2, ctrl_state=ctrl_state_k_2, action_only=True
).definition
self.definition.append(
mcx_2, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target]
)
self.definition.append(s_gate.inverse(), [target])
self.definition.append(h_gate, [target])
else:
mcx_1 = McxVchainDirty(k_1, ctrl_state=ctrl_state_k_1).definition
self.definition.append(
mcx_1, controls[:k_1] + controls[k_1 : 2 * k_1 - 2] + [target]
)
self.definition.append(h_gate, [target])
self.definition.append(s_gate, [target])
mcx_2 = McxVchainDirty(k_2, ctrl_state=ctrl_state_k_2).definition
self.definition.append(
mcx_2, controls[k_1:] + controls[k_1 - k_2 + 2 : k_1] + [target]
)
self.definition.append(s_gate.inverse(), [target])
self.definition.h(target)
@staticmethod
def ldmcsu(
circuit,
unitary,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str = None,
):
"""
Apply multi-controlled SU(2)
https://arxiv.org/abs/2302.06377
"""
circuit.append(
Ldmcsu(unitary, len(controls), ctrl_state=ctrl_state), [*controls, target]
)
class LdMcSpecialUnitary(Gate):
"""
Linear-depth Multicontrolled Special Unitary
--------------------------------------------
Implements the gate decompostion of any gate in SU(2) with linear depth (Ld)
presented in Lemma 7.9 in Barenco et al., 1995 (arXiv:quant-ph/9503016)
with optimizations from Theorem 5 of Iten et al., 2016 (arXiv:1501.06911)
"""
def __init__(self, unitary, num_controls, ctrl_state=None):
if not check_su2(unitary):
raise ValueError("Operator must be in SU(2)")
self.unitary = np.array(unitary, dtype=complex)
if num_controls > 0:
self.control_qubits = QuantumRegister(num_controls)
else:
self.control_qubits = []
self.target_qubit = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
if self.ctrl_state is None:
self.ctrl_state = "1" * num_controls
super().__init__("ldmc_su2", self.num_qubits, [], "LdMcSu2")
@staticmethod
def get_abc_operators(beta, gamma, delta):
"""
Creates A,B and C matrices such that
ABC = I
"""
# A
a_rz = RZGate(beta).to_matrix()
a_ry = RYGate(gamma / 2).to_matrix()
a_matrix = a_rz.dot(a_ry)
# B
b_ry = RYGate(-gamma / 2).to_matrix()
b_rz = RZGate(-(delta + beta) / 2).to_matrix()
b_matrix = b_ry.dot(b_rz)
# C
c_matrix = RZGate((delta - beta) / 2).to_matrix()
a_gate = UnitaryGate(a_matrix, label="A")
b_gate = UnitaryGate(b_matrix, label="B")
c_gate = UnitaryGate(c_matrix, label="C")
return a_gate, b_gate, c_gate
def _define(self):
self.definition = QuantumCircuit(self.control_qubits, self.target_qubit)
if len(self.control_qubits) > 0:
self._apply_ctrl_state()
theta, phi, lamb, _ = OneQubitEulerDecomposer._params_zyz(self.unitary)
a_gate, b_gate, c_gate = LdMcSpecialUnitary.get_abc_operators(
phi, theta, lamb
)
self._apply_abc(a_gate, b_gate, c_gate)
self._apply_ctrl_state()
else:
self.unitary(self.unitary, self.target_qubit)
def _apply_abc(self, a_gate: UnitaryGate, b_gate: UnitaryGate, c_gate: UnitaryGate):
"""
Applies ABC matrices to the quantum circuit according to theorem 5
of Iten et al. 2016 (arXiv:1501.06911).
Parameters
----------
a_gate, b_gate and c_gate expceted to be special unitary gates
"""
if len(self.control_qubits) < 3:
self.definition.append(c_gate, [self.target_qubit])
self.definition.mcx(self.control_qubits, self.target_qubit)
self.definition.append(b_gate, [self.target_qubit])
self.definition.mcx(self.control_qubits, self.target_qubit)
self.definition.append(a_gate, [self.target_qubit])
else:
ancilla = self.control_qubits[-1]
action_only = True
if len(self.control_qubits) < 6:
action_only = False
# decompose A, B and C to use their optimized controlled versions
theta_a, phi_a, lam_a, _ = OneQubitEulerDecomposer._params_zyz(
a_gate.to_matrix()
)
theta_b, phi_b, lam_b, _ = OneQubitEulerDecomposer._params_zyz(
b_gate.to_matrix()
)
theta_c, phi_c, lam_c, _ = OneQubitEulerDecomposer._params_zyz(
c_gate.to_matrix()
)
a_a, b_a, c_a = LdMcSpecialUnitary.get_abc_operators(phi_a, theta_a, lam_a)
a_b, b_b, c_b = LdMcSpecialUnitary.get_abc_operators(phi_b, theta_b, lam_b)
a_c, b_c, c_c = LdMcSpecialUnitary.get_abc_operators(phi_c, theta_c, lam_c)
# definition of left mcx, which will also be inverted as the right mcx
mcx_gate = LinearMcx(
len(self.control_qubits[:-1]), action_only=action_only
).definition
# decomposed controlled C
self.definition.unitary(c_c, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(b_c, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(a_c, self.target_qubit)
self.definition.append(
mcx_gate, self.control_qubits[:-1] + [self.target_qubit] + [ancilla]
)
# decomposed controlled B
self.definition.unitary(c_b, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(b_b, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(a_b, self.target_qubit)
self.definition.append(
mcx_gate.inverse(),
self.control_qubits[:-1] + [self.target_qubit] + [ancilla],
)
# decomposed A
self.definition.unitary(c_a, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(b_a, self.target_qubit)
self.definition.cx(ancilla, self.target_qubit)
self.definition.unitary(a_a, self.target_qubit)
@staticmethod
def ldmcsu(circuit, unitary, controls, target, ctrl_state=None):
"""
Linear-depth Multicontrolled Special Unitary
--------------------------------------------
Implements the gate decompostion of any gate in SU(2) with linear depth (Ld)
presented in Lemma 7.9 in Barenco et al., 1995 (arXiv:quant-ph/9503016)
with optimizations from Theorem 5 of Iten et al., 2016 (arXiv:1501.06911)
"""
circuit.append(
LdMcSpecialUnitary(unitary, len(controls), ctrl_state), [*controls, target]
)
LdMcSpecialUnitary._apply_ctrl_state = apply_ctrl_state
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
n-qubit controlled gate
"""
from collections import namedtuple
import numpy as np
import qiskit
from qiskit.circuit import Gate
from qiskit import QuantumCircuit, QuantumRegister
from .util import check_u2, apply_ctrl_state
# pylint: disable=maybe-no-member
# pylint: disable=protected-access
class Ldmcu(Gate):
"""
Linear Depth Multi-Controlled Unitary
-----------------------------------------
Implements gate decomposition of a multi-controlled operator in U(2) according to
https://arxiv.org/abs/2203.11882
https://journals.aps.org/pra/abstract/10.1103/PhysRevA.106.042602.
"""
def __init__(self, unitary, num_controls, ctrl_state: str = None):
check_u2(unitary)
self.unitary = unitary
if num_controls > 0:
self.control_qubits = QuantumRegister(num_controls)
else:
self.control_qubits = []
self.target_qubit = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
super().__init__("Ldmcu", self.num_qubits, [], "Ldmcu")
def _define(self):
if len(self.control_qubits) > 0:
self.definition = QuantumCircuit(self.control_qubits, self.target_qubit)
self._apply_ctrl_state()
qubits_indexes = list(range(self.num_qubits))
gate_circuit = qiskit.QuantumCircuit(self.num_qubits, name="T" + str(0))
self._c1c2(self.unitary, self.num_qubits, gate_circuit)
self._c1c2(self.unitary, self.num_qubits, gate_circuit, step=-1)
self._c1c2(self.unitary, self.num_qubits - 1, gate_circuit, False)
self._c1c2(self.unitary, self.num_qubits - 1, gate_circuit, False, step=-1)
self.definition.append(gate_circuit, [*self.control_qubits, self.target_qubit])
self._apply_ctrl_state()
else:
self.definition = QuantumCircuit(self.target_qubit)
self.definition.unitary(self.unitary, 0)
def _c1c2(self, unitary, n_qubits, gate_circ, first=True, step=1):
pairs = namedtuple("pairs", ["control", "target"])
if step == 1:
start = 0
reverse = True
else:
start = 1
reverse = False
qubit_pairs = [
pairs(control, target)
for target in range(n_qubits)
for control in range(start, target)
]
qubit_pairs.sort(key=lambda e: e.control + e.target, reverse=reverse)
for pair in qubit_pairs:
exponent = pair.target - pair.control
if pair.control == 0:
exponent = exponent - 1
param = 2 ** exponent
signal = -1 if (pair.control == 0 and not first) else 1
signal = step * signal
if pair.target == n_qubits - 1 and first:
csqgate = Ldmcu._gate_u(unitary, param, signal)
gate_circ.compose(csqgate,
qubits=[pair.control, pair.target],
inplace=True)
else:
gate_circ.crx(signal * np.pi / param, pair.control, pair.target)
@staticmethod
def _gate_u(agate, coef, signal):
param = 1 / np.abs(coef)
values, vectors = np.linalg.eig(agate)
gate = np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T
gate = (
gate
+ np.power(values[1] + 0j, param) * vectors[:, [1]] @ vectors[:, [1]].conj().T
)
if signal < 0:
gate = np.linalg.inv(gate)
sqgate = QuantumCircuit(1, name="U^1/" + str(coef))
sqgate.unitary(gate, 0) # pylint: disable=maybe-no-member
csqgate = sqgate.control(1)
return csqgate
@staticmethod
def ldmcu(circuit, unitary, controls, target, ctrl_state=None):
circuit.append(
Ldmcu(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
Ldmcu._apply_ctrl_state = apply_ctrl_state
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Multicontrolled gate decompositions for unitaries in U(2) and SU(2)"""
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate
from .ldmcu import Ldmcu
from .ldmcsu import Ldmcsu
from .util import check_u2, check_su2, u2_to_su2
# pylint: disable=maybe-no-member
# pylint: disable=protected-access
class Mcg(Gate):
"""
Selects the most cost-effective multicontrolled gate decomposition.
"""
def __init__(
self,
unitary,
num_controls,
ctrl_state: str=None,
up_to_diagonal: bool=False
):
check_u2(unitary)
self.unitary = unitary
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
self.up_to_diagonal = up_to_diagonal
super().__init__("mcg", self.num_qubits, [], "mcg")
def _define(self):
self.definition = QuantumCircuit(self.controls, self.target)
num_ctrl = len(self.controls)
if num_ctrl == 0:
self.definition.unitary(self.unitary, [self.target])
elif num_ctrl == 1:
u_gate = QuantumCircuit(1)
u_gate.unitary(self.unitary, 0)
self.definition.append(
u_gate.control(num_ctrl, ctrl_state=self.ctrl_state),
[*self.controls, self.target]
)
else:
if check_su2(self.unitary):
Ldmcsu.ldmcsu(
self.definition,
self.unitary,
self.controls,
self.target,
ctrl_state=self.ctrl_state
)
else:
if self.up_to_diagonal:
su_2, _ = u2_to_su2(self.unitary)
self.mcg(su_2, self.controls, self.target, self.ctrl_state)
else:
Ldmcu.ldmcu(self.definition, self.unitary, self.controls[:], self.target[0], self.ctrl_state)
@staticmethod
def mcg(
circuit,
unitary,
controls,
target,
ctrl_state: str = None
):
circuit.append(
Mcg(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
n-qubit controlled gate
"""
from collections import namedtuple
import numpy as np
import qiskit
from qiskit.circuit import Gate
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.util import check_u2, apply_ctrl_state
from qclib.gates.multitargetmcsu2 import MultiTargetMCSU2
from qclib.gates.ldmcu import Ldmcu
# pylint: disable=protected-access
class MCU(Gate):
"""
Approximated Multi-Controlled Unitary Gate
https://arxiv.org/abs/2310.14974
-----------------------------------------
Implements gate decomposition of a multi-controlled operator in U(2)
"""
def __init__(self, unitary, num_controls, error=0, ctrl_state: str = None):
"""
Parameters
----------
unitary: U(2) gate
num_controls (int): Number of controls
error (float): max_error
ctrl_state (str or int): Control state in decimal or as a bitstring
"""
check_u2(unitary)
self.unitary = unitary
self.error = error
if num_controls > 0:
self.control_qubits = QuantumRegister(num_controls)
else:
self.control_qubits = []
self.target_qubit = QuantumRegister(1)
self.n_ctrl_base = self._get_num_base_ctrl_qubits(self.unitary, self.error)
if self.n_ctrl_base == 0:
raise ValueError("The number of base qubits is 0")
if self.n_ctrl_base > num_controls:
raise ValueError("The number of control qubits is too low")
self.ctrl_state = ctrl_state
super().__init__("McuApprox", num_controls + 1, [], "McuApprox")
def _define(self):
if len(self.control_qubits) > 0:
self.definition = QuantumCircuit(self.control_qubits, self.target_qubit)
self._apply_ctrl_state()
gate_circuit = qiskit.QuantumCircuit(self.num_qubits, name="T" + str(0))
self._c1c2(self.num_qubits, gate_circuit)
self._c1c2(self.num_qubits, gate_circuit, step=-1)
self._c1c2(self.num_qubits - 1, gate_circuit, False)
self._c1c2(self.num_qubits - 1, gate_circuit, False, -1)
self.definition.append(
gate_circuit, [*self.control_qubits, self.target_qubit]
)
self._apply_ctrl_state()
else:
self.definition = QuantumCircuit(self.target_qubit)
self.definition.unitary(self.unitary, 0)
@staticmethod
def _get_num_base_ctrl_qubits(unitary, error):
"""
Get the baseline number of control qubits for the approximation
given an error
args:
unitary: Unitary to be approximated
error: Error of the approximation
"""
eig_vals, _ = np.linalg.eig(unitary)
angles = np.angle(eig_vals)
if (1 - np.cos(angles[0])) >= (1 - np.cos(angles[1])):
angle = angles[0]
else:
angle = angles[1]
quotient = angle / np.arccos(1 - error**2 / 2)
return int(np.ceil(np.log2(quotient))) + 1
def get_n_base(self, unitary, error):
return self._get_num_base_ctrl_qubits(unitary, error)
def _c1c2(self, n_qubits, gate_circ, first=True, step=1):
extra_q, n_qubits_base = self._calc_extra_qubits(first, n_qubits)
qubit_pairs = self._compute_qubit_pairs(n_qubits_base, step)
unitary_list = []
targets = []
for pair in qubit_pairs:
param = self._compute_param(pair)
signal = -1 if (pair.control == 0 and not first) else 1
signal = step * signal
# Perform a translation of the qubits by extra_q qubits in all cases
# When target == last qubit and first==true apply the U gates, except
# when control==0, in which case we don't do anything
if pair.target == n_qubits_base - 1 and first:
if pair.control != 0:
csqgate = MCU._gate_u(self.unitary, param, signal)
gate_circ.compose(
csqgate,
qubits=[pair.control + extra_q, pair.target + extra_q],
inplace=True,
)
# For the controlled rotations, when control==0, apply a multi-controlled
# rotation with the extra control qubits
else:
if pair.control == 0 and extra_q >= 1:
# Apply a multi-controlled Rx gate with the additional control qubits
control_list = np.array(range(0, extra_q + 1))
unitary_list.append(self._compute_rx_matrix(param, signal))
targets.append(pair.target + extra_q)
if pair.target == 1:
MultiTargetMCSU2.multi_target_mcsu2(
gate_circ, unitary_list, control_list, targets
)
else:
gate_circ.crx(
signal * np.pi / param,
pair.control + extra_q,
pair.target + extra_q,
)
def _calc_extra_qubits(self, first, n_qubits):
if first:
n_qubits_base = self.n_ctrl_base + 1
else:
n_qubits_base = self.n_ctrl_base
extra_q = n_qubits - n_qubits_base
return extra_q, n_qubits_base
@staticmethod
def _compute_param(pair):
exponent = pair.target - pair.control
if pair.control == 0:
exponent = exponent - 1
param = 2**exponent
return param
@staticmethod
def _compute_rx_matrix(param, signal):
theta = signal * np.pi / param
rx_matrix = np.array(
[
[np.cos(theta / 2), (-1j) * np.sin(theta / 2)],
[(-1j) * np.sin(theta / 2), np.cos(theta / 2)],
]
)
return rx_matrix
@staticmethod
def _compute_qubit_pairs(n_qubits_base, step):
pairs = namedtuple("pairs", ["control", "target"])
if step == 1:
start = 0
reverse = True
else:
start = 1
reverse = False
qubit_pairs = [
pairs(control, target)
for target in range(n_qubits_base)
for control in range(start, target)
]
qubit_pairs.sort(key=lambda e: e.control + e.target, reverse=reverse)
return qubit_pairs
@staticmethod
def _gate_u(a_gate, coefficient, signal):
param = 1 / np.abs(coefficient)
values, vectors = np.linalg.eig(a_gate)
gate = (
np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T
)
gate = (
gate
+ np.power(values[1] + 0j, param)
* vectors[:, [1]]
@ vectors[:, [1]].conj().T
)
if signal < 0:
gate = np.linalg.inv(gate)
s_q_gate = QuantumCircuit(1, name="U^1/" + str(coefficient))
s_q_gate.unitary(gate, 0) # pylint: disable=maybe-no-member
c_s_q_gate = s_q_gate.control(1)
return c_s_q_gate
@staticmethod
def mcu(circuit, unitary, controls, target, error, ctrl_state=None):
"""
Approximated Multi-Controlled Unitary Gate
https://arxiv.org/abs/2310.14974
"""
if error == 0:
circuit.append(
Ldmcu(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
else:
circuit.append(
MCU(unitary, len(controls), error, ctrl_state=ctrl_state),
[*controls, target],
)
MCU._apply_ctrl_state = apply_ctrl_state
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
linear-depth n-qubit controlled X with ancilla
"""
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import C3XGate, C4XGate
from qiskit.circuit import Gate
from qclib.gates.toffoli import Toffoli
from qclib.gates.util import apply_ctrl_state
# pylint: disable=protected-access
class McxVchainDirty(Gate):
"""
Implementation based on lemma 8 of Iten et al. (2016) arXiv:1501.06911.
Decomposition of a multicontrolled X gate with at least k <= ceil(n/2) ancilae
for n as the total number of qubits in the system. It also includes optimizations
using approximated Toffoli gates up to a diagonal.
"""
def __init__(
self,
num_controls: int,
num_target_qubit=1,
ctrl_state=None,
relative_phase=False,
action_only=False,
):
"""
Parameters
----------
num_target_qubit
num_controls
ctrl_state
relative_phase
action_only
"""
self.control_qubits = QuantumRegister(num_controls)
self.target_qubits = QuantumRegister(num_target_qubit)
self.ctrl_state = ctrl_state
self.relative_phase = relative_phase
self.action_only = action_only
num_ancilla = 0
self.ancilla_qubits = []
if num_controls - 2 > 0:
num_ancilla = num_controls - 2
self.ancilla_qubits = QuantumRegister(num_ancilla)
super().__init__(
"mcx_vc_dirty", num_controls + num_ancilla + 1, [], "mcx_vc_dirty"
)
@staticmethod
def toffoli_multi_target(num_targets, side=None):
""" " """
size = 2 + num_targets
circuit = QuantumCircuit(size)
if side == "l":
for i in range(num_targets - 1):
circuit.name = 'toff_left'
circuit.cx(size - i - 2, size - i - 1)
circuit.ccx(0, 1, 2)
return circuit
elif side == "r":
circuit.name = 'toff_right'
circuit.ccx(0, 1, 2)
for i in range(num_targets - 1):
circuit.cx(i + 2, i + 3)
return circuit
elif side is None:
circuit.name = 'toff_l_and_r'
for i in range(num_targets - 1):
circuit.cx(size - i - 2, size - i - 1)
circuit.ccx(0, 1, 2)
for i in range(num_targets - 1):
circuit.cx(i + 2, i + 3)
return circuit
def _define(self):
self.definition = QuantumCircuit(
self.control_qubits, self.ancilla_qubits, self.target_qubits
)
num_ctrl = len(self.control_qubits)
num_target = len(self.target_qubits)
num_ancilla = num_ctrl - 2
targets_aux = self.target_qubits[0:1] + self.ancilla_qubits[:num_ancilla][::-1]
self._apply_ctrl_state()
if num_ctrl == 2:
self.definition.append(
self.toffoli_multi_target(len(self.target_qubits)),
[*self.control_qubits, *self.target_qubits],
)
elif num_ctrl == 1:
for k, _ in enumerate(self.target_qubits):
self.definition.mcx(
control_qubits=self.control_qubits,
target_qubit=self.target_qubits[k],
mode="noancilla",
)
elif not self.relative_phase and num_ctrl == 3 and num_target < 2:
for k, _ in enumerate(self.target_qubits):
self.definition.append(
C3XGate(), [*self.control_qubits[:], self.target_qubits[k]], []
)
else:
side = 'l'
for j in range(2):
self._action_circuit(j, num_ancilla, num_ctrl, targets_aux, side)
side = 'r'
for i, _ in enumerate(self.ancilla_qubits[1:]): # reset part
controls = [self.control_qubits[2 + i], self.ancilla_qubits[i]]
self.definition.append(
Toffoli(cancel="left"), [*controls, self.ancilla_qubits[i + 1]]
)
if self.action_only:
control_1 = self.control_qubits[-1]
control_2 = self.ancilla_qubits[-1]
targets = self.target_qubits
num_targets = len(targets)
self.definition.append(
self.toffoli_multi_target(num_targets, side),
[control_1, control_2, *targets],
)
break
self._apply_ctrl_state()
def _action_circuit(self, j, num_ancilla, num_ctrl, targets_aux, side):
for i, _ in enumerate(self.control_qubits): # action part
if i < num_ctrl - 2:
if (
targets_aux[i] not in self.target_qubits
or self.relative_phase
):
# gate cancelling
controls = [
self.control_qubits[num_ctrl - i - 1],
self.ancilla_qubits[num_ancilla - i - 1],
]
# cancel rightmost gates of action part
# with leftmost gates of reset part
if (
self.relative_phase
and targets_aux[i] in self.target_qubits
and j == 1
):
self.definition.append(
Toffoli(cancel="left"), [*controls, targets_aux[i]]
)
else:
self.definition.append(
Toffoli(cancel="right"), [*controls, targets_aux[i]]
)
else:
control_1 = self.control_qubits[num_ctrl - i - 1]
control_2 = self.ancilla_qubits[num_ancilla - i - 1]
targets = self.target_qubits
num_targets = len(targets)
self.definition.append(
self.toffoli_multi_target(num_targets, side),
[control_1, control_2, *targets],
)
else:
controls = [
self.control_qubits[num_ctrl - i - 2],
self.control_qubits[num_ctrl - i - 1],
]
self.definition.append(Toffoli(), [*controls, targets_aux[i]])
break
@staticmethod
def mcx_vchain_dirty(
circuit,
controls=None,
target=None,
ctrl_state=None,
relative_phase=False,
action_only=False,
):
"""
Implementation based on lemma 8 of Iten et al. (2016) arXiv:1501.06911.
Decomposition of a multicontrolled X gate with at least k <= ceil(n/2) ancilae
for n as the total number of qubits in the system. It also includes optimizations
using approximated Toffoli gates up to a diagonal.
"""
circuit.append(
McxVchainDirty(len(controls), ctrl_state, relative_phase, action_only),
[*controls, target],
)
McxVchainDirty._apply_ctrl_state = apply_ctrl_state
class LinearMcx(Gate):
"""
Implementation based on lemma 9 of Iten et al. (2016) arXiv:1501.06911.
Decomposition of a multicontrolled X gate with a dirty ancilla by splitting
it into two sequences of two alternating multicontrolled X gates on
k1 = ceil((n+1)/2) and k2 = floor((n+1)/2) qubits. For n the total
number of qubits in the system. Where it also reuses some optimizations available
"""
def __init__(self, num_controls, ctrl_state=None, action_only=False):
self.action_only = action_only
self.ctrl_state = ctrl_state
num_qubits = num_controls + 2
self.control_qubits = list(range(num_qubits - 2))
self.target_qubit = (num_qubits - 2,)
self.ancilla_qubit = num_qubits - 1
super().__init__("linear_mcx", num_controls + 2, [], "mcx")
def _define(self):
self.definition = QuantumCircuit(self.num_qubits)
self._apply_ctrl_state()
if self.num_qubits < 5:
self.definition.mcx(
control_qubits=self.control_qubits,
target_qubit=self.target_qubit,
mode="noancilla",
)
elif self.num_qubits == 5:
self.definition.append(
C3XGate(), [*self.control_qubits[:], self.target_qubit], []
)
elif self.num_qubits == 6:
self.definition.append(
C4XGate(), [*self.control_qubits[:], self.target_qubit], []
)
elif self.num_qubits == 7:
self.definition.append(
C3XGate(), [*self.control_qubits[:3], self.ancilla_qubit], []
)
self.definition.append(
C3XGate(),
[*self.control_qubits[3:], self.ancilla_qubit, self.target_qubit],
[],
)
self.definition.append(
C3XGate(), [*self.control_qubits[:3], self.ancilla_qubit], []
)
self.definition.append(
C3XGate(),
[*self.control_qubits[3:], self.ancilla_qubit, self.target_qubit],
[],
)
else:
# split controls to halve the number of qubits used for each mcx
num_ctrl = len(self.control_qubits)
k_2 = int(np.ceil(self.num_qubits / 2.0))
k_1 = num_ctrl - k_2 + 1
first_gate = McxVchainDirty(k_1, relative_phase=True).definition
second_gate = McxVchainDirty(k_2).definition
self.definition.append(
first_gate,
self.control_qubits[:k_1]
+ self.control_qubits[k_1 : k_1 + k_1 - 2]
+ [self.ancilla_qubit],
)
self.definition.append(
second_gate,
[*self.control_qubits[k_1:], self.ancilla_qubit]
+ self.control_qubits[k_1 - k_2 + 2 : k_1]
+ [self.target_qubit],
)
self.definition.append(
first_gate,
self.control_qubits[:k_1]
+ self.control_qubits[k_1 : k_1 + k_1 - 2]
+ [self.ancilla_qubit],
)
last_gate = McxVchainDirty(k_2, action_only=self.action_only).definition
self.definition.append(
last_gate,
[*self.control_qubits[k_1:], self.ancilla_qubit]
+ self.control_qubits[k_1 - k_2 + 2 : k_1]
+ [self.target_qubit],
)
self._apply_ctrl_state()
@staticmethod
def mcx(circuit, controls=None, target=None, ctrl_state=None, action_only=False):
"""
Implementation based on lemma 9 of Iten et al. (2016) arXiv:1501.06911.
Decomposition of a multicontrolled X gate with a dirty ancilla by splitting
it into two sequences of two alternating multicontrolled X gates on
k1 = ceil((n+1)/2) and k2 = floor((n+1)/2) qubits. For n the total
number of qubits in the system. Where it also reuses some optimizations available
"""
circuit.append(
LinearMcx(len(controls), ctrl_state, action_only), [*controls, target]
)
LinearMcx._apply_ctrl_state = apply_ctrl_state
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Linear-depth Multicontrolled Special Unitary
"""
from typing import Union, List
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import UnitaryGate
from qiskit.circuit import Gate, Qubit
from qclib.gates.ldmcsu import Ldmcsu
from qclib.gates.mcx import McxVchainDirty
from qclib.gates.util import check_su2, isclose
# pylint: disable=protected-access
class MultiTargetMCSU2(Gate):
"""
Multi-target Multi-Controlled Gate for Special Unitary
------------------------------------------------
Linear decomposition of approximate multi-controlled single qubit gates
https://arxiv.org/abs/2310.14974 Lemma 7
"""
def __init__(self, unitaries, num_controls, num_target=1, ctrl_state: str = None):
"""
Parameters
----------
unitaries (list): List of SU(2) matrices
num_controls (int): Number of control gastes
num_target (int): Number of target gates
ctrl_state (str): Control state in decimal or as a bitstring
"""
if isinstance(unitaries, list):
for unitary in unitaries:
check_su2(unitary)
else:
check_su2(unitaries)
self.unitaries = unitaries
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(num_target)
self.num_controls = num_controls + 1
self.ctrl_state = ctrl_state
super().__init__("ldmcsu", self.num_controls, [], "ldmcsu")
def _define(self):
if isinstance(self.unitaries, list):
self.definition = QuantumCircuit(self.controls, self.target)
is_main_diags_real = []
is_secondary_diags_real = []
for unitary in self.unitaries:
is_main_diags_real.append(
isclose(unitary[0, 0].imag, 0.0)
and isclose(unitary[1, 1].imag, 0.0)
)
is_secondary_diags_real.append(
isclose(unitary[0, 1].imag, 0.0)
and isclose(unitary[1, 0].imag, 0.0)
)
for idx, unitary in enumerate(self.unitaries):
if not is_secondary_diags_real[idx] and is_main_diags_real[idx]:
self.definition.h(self.target[idx])
self.clinear_depth_mcv()
for idx, unitary in enumerate(self.unitaries):
if not is_secondary_diags_real[idx] and is_main_diags_real[idx]:
self.definition.h(self.target[idx])
else:
self.definition = Ldmcsu(self.unitaries, self.num_controls)
def clinear_depth_mcv(self, general_su2_optimization=False):
"""
Multi-target version of Theorem 1 - https://arxiv.org/pdf/2302.06377.pdf
"""
# S gate definition
gates_a = self._s_gate_definition(self.unitaries)
num_ctrl = len(self.controls)
target_size = len(self.target)
k_1 = int(np.ceil(num_ctrl / 2.0))
k_2 = int(np.floor(num_ctrl / 2.0))
ctrl_state_k_1 = None
ctrl_state_k_2 = None
if self.ctrl_state is not None:
ctrl_state_k_1 = self.ctrl_state[::-1][:k_1][::-1]
ctrl_state_k_2 = self.ctrl_state[::-1][k_1:][::-1]
if not general_su2_optimization:
mcx_1 = McxVchainDirty(
k_1, num_target_qubit=target_size, ctrl_state=ctrl_state_k_1
).definition
self.definition.append(
mcx_1,
self.controls[:k_1] + self.controls[k_1: 2 * k_1 - 2] + [*self.target],
)
for idx, gate_a in enumerate(gates_a):
self.definition.append(gate_a, [num_ctrl + idx])
mcx_2 = McxVchainDirty(
k_2,
num_target_qubit=target_size,
ctrl_state=ctrl_state_k_2,
action_only=general_su2_optimization,
).definition
self.definition.append(
mcx_2.inverse(),
self.controls[k_1:] + self.controls[k_1 - k_2 + 2: k_1] + [*self.target],
)
for idx, gate_a in enumerate(gates_a):
self.definition.append(gate_a.inverse(), [num_ctrl + idx])
mcx_3 = McxVchainDirty(
k_1, num_target_qubit=target_size, ctrl_state=ctrl_state_k_1
).definition
self.definition.append(
mcx_3,
self.controls[:k_1] + self.controls[k_1: 2 * k_1 - 2] + [*self.target],
)
for idx, gate_a in enumerate(gates_a):
self.definition.append(gate_a, [num_ctrl + idx])
mcx_4 = McxVchainDirty(
k_2, num_target_qubit=target_size, ctrl_state=ctrl_state_k_2
).definition
self.definition.append(
mcx_4,
self.controls[k_1:] + self.controls[k_1 - k_2 + 2: k_1] + [*self.target],
)
for idx, gate_a in enumerate(gates_a):
self.definition.append(gate_a.inverse(), [num_ctrl + idx])
def _s_gate_definition(self, su2_unitaries):
gates_a = []
for su2_unitary in su2_unitaries:
x_value, z_value = Ldmcsu._get_x_z(su2_unitary)
op_a = Ldmcsu._compute_gate_a(x_value, z_value)
gates_a.append(UnitaryGate(op_a))
return gates_a
@staticmethod
def multi_target_mcsu2(
circuit,
unitary,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str = None,
):
"""
Multi-target version of multi-controlled SU(2)
https://arxiv.org/abs/2302.06377
"""
if isinstance(unitary, list):
num_target = len(unitary)
circuit.append(
MultiTargetMCSU2(unitary, len(controls), num_target=num_target).definition,
[*controls, *target],
)
else:
circuit.append(
Ldmcsu(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target],
)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Quadratic-depth Multicontrolled Special Unitary
"""
from typing import Union, List
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Qubit
from qiskit.circuit import Gate
from numpy import sqrt, outer
from numpy.linalg import eig
from .mcx import LinearMcx
from .util import check_u2
# pylint: disable=protected-access
class Qdmcu(Gate):
"""
Quandratic Depth Multi-Controlled Unitary
-----------------------------------------
Implements gate decomposition of a munticontrolled operator in U(2) according to
Theorem 4 of Iten et al. (2016) arXiv:1501.06911.
"""
def __init__(
self,
unitary,
num_controls,
ctrl_state: str=None
):
"""
Parameters
----------
unitary : numpy.ndarray 2 x 2 unitary matrix
controls : Either qiskit.QuantumRegister or list of qiskit.Qubit containing the
qubits to be used as control gates.
target : qiskit.Qubit on wich the unitary operation is to be applied
ctrl_state : String of binary digits describing the basis state used as control
"""
check_u2(unitary)
self.unitary = unitary
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
super().__init__("qdmcu", self.num_qubits, [], "qdmcu")
def _define(self):
self.definition = QuantumCircuit(self.controls, self.target)
num_ctrl = len(self.controls)
if num_ctrl == 1:
u_gate = QuantumCircuit(1)
u_gate.unitary(self.unitary, 0)
self.definition.append(
u_gate.control(
num_ctrl_qubits=num_ctrl,
ctrl_state=self.ctrl_state
),
[*self.controls, self.target]
)
else:
if self.ctrl_state is None:
self.ctrl_state = '1' * num_ctrl
# Notice that `ctrl_state`` is reversed with respect to `controls``.
v_op = Qdmcu.custom_sqrtm(self.unitary)
v_gate = QuantumCircuit(1, name="V")
v_gate.unitary(v_op, 0)
v_gate_dag = QuantumCircuit(1, name="V^dag")
v_gate_dag.unitary(v_op.T.conj(), 0)
linear_mcx_gate = LinearMcx(
num_controls=num_ctrl-1,
ctrl_state=self.ctrl_state[1:],
action_only=True
).definition
self.definition.append(
v_gate.control(1, ctrl_state=self.ctrl_state[:1]),
[self.controls[-1], self.target]
)
self.definition.append(
linear_mcx_gate,
[*self.controls[:-1], self.controls[-1], self.target]
)
self.definition.append(
v_gate_dag.control(1, ctrl_state=self.ctrl_state[:1]),
[self.controls[-1], self.target]
)
self.definition.append(
linear_mcx_gate.inverse(),
[*self.controls[:-1], self.controls[-1], self.target]
)
self.qdmcu(
self.definition,
v_op,
self.controls[:-1],
self.target,
self.ctrl_state[1:]
)
@staticmethod
def custom_sqrtm(unitary):
eig_vals, eig_vecs = eig(unitary)
first_eig = sqrt(eig_vals[0]) * outer(eig_vecs[:, 0], eig_vecs[:, 0].conj())
second_eig = sqrt(eig_vals[1]) * outer(eig_vecs[:, 1], eig_vecs[:, 1].conj())
return first_eig + second_eig
@staticmethod
def qdmcu(
circuit,
unitary,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str=None
):
circuit.append(
Qdmcu(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Toffoli decomposition explained in Lemma 8 from
Quantum Circuits for Isometries.
https://arxiv.org/abs/1501.06911
'''
from numpy import pi
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
class Toffoli(Gate):
def __init__(self, cancel=None):
self.cancel = cancel
super().__init__('toffoli', 3, [], "Toffoli")
def _define(self):
self.definition = QuantumCircuit(3)
theta = pi / 4.
control_qubits = self.definition.qubits[:2]
target_qubit = self.definition.qubits[-1]
if self.cancel != 'left':
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=-theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[1], target_qubit)
if self.cancel != 'right':
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
self.definition.cx(control_qubits[0], target_qubit)
self.definition.u(theta=theta, phi=0., lam=0., qubit=target_qubit)
@staticmethod
def ccx(circuit, controls=None, target=None, cancel=None):
if controls is None or target is None:
circuit.append(Toffoli(cancel), circuit.qubits[:3])
else:
circuit.append(Toffoli(cancel), [*controls, target])
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Constructs a multiplexor gate.
"""
from math import log2
from typing import List, Union, Type
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import RZGate, RYGate, CXGate, CZGate
def ucr(
r_gate: Union[Type[RZGate], Type[RYGate]],
angles: List[float],
c_gate: Union[Type[CXGate], Type[CZGate]] = CXGate,
last_control=True,
) -> QuantumCircuit:
"""
Constructs a multiplexor rotation gate.
Synthesis of Quantum Logic Circuits
https://arxiv.org/abs/quant-ph/0406176
"""
size = len(angles)
n_qubits = int(log2(size)) + 1
reg = QuantumRegister(n_qubits)
circuit = QuantumCircuit(reg)
target = reg[0]
control = reg[n_qubits - 1]
if n_qubits == 1:
if abs(angles[0]) > 10**-8:
circuit.append(r_gate(angles[0]), [target])
return circuit
angle_multiplexor = np.kron(
[[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (n_qubits - 2))
)
multiplexed_angles = angle_multiplexor.dot(angles)
# Figure 2 from Synthesis of Quantum Logic Circuits:
# The recursive decomposition of a multiplexed Rz gate.
# The boxed CNOT gates may be canceled.
# This is why "last_cnot=False" in both calls of "rotation_multiplexor()" and
# also why the multiplexer in the second "circuit.append()" is reversed.
mult = ucr(r_gate, multiplexed_angles[: size // 2], c_gate, False)
circuit.append(mult.to_instruction(), reg[0:-1])
circuit.append(c_gate(), [control, target])
mult = ucr(r_gate, multiplexed_angles[size // 2 :], c_gate, False)
circuit.append(mult.reverse_ops().to_instruction(), reg[0:-1])
# The following condition allows saving CNOTs when two multiplexors are used
# in sequence. Any multiplexor can have its operation reversed. Therefore, if
# the second multiplexor is reverted, its last CNOT will be cancelled by the
# last CNOT of the first multiplexer. In this condition, both last CNOTs are
# unnecessary.
if last_control:
circuit.append(c_gate(), [control, target])
return circuit
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Bounded Approximation version of Plesch's algorithm.
https://arxiv.org/abs/2111.03132
"""
from dataclasses import dataclass
from qiskit import QuantumCircuit
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.baa import adaptive_approximation
from .lowrank import LowRankInitialize
@dataclass
class _OptParams:
def __init__(self, opt_params):
if opt_params is None:
self.max_fidelity_loss = 0.0
self.isometry_scheme = "ccd"
self.unitary_scheme = "qsd"
self.strategy = "greedy"
self.max_combination_size = 0
self.use_low_rank = False
else:
self.max_fidelity_loss = 0.0 if opt_params.get("max_fidelity_loss") is None \
else opt_params.get("max_fidelity_loss")
self.isometry_scheme = "ccd" if opt_params.get("iso_scheme") is None else \
opt_params.get("iso_scheme")
self.unitary_scheme = "qsd" if opt_params.get("unitary_scheme") is None else \
opt_params.get("unitary_scheme")
self.strategy = "greedy" if opt_params.get("strategy") is None else \
opt_params.get("strategy")
self.max_combination_size = 0 if opt_params.get("max_combination_size") is None else \
opt_params.get("max_combination_size")
self.use_low_rank = False if opt_params.get("use_low_rank") is None else \
opt_params.get("use_low_rank")
if self.max_fidelity_loss < 0 or self.max_fidelity_loss > 1:
self.max_fidelity_loss = 0.0
class BaaLowRankInitialize(Initialize):
"""
State preparation using the bounded approximation algorithm via Schmidt
decomposition arXiv:1003.5760
https://arxiv.org/abs/2111.03132
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: Dictionary
max_fidelity_loss: float
``state`` allowed (fidelity) error for approximation
(0<=``max_fidelity_loss``<=1). If ``max_fidelity_loss`` is not in the valid
range, it will be ignored.
isometry_scheme: string
Scheme used to decompose isometries.
Possible values are ``'knill'`` and ``'ccd'`` (column-by-column decomposition).
Default is ``isometry_scheme='ccd'``.
unitary_scheme: string
Scheme used to decompose unitaries.
Possible values are ``'csd'`` (cosine-sine decomposition) and ``'qsd'`` (quantum
Shannon decomposition).
Default is ``unitary_scheme='qsd'``.
strategy: string
Method to search for the best approximation (``'brute_force'`` or ``'greedy'``).
For states larger than 2**8, the greedy strategy should preferably be used.
Default is ``strategy='greedy'``.
max_combination_size: int
Maximum size of the combination ``C(n_qubits, max_combination_size)``
between the qubits of an entangled subsystem of length ``n_qubits`` to
produce the possible bipartitions
(1 <= ``max_combination_size`` <= ``n_qubits``//2).
For example, if ``max_combination_size``==1, there will be ``n_qubits``
bipartitions between 1 and ``n_qubits``-1 qubits.
The default value is 0 (the size will be maximum for each level).
use_low_rank: bool
If set to True, ``rank``>1 approximations are also considered. This is fine
tuning for high-entanglement states and is slower.
The default value is False.
"""
self._name = "baa-lrsp"
self._get_num_qubits(params)
self.node = None
self.opt_params = _OptParams(opt_params)
if label is None:
self._label = "BAASP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
self.node = adaptive_approximation(
self.params,
self.opt_params.max_fidelity_loss,
self.opt_params.strategy,
self.opt_params.max_combination_size,
self.opt_params.use_low_rank,
)
circuit = QuantumCircuit(self.num_qubits)
for vector, qubits, rank, partition in zip(
self.node.vectors, self.node.qubits, self.node.ranks, self.node.partitions
):
opt_params = {
"iso_scheme": self.opt_params.isometry_scheme,
"unitary_scheme": self.opt_params.unitary_scheme,
"partition": partition,
"lr": rank,
}
gate = LowRankInitialize(vector, opt_params=opt_params)
circuit.compose(gate, qubits[::-1], inplace=True) # qiskit little-endian.
return circuit.reverse_bits()
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a BaaLowRankInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
BaaLowRankInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(BaaLowRankInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Bidirectional state preparation
https://arxiv.org/abs/2108.10182
"""
from math import ceil, log2
import numpy as np
from qiskit import QuantumCircuit
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.state_tree_preparation import (
Amplitude,
state_decomposition,
)
from qclib.state_preparation.util.angle_tree_preparation import create_angles_tree
from qclib.state_preparation.util.tree_register import add_register
from qclib.state_preparation.util.tree_walk import top_down, bottom_up
class BdspInitialize(Initialize):
"""
Configurable sublinear circuits for quantum state preparation
https://arxiv.org/abs/2108.10182
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: {'split': split}
split: int
Level (enumerated from bottom to top, where 1 ≤ s ≤ n)
at which the angle tree is split.
Default value is ``ceil(n_qubits/2)`` (sublinear).
"""
if opt_params is None:
self.split = int(ceil(log2(len(params)) / 2)) # sublinear
else:
if opt_params.get("split") is None:
self.split = int(ceil(log2(len(params)) / 2)) # sublinear
else:
self.split = opt_params.get("split")
self._name = "bdsp"
self._get_num_qubits(params)
if label is None:
label = "BDSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
n_qubits = int(np.log2(len(self.params)))
data = [Amplitude(i, a) for i, a in enumerate(self.params)]
state_tree = state_decomposition(n_qubits, data)
angle_tree = create_angles_tree(state_tree)
circuit = QuantumCircuit()
add_register(circuit, angle_tree, n_qubits - self.split)
top_down(angle_tree, circuit, n_qubits - self.split)
bottom_up(angle_tree, circuit, n_qubits - self.split)
return circuit
def _get_num_qubits(self, params):
n_qubits = log2(len(params))
if not n_qubits.is_integer():
Exception("The number of amplitudes is not a power of 2")
n_qubits = int(n_qubits)
self.num_qubits = (self.split + 1) * 2 ** (n_qubits - self.split) - 1
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a BdspInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
BdspInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(BdspInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Black-box state preparation
Grover, Lov K. "Synthesis of quantum superpositions by quantum computation."
Physical review letters 85.6 (2000): 1334.
Gate U2 in PRL 85.6 (2000) is implemented with uniformly controlled rotations
"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import UCRYGate, UCRZGate
from qiskit.circuit.library import UnitaryGate
from qclib.gates.initialize import Initialize
class BlackBoxInitialize(Initialize):
"""
Black-box state preparation
Grover, Lov K. "Synthesis of quantum superpositions by quantum computation."
Physical review letters 85.6 (2000): 1334.
Gate U2 in PRL 85.6 (2000) is implemented with uniformly controlled rotations
"""
def __init__(self, params, label=None):
self._name = "blackbox"
self._get_num_qubits(params)
self.num_qubits += 1
if label is None:
label = "BBSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
n_amplitudes = len(self.params)
theta = 2 * np.arccos(np.abs(self.params))
phi = -2 * np.angle(self.params)
ury_gate = UCRYGate(list(theta))
urz_gate = UCRZGate(list(phi))
gate_u = QuantumCircuit(self.num_qubits, name="U")
gate_u.h(gate_u.qubits[1:])
gate_u.append(ury_gate, gate_u.qubits)
gate_u.append(urz_gate, gate_u.qubits)
gate_u = gate_u.to_instruction()
it_matrix = [[-1, 0], [0, 1]]
gate_it = UnitaryGate(it_matrix)
gate_it.name = "I_t"
gate_is = gate_it.control(self.num_qubits - 1, ctrl_state=0)
gate_is.name = "I_s"
repetitions = (np.pi / 4) * (
np.sqrt(n_amplitudes) / np.linalg.norm(self.params)
)
repetitions = int(repetitions)
q_circuit = QuantumCircuit(self.num_qubits)
for _ in range(repetitions):
q_circuit.append(gate_u, q_circuit.qubits)
q_circuit.append(gate_it, q_circuit.qubits[0:1])
q_circuit.append(gate_u.inverse(), q_circuit.qubits)
q_circuit.append(gate_is, q_circuit.qubits)
q_circuit.append(gate_u, q_circuit.qubits)
if repetitions % 2 == 1:
q_circuit.global_phase = np.pi
return q_circuit
@staticmethod
def initialize(q_circuit, state, qubits=None):
if qubits is None:
q_circuit.append(BlackBoxInitialize(state), q_circuit.qubits)
else:
q_circuit.append(BlackBoxInitialize(state), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" cvo-qram """
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import UGate
from qiskit.quantum_info import Operator
from qclib.util import _compute_matrix_angles
from qclib.gates.initialize_sparse import InitializeSparse
from qclib.gates.mcg import Mcg
from qclib.gates.ldmcsu import LdMcSpecialUnitary
# pylint: disable=maybe-no-member
class CvoqramInitialize(InitializeSparse):
"""
Initializing the Amplitude Distribution of a Quantum State
This class implements a sparse state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
self._get_num_qubits(params)
self.norm = 1
self.anc = None
self.aux = None
self.memory = None
self.control = None
default_with_aux = True
if opt_params is None:
self.with_aux = default_with_aux
self.mcg_method = 'linear'
else:
if opt_params.get("with_aux") is None:
self.with_aux = default_with_aux
else:
self.with_aux = opt_params.get("with_aux")
if opt_params.get("mcg_method") is None:
self.mcg_method = 'linear'
else:
self.mcg_method = opt_params.get("mcg_method")
if label is None:
label = "CVOSP"
super().__init__("cvoqram", self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
"""Initialize quantum registers"""
self.anc = QuantumRegister(self.num_qubits - 1, name="anc")
self.aux = QuantumRegister(1, name="u")
self.memory = QuantumRegister(self.num_qubits, name="m")
if self.with_aux:
circuit = QuantumCircuit(self.aux, self.anc, self.memory)
else:
self.anc = None
circuit = QuantumCircuit(self.aux, self.memory)
self.norm = 1
circuit.x(self.aux[0])
for k, (binary_string, feature) in enumerate(self.params):
self.control = self._select_controls(binary_string)
self._flip_flop(circuit)
self._load_superposition(circuit, feature, self.control, self.memory)
if k < len(self.params) - 1:
self._flip_flop(circuit)
else:
break
return circuit
def _flip_flop(self, circuit):
for k in self.control:
circuit.cx(self.aux[0], self.memory[k])
@staticmethod
def _select_controls(binary_string):
control = []
for k, bit in enumerate(binary_string[::-1]):
if bit == "1":
control.append(k)
return control
def _mcuvchain(self, circuit, alpha, beta, phi):
"""
N-qubit controlled-unitary gate
"""
lst_ctrl = self.control
lst_ctrl_reversed = list(reversed(lst_ctrl))
circuit.rccx(
self.memory[lst_ctrl_reversed[0]],
self.memory[lst_ctrl_reversed[1]],
self.anc[self.num_qubits - 2],
)
tof = {}
i = self.num_qubits - 1
for ctrl in lst_ctrl_reversed[2:]:
circuit.rccx(self.anc[i - 1], self.memory[ctrl], self.anc[i - 2])
tof[ctrl] = [i - 1, i - 2]
i -= 1
circuit.cu(alpha, beta, phi, 0, self.anc[i - 1], self.aux[0])
for ctrl in lst_ctrl[:-2]:
circuit.rccx(self.anc[tof[ctrl][0]], self.memory[ctrl], self.anc[tof[ctrl][1]])
circuit.rccx(
self.memory[lst_ctrl[-1]], self.memory[lst_ctrl[-2]], self.anc[self.num_qubits - 2]
)
def _load_superposition(self, circuit, feature, control, memory):
"""
Load pattern in superposition
"""
theta, phi, lam = _compute_matrix_angles(feature, self.norm)
if len(control) == 0:
circuit.u(theta, phi, lam, self.aux[0])
elif len(control) == 1:
circuit.cu(theta, phi, lam, 0, memory[control[0]], self.aux[0])
else:
if self.with_aux:
self._mcuvchain(circuit, theta, phi, lam)
else:
gate = UGate(theta, phi, lam)
if self.mcg_method == 'qiskit':
circuit.append(gate.control(len(control)), memory[control] + [self.aux[0]])
elif self.mcg_method == 'barenco':
gate_op = Operator(gate).data
LdMcSpecialUnitary.ldmcsu(circuit, gate_op, memory[control], [self.aux[0]])
else:
gate_op = Operator(gate).data
Mcg.mcg(circuit, gate_op, memory[control], [self.aux[0]])
self.norm = self.norm - np.absolute(np.power(feature, 2))
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
if qubits is None:
q_circuit.append(
CvoqramInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(CvoqramInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" https://arxiv.org/abs/2011.07977 """
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.util import _compute_matrix_angles
from qclib.gates.initialize_sparse import InitializeSparse
# pylint: disable=maybe-no-member
class CvqramInitialize(InitializeSparse):
"""
Initializing the Amplitude Distribution of a Quantum State
https://arxiv.org/abs/2011.07977
This class implements a sparse state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
self._name = "cvqram"
self._get_num_qubits(params)
self.norm = 1
default_mode = "v-chain"
if opt_params is None:
self.mode = default_mode
else:
if opt_params.get("mode") is None:
self.mode = default_mode
else:
self.mode = opt_params.get("mode")
if label is None:
label = "CVSP"
super().__init__(self._name, self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
memory = QuantumRegister(self.num_qubits, name="m")
if self.mode == "mct":
aux = None
qr_u1 = QuantumRegister(2, name="u1")
circuit = QuantumCircuit(qr_u1, memory)
circuit.x(qr_u1[1])
elif self.mode == "v-chain":
aux = QuantumRegister(self.num_qubits - 1, name="anc")
qr_u1 = QuantumRegister(1, name="u1")
qr_u2 = QuantumRegister(1, name="u2")
circuit = QuantumCircuit(
qr_u1,
qr_u2,
memory,
aux,
)
circuit.x(qr_u2[0])
self.norm = 1
control = range(self.num_qubits)
for binary_string, amplitude in self.params:
self._load_binary(circuit, binary_string, self.mode, memory, qr_u1)
self._load_superposition(
circuit, amplitude, self.mode, control, memory, qr_u1, qr_u2, aux
)
self._load_binary(circuit, binary_string, self.mode, memory, qr_u1)
return circuit
@staticmethod
def _load_binary(circuit, binary_string, mode, memory, qr_u1):
for bit_index, bit in enumerate(binary_string):
if bit == "1":
if mode == "v-chain":
circuit.cx(qr_u1[0], memory[bit_index])
elif mode == "mct":
circuit.cx(qr_u1[1], memory[bit_index])
elif bit == "0":
circuit.x(memory[bit_index])
def _load_superposition(
self, circuit, feature, mode, control, memory, qr_u1, qr_u2, aux
):
"""
Load pattern in superposition
"""
alpha, beta, phi = _compute_matrix_angles(feature, self.norm)
if mode == "mct":
circuit.mct(memory, qr_u1[0])
circuit.cu3(alpha, beta, phi, qr_u1[0], qr_u1[1])
circuit.mct(memory, qr_u1[0])
elif mode == "v-chain":
circuit.rccx(memory[control[0]], memory[control[1]], aux[0])
for j in range(2, len(control)):
circuit.rccx(memory[control[j]], aux[j - 2], aux[j - 1])
circuit.cx(aux[len(control) - 2], qr_u1[0])
circuit.cu3(alpha, beta, phi, qr_u1[0], qr_u2[0])
circuit.cx(aux[len(control) - 2], qr_u1[0])
for j in reversed(range(2, len(control))):
circuit.rccx(memory[control[j]], aux[j - 2], aux[j - 1])
circuit.rccx(memory[control[0]], memory[control[1]], aux[0])
self.norm = self.norm - np.absolute(np.power(feature, 2))
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
if qubits is None:
q_circuit.append(
CvqramInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(CvqramInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Divide-and-conquer state preparation
https://doi.org/10.1038/s41598-021-85474-1
https://arxiv.org/abs/2108.10182
"""
from math import log2
from qiskit import QuantumCircuit
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.state_tree_preparation import (
Amplitude,
state_decomposition,
)
from qclib.state_preparation.util.angle_tree_preparation import create_angles_tree
from qclib.state_preparation.util.tree_register import add_register
from qclib.state_preparation.util.tree_walk import bottom_up
class DcspInitialize(Initialize):
"""
A divide-and-conquer algorithm for quantum state preparation
https://doi.org/10.1038/s41598-021-85474-1
This class implements a state preparation gate.
"""
def __init__(self, params, label=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
"""
self._name = "dcsp"
self._get_num_qubits(params)
if label is None:
self._label = "DCSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
n_qubits = int(log2(len(self.params)))
data = [Amplitude(i, a) for i, a in enumerate(self.params)]
state_tree = state_decomposition(n_qubits, data)
angle_tree = create_angles_tree(state_tree)
circuit = QuantumCircuit()
add_register(circuit, angle_tree, n_qubits - 1)
bottom_up(angle_tree, circuit, n_qubits)
return circuit
def _get_num_qubits(self, params):
if not log2(len(params)).is_integer():
Exception("The number of amplitudes is not a power of 2")
self.num_qubits = len(params) - 1
@staticmethod
def initialize(q_circuit, state, qubits=None):
"""
Appends a DcspInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(DcspInitialize(state), q_circuit.qubits)
else:
q_circuit.append(DcspInitialize(state), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
https://arxiv.org/abs/quant-ph/9807054
"""
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.initialize_sparse import InitializeSparse
# pylint: disable=maybe-no-member
class FnPointsInitialize(InitializeSparse):
"""
Initializing the Amplitude Distribution of a Quantum State
https://arxiv.org/abs/quant-ph/9807054
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""State preparation using Ventura and Martinez algorithm quant-ph/9807054
Algorithm that requires a polynomial number of elementary operations for
initializing a quantum system to represent only the m known points of a
function f (m = len(state)).
The result is a quantum superposition with m nonzero coefficients -- the
creation of which is a nontrivial task compared to creating a superposition
of all basis states.
The amplitudes of modulus "1/sqrt(m)" will be "2 pi / N" radians apart from
each other on the complex plane.
Binary output function case:
f:z->s with z \\in {0,1}^n and s \\in {0, 1}
General case:
f:z->s with z \\in {0,1}^n and s \\in {0, 1, ..., N-1}
For instance, to initialize the state
1/sqrt(3)|01> + 1/sqrt(3)*e^(1*i*2pi/N)|10> + 1/sqrt(3)*e^(2*i*2pi/N)c|11>
$ state = {1: 0, 2: 1, 3: 2}
$ circuit = initialize(state, n=2, N=3)
Parameters
----------
params: dict of {int:float}
A unit vector representing a quantum state.
Keys are function binary input values and values are function output values.
opt_params: Dictionary
n_output_values: int
Number of possible output values N (Ex.: n_output_values=2 for a binary
function). Default value is the max value in ``params`` minus 1.
"""
self._name = "fn-points"
self._get_num_qubits(params)
default_n_output_values = max(params.values()) - 1
if opt_params is None:
self.n_output_values = default_n_output_values
else:
if opt_params.get("n_output_values") is None:
self.n_output_values = default_n_output_values
else:
self.n_output_values = opt_params.get("n_output_values")
self.n_output_values = max(self.n_output_values, default_n_output_values)
if label is None:
self._label = "FNSP"
super().__init__(self._name, self.num_qubits, params.items(), label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
reg_x = QuantumRegister(self.num_qubits, "x")
reg_g = QuantumRegister(self.num_qubits - 1, "g")
reg_c = QuantumRegister(2, "c")
circuit = QuantumCircuit(reg_x, reg_g, reg_c)
reg_x = reg_x[::-1] # qiskit reverse (qiskit little-endian)
bits_z0 = [int(k) for k in f"{0:0{self.num_qubits}b}"]
for idx_p, (input_z, output_s) in list(enumerate(self.params))[::-1]:
bits_z = [int(k) for k in input_z]
circuit.x(reg_c[1])
for j, k in enumerate(bits_z):
if bits_z0[j] != k:
circuit.cx(reg_c[1], reg_x[j])
bits_z0 = bits_z
circuit.cx(reg_c[1], reg_c[0])
circuit.x(reg_c[1])
self._apply_smatrix(
circuit, idx_p, output_s.real, reg_c
)
self._flipflop01(bits_z, circuit, reg_x)
circuit.ccx(reg_x[0], reg_x[1], reg_g[0])
self._flipflop01(bits_z, circuit, reg_x)
for k in range(2, self.num_qubits):
if bits_z[k] == 0:
circuit.x(reg_x[k])
circuit.ccx(reg_x[k], reg_g[k - 2], reg_g[k - 1])
if bits_z[k] == 0:
circuit.x(reg_x[k])
circuit.cx(reg_g[self.num_qubits - 2], reg_c[0])
for k in range(self.num_qubits - 1, 1, -1):
if bits_z[k] == 0:
circuit.x(reg_x[k])
circuit.ccx(reg_x[k], reg_g[k - 2], reg_g[k - 1])
if bits_z[k] == 0:
circuit.x(reg_x[k])
self._flipflop01(bits_z, circuit, reg_x)
circuit.ccx(reg_x[0], reg_x[1], reg_g[0])
self._flipflop01(bits_z, circuit, reg_x)
circuit.x(reg_c[1])
return circuit
def _apply_smatrix(self, circuit, idx_p, output_s, reg_c):
theta = -2 * np.arccos(np.sqrt(idx_p / (idx_p + 1)))
# This sign is here for the smaller values of "s" to be represented by
# negative amplitudes and the larger ones by positive amplitudes.
# In the paper this negative sign is missing. Without it the matrix S
# is not unitary.
lamb = -output_s * 2 * np.pi / self.n_output_values
phi = -lamb
circuit.cu(theta, phi, lamb, 0, reg_c[0], reg_c[1])
@staticmethod
def _flipflop01(bits_z, circuit, reg_x):
if bits_z[0] == 0:
circuit.x(reg_x[0])
if bits_z[1] == 0:
circuit.x(reg_x[1])
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
if qubits is None:
q_circuit.append(
FnPointsInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(FnPointsInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# 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-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
# pylint: disable=unused-argument
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.compiler import transpile
from qiskit.quantum_info.random import random_unitary
class IsometryTranspileBench:
params = ([0, 1, 2, 3], [3, 4, 5, 6])
param_names = ["number of input qubits", "number of output qubits"]
def setup(self, m, n):
q = QuantumRegister(n)
qc = QuantumCircuit(q)
if not hasattr(qc, "iso"):
raise NotImplementedError
iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m]
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
qc.iso(iso, q[:m], q[m:])
self.circuit = qc
def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused):
coupling = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
self.circuit,
basis_gates=["u1", "u3", "u2", "cx"],
coupling_map=coupling,
seed_transpiler=0,
)
counts = circuit.count_ops()
cnot_count = counts.get("cx", 0)
return cnot_count
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Implements the state preparation
defined at https://arxiv.org/abs/1003.5760.
"""
import numpy as np
from qiskit import QuantumCircuit
from qclib.unitary import unitary as decompose_unitary, cnot_count as cnots_unitary
from qclib.isometry import decompose as decompose_isometry, cnot_count as cnots_isometry
from qclib.gates.initialize import Initialize
from qclib.entanglement import schmidt_decomposition, _to_qubits
from .topdown import TopDownInitialize
# pylint: disable=maybe-no-member
class LowRankInitialize(Initialize):
"""
Approximated quantum-state preparation with entanglement dependent complexity
https://arxiv.org/abs/2111.03132
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: {'lr': low_rank,
'iso_scheme': isometry_scheme,
'unitary_scheme': unitary_scheme,
'partition': partition}
low_rank: int
``state`` low-rank approximation (1 <= ``low_rank`` < 2**(n_qubits//2)).
If ``low_rank`` is not in the valid range, it will be ignored.
This parameter limits the rank of the Schmidt decomposition. If the Schmidt rank
of the state decomposition is greater than ``low_rank``, a low-rank
approximation is applied.
iso_scheme: string
Scheme used to decompose isometries.
Possible values are ``'knill'`` and ``'ccd'`` (column-by-column decomposition).
Default is ``isometry_scheme='ccd'``.
unitary_scheme: string
Scheme used to decompose unitaries.
Possible values are ``'csd'`` (cosine-sine decomposition) and ``'qsd'`` (quantum
Shannon decomposition).
Default is ``unitary_scheme='qsd'``.
partition: list of int
Set of qubit indices that represent a part of the bipartition.
The other partition will be the relative complement of the full set of qubits
with respect to the set ``partition``.
The valid range for indexes is ``0 <= index < n_qubits``. The number of indexes
in the partition must be greater than or equal to ``1`` and less than or equal
to ``n_qubits//2`` (``n_qubits//2+1`` if ``n_qubits`` is odd).
Default is ``partition=list(range(n_qubits//2 + odd))``.
svd: string
Function to compute the SVD, acceptable values are 'auto' (default), 'regular',
and 'randomized'. 'auto' sets `svd='randomized'` for `n_qubits>=14 and rank==1`.
"""
self._name = "low_rank"
self._get_num_qubits(params)
if opt_params is None:
self.isometry_scheme = "ccd"
self.unitary_scheme = "qsd"
self.low_rank = 0
self.partition = None
self.svd = "auto"
else:
self.low_rank = 0 if opt_params.get("lr") is None else opt_params.get("lr")
self.partition = opt_params.get("partition")
if opt_params.get("iso_scheme") is None:
self.isometry_scheme = "ccd"
else:
self.isometry_scheme = opt_params.get("iso_scheme")
if opt_params.get("unitary_scheme") is None:
self.unitary_scheme = "qsd"
else:
self.unitary_scheme = opt_params.get("unitary_scheme")
if opt_params.get("svd") is None:
self.svd = "auto"
else:
self.svd = opt_params.get("svd")
if label is None:
label = "LRSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
if self.num_qubits < 2:
return TopDownInitialize(self.params).definition
circuit, reg_a, reg_b = self._create_quantum_circuit()
# Schmidt decomposition
rank, svd_u, singular_values, svd_v = schmidt_decomposition(
self.params, reg_a, rank=self.low_rank, svd=self.svd
)
# Schmidt measure of entanglement
e_bits = _to_qubits(rank)
# Phase 1. Encodes the singular values.
if e_bits > 0:
reg_sv = reg_b[:e_bits]
singular_values = singular_values / np.linalg.norm(singular_values)
self._encode(singular_values.reshape(rank, 1), circuit, reg_sv)
# Phase 2. Entangles only the necessary qubits, according to rank.
for j in range(e_bits):
circuit.cx(reg_b[j], reg_a[j])
# Phase 3 and 4 encode gates U and V.T
self._encode(svd_u, circuit, reg_b)
self._encode(svd_v.T, circuit, reg_a)
return circuit.reverse_bits()
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a LowRankInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
LowRankInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(LowRankInitialize(state, opt_params=opt_params), qubits)
def _encode(self, data, circuit, reg):
"""
Encodes data using the most appropriate method.
"""
if data.shape[1] == 1:
# state preparation
gate_u = LowRankInitialize(data[:, 0], opt_params={
"iso_scheme": self.isometry_scheme,
"unitary_scheme": self.unitary_scheme,
"svd": self.svd
})
elif data.shape[0] // 2 == data.shape[1]:
# isometry 2^(n-1) to 2^n.
gate_u = decompose_isometry(data, scheme="csd")
elif data.shape[0] > data.shape[1]:
gate_u = decompose_isometry(data, scheme=self.isometry_scheme)
else:
gate_u = decompose_unitary(data, decomposition=self.unitary_scheme)
# Apply gate U to the register reg
circuit.compose(gate_u, reg, inplace=True)
def _create_quantum_circuit(self):
if self.partition is None:
self.partition = _default_partition(self.num_qubits)
complement = sorted(set(range(self.num_qubits)).difference(set(self.partition)))
circuit = QuantumCircuit(self.num_qubits)
return circuit, self.partition[::-1], complement[::-1]
def _default_partition(n_qubits):
odd = n_qubits % 2
return list(range(n_qubits // 2 + odd))
def cnot_count(
state_vector,
low_rank=0,
isometry_scheme="ccd",
unitary_scheme="qsd",
partition=None,
method = "estimate",
svd="auto"
):
"""
Estimate the number of CNOTs to build the state preparation circuit.
"""
n_qubits = _to_qubits(len(state_vector))
if n_qubits < 2:
return 0
if partition is None:
partition = _default_partition(n_qubits)
cnots = 0
rank, svd_u, singular_values, svd_v = schmidt_decomposition(
state_vector,
partition,
rank=low_rank,
svd=svd
)
# Schmidt measure of entanglement
ebits = _to_qubits(rank)
# Phase 1.
if ebits > 0:
singular_values = singular_values / np.linalg.norm(singular_values)
cnots += _cnots(
singular_values.reshape(rank, 1), isometry_scheme, unitary_scheme, method, svd
)
# Phase 2.
cnots += ebits
# Phases 3 and 4.
cnots += _cnots(svd_u, isometry_scheme, unitary_scheme, method, svd)
cnots += _cnots(svd_v.T, isometry_scheme, unitary_scheme, method, svd)
return cnots
def _cnots(data, iso_scheme="ccd", uni_scheme="qsd", method="estimate", svd="auto"):
if data.shape[1] == 1:
return cnot_count(
data[:, 0],
isometry_scheme=iso_scheme,
unitary_scheme=uni_scheme,
method=method,
svd=svd
)
if data.shape[0] // 2 == data.shape[1]:
return cnots_isometry(data, scheme="csd", method=method)
if data.shape[0] > data.shape[1]:
return cnots_isometry(data, scheme=iso_scheme, method=method)
return cnots_unitary(data, decomposition=uni_scheme, method=method)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
An Efficient Algorithm for Sparse Quantum State Preparation
https://ieeexplore.ieee.org/document/9586240
"""
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import UGate
from qclib.gates.ldmcu import Ldmcu
from qclib.gates.initialize_sparse import InitializeSparse
class MergeInitialize(InitializeSparse):
"""
An Efficient Algorithm for Sparse Quantum State Preparation
https://ieeexplore.ieee.org/document/9586240
"""
def __init__(self, params, label=None):
"""
Classical algorithm that creates a quantum circuit C that loads
a sparse quantum state, applying a sequence of operations maping
the desired state |sigma> to |0>. And then inverting C to obtain
the mapping of |0> to the desired state |sigma>.
Args:
params: A dictionary with the non-zero amplitudes corresponding to each state in
format { '000': <value>, ... , '111': <value> }
Returns:
Creates a quantum gate that maps |0> to the desired state |params>
"""
self._name = "merge"
if label is None:
label = "MERGESP"
# Parameters need to be validated first by superclass
self._get_num_qubits(params)
super().__init__(self._name, self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
state_dict = dict(self.params)
b_strings = list(state_dict.keys())
n_qubits = len(b_strings[0])
quantum_register = QuantumRegister(n_qubits)
quantum_circuit = QuantumCircuit(quantum_register)
while len(b_strings) > 1:
bitstr1, bitstr2, dif, dif_qubits = self._select_strings(state_dict)
bitstr1, bitstr2, state_dict, quantum_circuit = self._preprocess_states(
bitstr1, bitstr2, dif, dif_qubits, state_dict, quantum_circuit
)
state_dict, quantum_circuit = self._merge(
state_dict, quantum_circuit, bitstr1, bitstr2, dif_qubits, dif
)
b_strings = list(state_dict.keys())
b_string = b_strings.pop()
for (bit_idx, bit) in enumerate(b_string):
if bit == "1":
quantum_circuit.x(bit_idx)
return quantum_circuit.reverse_ops()
@staticmethod
def initialize(q_circuit, state, qubits=None):
if qubits is None:
q_circuit.append(MergeInitialize(state), q_circuit.qubits)
else:
q_circuit.append(MergeInitialize(state), qubits)
@staticmethod
def _maximizing_difference_bit_search(b_strings, dif_qubits):
"""
Splits the set of bit strings into two (t_0 and t_1), by setting
t_0 as the set of bit_strings with 0 in the bit_index position, and
t_1 as the set of bit_strings with 1 in the bit_index position.
Searching for the bit_index not in dif_qubits that maximizes the difference
between the size of the nonempty t_0 and t_1.
Args:
b_string: A list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: A list of previous qubits found to maximize the difference
Returns:
bit_index: The qubit index that maximizes abs(len(t_0)-len(t_1))
t_0: List of binary strings with 0 on the bit_index qubit
t_1: List of binary strings with 1 on the bit_index qubit
"""
t_0 = []
t_1 = []
bit_index = 0
set_difference = -1
bit_search_space = list(set(range(len(b_strings[0]))) - set(dif_qubits))
for bit in bit_search_space:
temp_t0 = [x for x in b_strings if x[bit] == "0"]
temp_t1 = [x for x in b_strings if x[bit] == "1"]
if temp_t0 and temp_t1:
temp_difference = np.abs(len(temp_t0) - len(temp_t1))
if temp_difference > set_difference:
t_0 = temp_t0
t_1 = temp_t1
bit_index = bit
set_difference = temp_difference
return bit_index, t_0, t_1
@staticmethod
def _build_bit_string_set(b_strings, dif_qubits, dif_values):
"""
Creates a new set of bit strings from b_strings, where the bits
in the indexes in dif_qubits match the values in dif_values.
Args:
b_strings: list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: list of integers with the bit indexes
dif_values: list of integers values containing the values each bit
with index in dif_qubits shoud have
Returns:
A new list of bit_strings, with matching values in dif_values
on indexes dif_qubits
"""
bit_string_set = []
for b_string in b_strings:
if [b_string[i] for i in dif_qubits] == dif_values:
bit_string_set.append(b_string)
return bit_string_set
def _bit_string_search(self, b_strings, dif_qubits, dif_values):
"""
Searches for the bit strings with unique qubit values in `dif_values`
on indexes `dif_qubits`.
Args:
b_strings: List of binary strings where the search is to be performed
e.g.: ['000', '010', '101', '111']
dif_qubits: List of indices on a binary string of size N e.g.: [1, 3, 5]
dif_values: List of values each qubit must have on indexes stored in dif_qubits [0, 1, 1]
Returns:
b_strings: One size list with the string found, to have values dif_values on indexes
dif_qubits
dif_qubits: Updated list with new indexes
dif_values: Updated list with new values
"""
temp_strings = b_strings
while len(temp_strings) > 1:
bit, t_0, t_1 = self._maximizing_difference_bit_search(
temp_strings, dif_qubits
)
dif_qubits.append(bit)
if len(t_0) < len(t_1):
dif_values.append("0")
temp_strings = t_0
else:
dif_values.append("1")
temp_strings = t_1
return temp_strings, dif_qubits, dif_values
def _select_strings(self, state_dict):
"""
Searches for the states described by the bit strings bitstr1 and bitstr2 to be merged
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
Returns:
bitstr1: First binary string
bitstr2: Second binary string
dif_qubit: Qubit index to be used as target for the merging operation
dif_qubits: List of qubit indexes where bitstr1 and bitstr2 must be equal, because the
correspondig qubits of those indexes are to be used as control for the
merging operation
"""
# Initialization
dif_qubits = []
dif_values = []
b_strings1 = b_strings2 = list(state_dict.keys())
# Searching for bitstr1
(b_strings1, dif_qubits, dif_values) = self._bit_string_search(
b_strings1, dif_qubits, dif_values
)
dif_qubit = dif_qubits.pop()
dif_values.pop()
bitstr1 = b_strings1[0]
# Searching for bitstr2
b_strings2.remove(bitstr1)
b_strings1 = self._build_bit_string_set(b_strings2, dif_qubits, dif_values)
(b_strings1, dif_qubits, dif_values) = self._bit_string_search(
b_strings1, dif_qubits, dif_values
)
bitstr2 = b_strings1[0]
return bitstr1, bitstr2, dif_qubit, dif_qubits
@staticmethod
def _apply_operation_to_bit_string(b_string, operation, qubit_indexes):
"""
Applies changes on binary strings according to the operation
Args:
b_string: Binary string '00110'
operation: Operation to be applied to the string
qubit_indexes: Indexes of the qubits on the binary strings where the operations are to
be applied
Returns:
Updated binary string
"""
assert operation in ["x", "cx"]
if operation == "x":
compute = _compute_op_x
else:
compute = _compute_op_cx
return compute(b_string, qubit_indexes)
@staticmethod
def _update_state_dict_according_to_operation(
state_dict, operation, qubit_indexes, merge_strings=None
):
"""
Updates the keys of the state_dict according to the operation being applied to the circuit
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
operation: Operation to be applied to the states, it must be ['x', 'cx', 'merge']
qubit_indexes: Indexes of the qubits on the binary strings where the operations are to
be applied
merge_strings: Binary strings associated ot the states on the quantum processor
to be merge e.g.:['01001', '10110']
Returns:
A state_dict with the updated states
"""
assert operation in ["x", "cx", "merge"]
state_list = list(state_dict.items())
new_state_dict = {}
if operation == "merge":
assert merge_strings is not None
# Computes the norm of bitstr1 and bitstr2
new_state_dict = state_dict.copy()
norm = np.linalg.norm(
[new_state_dict[merge_strings[0]], new_state_dict[merge_strings[1]]]
)
new_state_dict.pop(merge_strings[1], None)
new_state_dict[merge_strings[0]] = norm
else:
for (bit_string, value) in state_list:
temp_bstring = MergeInitialize._apply_operation_to_bit_string(
bit_string, operation, qubit_indexes
)
new_state_dict[temp_bstring] = value
return new_state_dict
@staticmethod
def _equalize_bit_string_states(
bitstr1, bitstr2, dif, state_dict, quantum_circuit
):
"""
Applies operations to the states represented by bit strings bitstr1 and bitstr2 equalizing
them at every qubit except the one in the dif index. And alters the bit strings and
state_dict accordingly.
Args:
bitstr1: First bit string
bitstr2: Second bit string
dif: index where both bitstr1 and bitstr2 must be different
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
Returns:
Updated bitstr1, bitstr2, state_dict and quantum_circuit
"""
b_index_list = list(range(len(bitstr1)))
b_index_list.remove(dif)
for b_index in b_index_list:
if bitstr1[b_index] != bitstr2[b_index]:
quantum_circuit.cx(dif, b_index)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(
bitstr1, "cx", [dif, b_index]
)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(
bitstr2, "cx", [dif, b_index]
)
state_dict = MergeInitialize._update_state_dict_according_to_operation(
state_dict, "cx", [dif, b_index]
)
return bitstr1, bitstr2, state_dict, quantum_circuit
@staticmethod
def _apply_not_gates_to_qubit_index_list(
bitstr1, bitstr2, dif_qubits, state_dict, quantum_circuit
):
"""
Applies quantum not gate at the qubit at a given index, where the state represented by the
bit string bitstr2 is different than '1' at index in diff_qubits.
Args:
bitstr1: First bit string
bitstr2: Second bit string
dif_qubits: indexes where both bitstr1 and bitstr2 are equal
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
Returns:
Updated bitstr1, bitstr2, state_dict and quantum_circuit
"""
for b_index in dif_qubits:
if bitstr2[b_index] != "1":
quantum_circuit.x(b_index)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(bitstr1, "x", b_index)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(bitstr2, "x", b_index)
state_dict = MergeInitialize._update_state_dict_according_to_operation(
state_dict, "x", b_index
)
return bitstr1, bitstr2, state_dict, quantum_circuit
def _preprocess_states(
self, bitstr1, bitstr2, dif, dif_qubits, state_dict, quantum_circuit
):
"""
Apply the operations on the basis states to prepare for merging bitstr1 and bitstr2.
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
bitstr1: First binary string to be merged
bitstr2: Second binary string to be merged
dif_qubits: List of qubit indexes on the binary strings
dif: Target qubit index where the merge operation is to be applied
quantum_circuit: Qiskit's QuantumCircuit object where the operations are to be called
Returns:
state_dict: Updated state dict
bitstr1: First updated binary string to be merged
bitstr2: Second updated binary string to be merged
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
"""
if bitstr1[dif] != "1":
quantum_circuit.x(dif)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(bitstr1, "x", dif)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(bitstr2, "x", dif)
state_dict = self._update_state_dict_according_to_operation(
state_dict, "x", dif
)
(
bitstr1,
bitstr2,
state_dict,
quantum_circuit,
) = self._equalize_bit_string_states(
bitstr1, bitstr2, dif, state_dict, quantum_circuit
)
(
bitstr1,
bitstr2,
state_dict,
quantum_circuit,
) = self._apply_not_gates_to_qubit_index_list(
bitstr1, bitstr2, dif_qubits, state_dict, quantum_circuit
)
return bitstr1, bitstr2, state_dict, quantum_circuit
@staticmethod
def _compute_angles(amplitude_1, amplitude_2):
"""
Computes the angles for the adjoint of the merge matrix M
that is going to map the dif qubit to zero e.g.:
M(a|0> + b|1>) -> |1>
Args:
amplitude_1: A complex/real value, associated with the string with
1 on the dif qubit
amplitude_2: A complex/real value, associated with the string with
0 on the dif qubit
Returns:
The angles theta, lambda and phi for the U operator
"""
norm = np.linalg.norm([amplitude_1, amplitude_2])
phi = 0
lamb = 0
# there is no minus on the theta because the intetion is to compute the inverse
if isinstance(amplitude_1, complex) or isinstance(amplitude_2, complex):
amplitude_1 = (
complex(amplitude_1)
if not isinstance(amplitude_1, complex)
else amplitude_1
)
amplitude_2 = (
complex(amplitude_2)
if not isinstance(amplitude_2, complex)
else amplitude_2
)
theta = -2 * np.arcsin(np.abs(amplitude_2 / norm))
lamb = np.log(amplitude_2 / norm).imag
phi = np.log(amplitude_1 / norm).imag - lamb
else:
theta = -2 * np.arcsin(amplitude_2 / norm)
return theta, phi, lamb
def _merge(self, state_dict, quantum_circuit, bitstr1, bitstr2, dif_qubits, dif):
theta, phi, lamb = self._compute_angles(
state_dict[bitstr1], state_dict[bitstr2]
)
# Applying merge operation
merge_gate = UGate(theta, phi, lamb, label="U")
if not dif_qubits:
quantum_circuit.append(merge_gate, dif_qubits + [dif], [])
else:
gate_definition = UGate(theta, phi, lamb, label="U").to_matrix()
Ldmcu.ldmcu(quantum_circuit, gate_definition, dif_qubits, dif)
state_dict = self._update_state_dict_according_to_operation(
state_dict, "merge", None, merge_strings=[bitstr1, bitstr2]
)
return state_dict, quantum_circuit
def _compute_op_cx(xlist, idx):
return (
f'{xlist[: idx[1]]}{(not int(xlist[idx[1]])) * 1}{xlist[idx[1] + 1:]}'
if xlist[idx[0]] == "1"
else xlist
)
def _compute_op_x(xlist, idx):
return (
xlist[:idx] + "1" + xlist[idx + 1:]
if xlist[idx] == "0"
else xlist[0:idx] + "0" + xlist[idx + 1:]
)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Initializes a mixed quantum state.
"""
from math import log2, ceil, isclose
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.initialize import Initialize
from qclib.gates.initialize_mixed import InitializeMixed
from qclib.gates.initialize_sparse import InitializeSparse
from qclib.state_preparation import LowRankInitialize
# pylint: disable=maybe-no-member
class MixedInitialize(InitializeMixed):
"""
This class implements a mixed state preparation gate.
"""
def __init__(
self,
params,
initializer=LowRankInitialize,
opt_params=None,
probabilities=None,
label=None,
reset=True,
classical = True
):
"""
Parameters
----------
params: list of list of complex
A list of unit vectors, each representing a quantum state.
Values are amplitudes.
initializer: Initialize or InitializeSparse
Type of the class that will be applied to prepare pure states.
Default is ``LowRankInitialize``.
opt_params: dictionary
Optional parameters of the class of type ``initializer``.
reset: bool
Indicates whether the auxiliary qubits should be reset or not.
Default is ``True``.
classical: bool
Indicates whether the purification is done classically or
in-circuit (quantically). Default is ``True``.
"""
if (
not issubclass(initializer, Initialize) and
not issubclass(initializer, InitializeSparse)
):
raise TypeError("The value of initializer should be Initialize or InitializeSparse.")
if probabilities is None:
probabilities = [1/len(params)] * len(params)
elif any(i < 0.0 for i in probabilities):
raise ValueError("All probabilities must greater than or equal to 0.")
elif any(i > 1.0 for i in probabilities):
raise ValueError("All probabilities must less than or equal to 1.")
elif not isclose(sum(probabilities), 1.0):
raise ValueError("The sum of the probabilities must be 1.0.")
self._name = "mixed"
self._get_num_qubits(params)
self._initializer = initializer
self._reset = reset
self._opt_params = opt_params
self._probabilities = probabilities
self._classical = classical
self._num_ctrl_qubits = int(ceil(log2(len(params))))
self._num_data_qubits = initializer(params[0]).num_qubits
self._list_params = params
if label is None:
label = "Mixed"
super().__init__(self._name, self.num_qubits, np.array(params).reshape(-1), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
purified_circuit = QuantumCircuit(self.num_qubits)
if self._classical:
# Calculates the pure state classically.
pure_state = np.zeros(2**(self._num_qubits), dtype=complex)
for index, (state_vector, prob) in enumerate(
zip(self._list_params, self._probabilities)
):
basis = np.zeros(2**self._num_ctrl_qubits)
basis[index] = 1
pure_state += np.kron(np.sqrt(prob) * state_vector, basis)
purified_circuit = self._initializer(
pure_state,
opt_params=self._opt_params
).definition
else:
# Calculates the pure state quantically.
aux_state = np.concatenate((
np.sqrt(self._probabilities),
[0] * (2**(self._num_ctrl_qubits) - len(self._probabilities))
))
sub_circuit = self._initializer(
aux_state,
opt_params=self._opt_params
).definition
sub_circuit.name = 'aux. space'
purified_circuit.append(sub_circuit, range(self._num_ctrl_qubits))
for index, state in enumerate(self._list_params):
sub_circuit = self._initializer(
state,
opt_params=self._opt_params
).definition
sub_circuit.name = f'state {index}'
sub_circuit = sub_circuit.control(
num_ctrl_qubits=self._num_ctrl_qubits,
ctrl_state = f"{index:0{self._num_ctrl_qubits}b}"
)
purified_circuit.compose(sub_circuit, purified_circuit.qubits, inplace=True)
purified_circuit.name = 'purified state'
circuit = QuantumCircuit()
circuit.add_register(QuantumRegister(self._num_ctrl_qubits, 'aux'))
circuit.add_register(QuantumRegister(self._num_data_qubits, 'rho'))
circuit.append(purified_circuit, circuit.qubits)
if self._reset:
circuit.reset(range(self._num_ctrl_qubits))
return circuit
@staticmethod
def initialize(q_circuit, ensemble, qubits=None, opt_params=None, probabilities=None):
"""
Appends a MixedInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
MixedInitialize(
ensemble,
opt_params=opt_params,
probabilities=probabilities
)
, q_circuit.qubits
)
else:
q_circuit.append(
MixedInitialize(
ensemble,
opt_params=opt_params,
probabilities=probabilities
)
, qubits
)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" sparse state preparation """
import numpy as np
import qiskit
from qiskit import QuantumCircuit
from qclib.gates.initialize_sparse import InitializeSparse
from .lowrank import LowRankInitialize
# pylint: disable=maybe-no-member
class PivotInitialize(InitializeSparse):
"""Pivot State Preparation arXiv:2006.00016"""
def __init__(self, params, label=None, opt_params=None):
self._get_num_qubits(params)
default_aux = False
if opt_params is None:
self.aux = default_aux
else:
if opt_params.get("aux") is None:
self.aux = default_aux
else:
self.aux = opt_params.get("aux")
self.non_zero = len(params)
self.register = qiskit.QuantumRegister(self.num_qubits, name="q")
self.index_differ = None
self.ctrl_state = None
if label is None:
self.label = "PivotSP"
super().__init__("PivotInitialize", self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
target_size = np.log2(self.non_zero)
target_size = np.ceil(target_size)
target_size = int(target_size)
if self.aux:
anc, n_anci, pivot_circuit = self._circuit_with_ancilla(target_size)
else:
pivot_circuit = qiskit.QuantumCircuit(self.register)
next_state = self.params.copy()
index_nonzero = self._get_index_nz(self.num_qubits - target_size, next_state)
while index_nonzero is not None:
index_zero = self._get_index_zero(self.non_zero, next_state)
circ, next_state = self._pivoting(
index_nonzero, target_size, index_zero, next_state
)
pivot_circuit.compose(circ, pivot_circuit.qubits, inplace=True)
index_nonzero = self._get_index_nz(
self.num_qubits - target_size, next_state
)
dense_state = np.zeros(2 ** target_size, dtype=complex)
for key, value in next_state:
dense_state[int(key, 2)] = value
if self.non_zero <= 2:
initialize_circ = qiskit.QuantumCircuit(1)
LowRankInitialize.initialize(initialize_circ, dense_state)
else:
initialize_circ = QuantumCircuit(target_size)
LowRankInitialize.initialize(initialize_circ, dense_state)
if self.aux:
circuit = qiskit.QuantumCircuit(anc, self.register)
nun_aux = n_anci - 1
circuit.compose(
initialize_circ,
circuit.qubits[nun_aux : nun_aux + target_size],
inplace=True,
)
circuit.barrier()
circuit.compose(pivot_circuit.reverse_bits().reverse_ops(), inplace=True)
else:
circuit = qiskit.QuantumCircuit(self.num_qubits)
circuit.compose(initialize_circ, circuit.qubits[:target_size], inplace=True)
circuit.compose(
pivot_circuit.reverse_bits().reverse_ops(), circuit.qubits, inplace=True
)
return circuit
def _circuit_with_ancilla(self, target_size):
remain = list(range(self.num_qubits - target_size, self.num_qubits))
n_anci = len(remain)
anc = qiskit.QuantumRegister(n_anci - 1, name="anc")
pivot_circuit = qiskit.QuantumCircuit(anc, self.register)
return anc, n_anci, pivot_circuit
def _next_state(
self, remain, target_cx, index_zero, next_state
):
tab = {"0": "1", "1": "0"}
new_state = {}
for index, amp in next_state:
if index[self.index_differ] == self.ctrl_state:
n_index = ""
for k, value in enumerate(index):
if k in target_cx:
n_index = n_index + tab[value]
else:
n_index = n_index + value
else:
n_index = index
if n_index[remain[0] :] == index_zero[remain[0] :]:
n_index = (
n_index[:self.index_differ]
+ tab[index[self.index_differ]]
+ n_index[self.index_differ + 1 :]
)
new_state[n_index] = amp
return new_state.items()
def _pivoting(self, index_nonzero, target_size, index_zero, next_state):
"""pivot amplitudes of index_nonzero and self.index_zero"""
target = list(range(self.num_qubits - target_size))
remain = list(range(self.num_qubits - target_size, self.num_qubits))
memory = qiskit.QuantumRegister(self.num_qubits)
anc, circuit = self._initialize_circuit(memory, remain)
self.index_differ = 0
for k in target:
if index_nonzero[k] != index_zero[k]:
self.index_differ = k
break
target_cx = []
self.ctrl_state = index_nonzero[self.index_differ]
for k in target:
if self.index_differ != k and index_nonzero[k] != index_zero[k]:
circuit.cx(self.index_differ, k, ctrl_state=self.ctrl_state)
target_cx.append(k)
for k in remain:
if index_nonzero[k] != index_zero[k]:
circuit.cx(self.index_differ, k, ctrl_state=self.ctrl_state)
target_cx.append(k)
for k in remain:
if index_zero[k] == "0":
circuit.x(k)
if self.aux:
# apply mcx using mode v-chain
self._mcxvchain(circuit, memory, anc, remain, self.index_differ)
else:
circuit.mcx(remain, self.index_differ)
for k in remain:
if index_zero[k] == "0":
circuit.x(k)
next_state = self._next_state(
remain, target_cx, index_zero, next_state
)
return circuit, next_state
def _initialize_circuit(self, memory, remain):
if self.aux:
n_anci = len(remain)
anc = qiskit.QuantumRegister(n_anci - 1, name="anc")
circuit = qiskit.QuantumCircuit(memory, anc)
else:
circuit = qiskit.QuantumCircuit(memory)
anc = None
return anc, circuit
def _get_index_zero(self, non_zero, state):
index_zero = None
for k in range(2**non_zero):
index = f"{k:0{self.num_qubits}b}"
not_exists = sum(1 for v in state if v[0] == index) == 0
if not_exists:
index_zero = index
break
return index_zero
@staticmethod
def _get_index_nz(target_size, next_state):
index_nonzero = None
for index, _ in next_state:
if index[:target_size] != target_size * "0":
index_nonzero = index
break
return index_nonzero
@staticmethod
def _mcxvchain(circuit, memory, anc, lst_ctrl, tgt):
"""multi-controlled x gate with working qubits"""
circuit.rccx(memory[lst_ctrl[0]], memory[lst_ctrl[1]], anc[0])
for j in range(2, len(lst_ctrl)):
circuit.rccx(memory[lst_ctrl[j]], anc[j - 2], anc[j - 1])
circuit.cx(anc[len(lst_ctrl) - 2], tgt)
for j in reversed(range(2, len(lst_ctrl))):
circuit.rccx(memory[lst_ctrl[j]], anc[j - 2], anc[j - 1])
circuit.rccx(memory[lst_ctrl[0]], memory[lst_ctrl[1]], anc[0])
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
if qubits is None:
q_circuit.append(
PivotInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(PivotInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Implements the state preparation
defined at https://arxiv.org/abs/1003.5760.
"""
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qclib.unitary import unitary
from qclib.gates.initialize import Initialize
from .topdown import TopDownInitialize
class SVDInitialize(Initialize):
"""
https://arxiv.org/abs/1003.5760
This class implements a state preparation gate.
"""
def __init__(self, params, label=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
"""
self._name = "svd"
self._get_num_qubits(params)
if label is None:
label = "SVDSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
"""
State preparation using Schmidt decomposition arXiv:1003.5760
"""
state = np.copy(self.params)
n_qubits = self.num_qubits
odd = n_qubits % 2
state.shape = (int(2 ** (n_qubits // 2)), int(2 ** (n_qubits // 2 + odd)))
matrix_u, matrix_d, matrix_v = np.linalg.svd(state)
matrix_d = matrix_d / np.linalg.norm(matrix_d)
reg_a = QuantumRegister(n_qubits // 2 + odd)
reg_b = QuantumRegister(n_qubits // 2)
circuit = QuantumCircuit(reg_a, reg_b)
if len(matrix_d) > 2:
gate = SVDInitialize(matrix_d)
circuit.append(gate, reg_b)
else:
gate = TopDownInitialize(matrix_d)
circuit.append(gate, reg_b)
for k in range(int(n_qubits // 2)):
circuit.cx(reg_b[k], reg_a[k])
# apply gate U to the first register
gate_u = unitary(matrix_u)
circuit.append(gate_u, reg_b)
# apply gate V to the second register
gate_v = unitary(matrix_v.T)
circuit.append(gate_v, reg_a)
return circuit
@staticmethod
def initialize(q_circuit, state, qubits=None):
"""
Appends a SVDInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(SVDInitialize(state), q_circuit.qubits)
else:
q_circuit.append(SVDInitialize(state), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
https://arxiv.org/abs/quant-ph/0407010
https://arxiv.org/abs/2108.10182
"""
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.state_tree_preparation import (
Amplitude,
state_decomposition,
)
from qclib.state_preparation.util.angle_tree_preparation import create_angles_tree
from qclib.state_preparation.util.tree_register import add_register
from qclib.state_preparation.util.tree_walk import top_down
class TopDownInitialize(Initialize):
"""
Top-down state preparation
https://arxiv.org/abs/quant-ph/0407010
https://arxiv.org/abs/2108.10182
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: {'global_phase': global_phase, 'lib': lib}
global_phase: bool
If ``True``, corrects the global phase.
Default value is ``True``.
lib: str
Library to be used.
Default value is ``'qclib'``.
"""
self._name = "top-down"
self._get_num_qubits(params)
if opt_params is None:
self.global_phase = True
self.lib = "qclib"
else:
if opt_params.get("global_phase") is None:
self.global_phase = True
else:
self.global_phase = opt_params.get("global_phase")
if opt_params.get("lib") is None:
self.lib = "qclib"
else:
self.lib = opt_params.get("lib")
if label is None:
label = "TDSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
if self.lib == "qiskit":
reg = QuantumRegister(self.num_qubits)
circuit = QuantumCircuit(reg)
# pylint: disable=maybe-no-member
circuit.initialize(self.params)
return circuit
data = [Amplitude(i, a) for i, a in enumerate(self.params)]
state_tree = state_decomposition(self.num_qubits, data)
angle_tree = create_angles_tree(state_tree)
circuit = QuantumCircuit()
add_register(circuit, angle_tree, 0)
top_down(angle_tree, circuit, 0)
if self.global_phase:
circuit.global_phase += sum(np.angle(self.params)) / len(self.params)
return circuit
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a TopDownInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
TopDownInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(TopDownInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module implements the state preparation proposed by
Bergholm et al (2005) available in:
https://journals.aps.org/pra/abstract/10.1103/PhysRevA.71.052330
"""
import numpy as np
import numpy.linalg as la
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import UCGate
from qclib.gates.initialize import Initialize
class UCGInitialize(Initialize):
"""
Quantum circuits with uniformly controlled one-qubit gates
https://doi.org/10.48550/arXiv.quant-ph/0410066
"""
def __init__(self, params, label=None, opt_params=None):
self._name = "ucg_initialize"
self._get_num_qubits(params)
self.register = QuantumRegister(self.num_qubits)
self.circuit = QuantumCircuit(self.register)
self.target_state = 0 if opt_params is None else opt_params.get("target_state")
self.str_target = bin(self.target_state)[2:].zfill(self.num_qubits)[::-1]
self.preserve = False if opt_params is None else opt_params.get("preserve_previous")
if label is None:
label = "ucg_initialize"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
children = self.params
parent = self._update_parent(children)
tree_level = self.num_qubits
r_gate = self.target_state // 2
while tree_level > 0:
bit_target, ucg = self._disentangle_qubit(children, parent, r_gate, tree_level)
children = self._apply_diagonal(bit_target, parent, ucg)
parent = self._update_parent(children)
# prepare next iteration
r_gate = r_gate // 2
tree_level -= 1
return self.circuit.inverse()
def _disentangle_qubit(self, children: 'list[float]',
parent: 'list[float]',
r_gate: int, tree_level: int):
""" Apply UCGate to disentangle qubit target"""
bit_target = self.str_target[self.num_qubits - tree_level]
mult, mult_controls, target = self._define_mult(children, parent, tree_level)
if self.preserve:
self._preserve_previous(mult, mult_controls, r_gate, target)
ucg = self._apply_ucg(mult, mult_controls, target)
return bit_target, ucg
def _define_mult(self, children: 'list[float]', parent: 'list[float]', tree_level: int):
current_level_mux = self._build_multiplexor(parent,
children,
self.str_target)
mult_controls, target = self._get_ctrl_targ(tree_level)
return current_level_mux, mult_controls, target
def _apply_ucg(self, current_level_mux: 'list[np.ndarray]',
mult_controls: 'list[int]',
target: int):
""" Creates and applies multiplexer """
ucg = UCGate(current_level_mux, up_to_diagonal=True)
if len(current_level_mux) != 1:
self.circuit.append(ucg, [target] + mult_controls)
else:
self.circuit.unitary(current_level_mux[0], target) # pylint: disable=maybe-no-member
return ucg
def _preserve_previous(self, mux: 'list[np.ndarray]',
mult_controls: 'list[int]',
r_gate: int, target: int):
"""
Remove one gate from mux and apply separately to avoid changing previous base vectors
"""
out_gate = mux[r_gate]
qc_gate = QuantumCircuit(1)
qc_gate.unitary(out_gate, 0) # pylint: disable=maybe-no-member
mux[r_gate] = np.eye(2)
out_gate_ctrl = list(range(0, target)) + list(range(target + 1, self.num_qubits))
ctrl_state = self.str_target[0:target][::-1]
if len(ctrl_state) < self.num_qubits - 1:
ctrl_state = bin(r_gate)[2:].zfill(len(mult_controls)) + ctrl_state
gate = qc_gate.control(self.num_qubits - 1, ctrl_state=ctrl_state)
self.circuit.compose(gate, out_gate_ctrl + [target], inplace=True)
@staticmethod
def _update_parent(children):
size = len(children) // 2
parent = [la.norm([children[2 * k], children[2 * k + 1]]) for k in range(size)]
return parent
@staticmethod
def _apply_diagonal(bit_target: str, parent: 'list[float]', ucg: UCGate):
children = parent
if bit_target == '1':
diagonal = np.conj(ucg._get_diagonal())[1::2] # pylint: disable=protected-access
else:
diagonal = np.conj(ucg._get_diagonal())[::2] # pylint: disable=protected-access
children = children * diagonal
return children
def _get_ctrl_targ(self, tree_level: int):
controls = list(range(self.num_qubits - tree_level + 1, self.num_qubits))
target = self.num_qubits - tree_level
return controls, target
def _build_multiplexor(self, parent_amplitudes: 'list[float]',
children_amplitudes: 'list[float]', str_target: str):
"""
Infers the unitary to be used in the uniformily controlled multiplexor
defined by Bergholm et al (2005).
Args:
parent_amplitudes: list of amplitudes
children_amplitudes: children of the parent amplitudes
Returns:
list of 2-by-2 numpy arrays with the desired unitaries to be used
in the multiplexor
"""
tree_lvl = int(np.log2(len(children_amplitudes)))
bit_target = str_target[self.num_qubits - tree_lvl]
gates = []
len_pnodes = len(parent_amplitudes)
len_snodes = len(children_amplitudes)
for parent_idx, sibling_idx in zip(range(len_pnodes), range(0, len_snodes, 2)):
if parent_amplitudes[parent_idx] != 0:
amp_ket0 = (children_amplitudes[sibling_idx] / parent_amplitudes[parent_idx])
amp_ket1 = (children_amplitudes[sibling_idx + 1] / parent_amplitudes[parent_idx])
if amp_ket0 != 0:
gates += [self._get_branch_operator(amp_ket0, amp_ket1, bit_target)]
else:
gates += [self._get_diagonal_operator(amp_ket1, bit_target)]
else:
gates += [np.eye(2)]
return gates
@staticmethod
def _get_branch_operator(amplitude_ket0, amplitude_ket1, target='0'):
"""
Returns the matrix operator that is going to split the qubit in to two components
of a superposition
Args:
amplitude_ket0: Complex amplitude of the |0> component of the superpoisition
amplitude_ket1: Complex amplitude of the |1> component of the superpoisition
Returns:
A 2x2 numpy array defining the desired operator inferred from
the amplitude argument
"""
if target == '0':
operator = np.array([[amplitude_ket0, -np.conj(amplitude_ket1)],
[amplitude_ket1, np.conj(amplitude_ket0)]])
else:
operator = np.array([[-np.conj(amplitude_ket1), amplitude_ket0],
[np.conj(amplitude_ket0), amplitude_ket1]])
return np.conj(operator).T
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
gate = UCGInitialize(state, opt_params=opt_params)
if qubits is None:
q_circuit.append(gate.definition, q_circuit.qubits)
else:
q_circuit.append(gate.definition, qubits)
@staticmethod
def _get_diagonal_operator(amplitude_ket1, target):
if target == '0':
operator = np.array([[0, 1], [amplitude_ket1, 0]])
else:
operator = np.array([[1, 0], [0, amplitude_ket1]])
return np.conj(operator).T
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
todo
"""
import numpy as np
import qiskit
from qiskit.circuit.library import UCGate
from qiskit.quantum_info import Operator
from qclib.state_preparation.ucg import UCGInitialize
def _repetition_verify(base, d, mux, mux_cpy):
i = 0
next_base = base + d
while i < d:
if not np.allclose(mux[base], mux[next_base]):
return False
mux_cpy[next_base] = None
base, next_base, i = base + 1, next_base + 1, i + 1
return True
def _repetition_search(mux, n, mux_cpy):
dont_carry = []
for i in range(1, len(mux) // 2 + 1):
d = i
entanglement = False
if np.log2(d).is_integer() and np.allclose(mux[i], mux[0]):
mux_org = mux_cpy[:]
repetitions = len(mux) // (2 * d)
base = 0
while repetitions:
repetitions -= 1
valid = _repetition_verify(base, d, mux, mux_cpy)
base += 2 * d
if not valid:
mux_cpy[:] = mux_org
break
if repetitions == 0:
entanglement = True
if entanglement:
dont_carry.append(n + int(np.log2(d)) + 1)
return dont_carry
class UCGEInitialize(UCGInitialize):
""" todo """
def __init__(self, params, label=None, opt_params=None):
super().__init__(params, label=label, opt_params=opt_params)
def _define_initialize(self):
children = self.params
parent = self._update_parent(children)
tree_level = self.num_qubits
r_gate = self.target_state // 2
while tree_level > 0:
bit_target, ucg = self._disentangle_qubit(
children, parent, r_gate, tree_level
)
children = self._apply_diagonal(bit_target, parent, ucg)
parent = self._update_parent(children)
# prepare next iteration
r_gate = r_gate // 2
tree_level -= 1
return self.circuit.inverse()
def _disentangle_qubit(
self,
children: "list[float]",
parent: "list[float]",
r_gate: int,
tree_level: int,
):
"""Apply UCGate to disentangle qubit target"""
bit_target = self.str_target[self.num_qubits - tree_level]
old_mult, old_controls, target = self._define_mult(children, parent, tree_level)
nc, mult = self._simplify(old_mult, tree_level)
mult_controls = [x for x in old_controls if x not in nc]
if self.preserve:
self._preserve_previous(mult, mult_controls, r_gate, target)
ucg = self._apply_ucg(mult, mult_controls, target)
ucg.dont_carry = nc
ucg.controls = mult_controls
return bit_target, ucg
def _simplify(self, mux, level):
mux_cpy = mux.copy()
dont_carry = []
if len(mux) > 1:
n = self.num_qubits - level
dont_carry = _repetition_search(mux, n, mux_cpy)
new_mux = [matrix for matrix in mux_cpy if matrix is not None]
return dont_carry, new_mux
def _apply_diagonal(
self,
bit_target: str,
parent: "list[float]",
ucg: UCGate
):
children = parent
if bit_target == "1":
diagonal = np.conj(ucg._get_diagonal())[
1::2
] # pylint: disable=protected-access
else:
diagonal = np.conj(ucg._get_diagonal())[
::2
] # pylint: disable=protected-access
if ucg.dont_carry:
ucg.controls.reverse()
size_required = len(ucg.dont_carry) + len(ucg.controls)
ctrl_qc = [self.num_qubits - 1 - x for x in ucg.controls]
unitary_diagonal = np.diag(diagonal)
qc = qiskit.QuantumCircuit(size_required)
qc.unitary(unitary_diagonal, ctrl_qc)
matrix = Operator(qc).to_matrix()
diagonal = np.diag(matrix)
children = children * diagonal
return children
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
gate = UCGEInitialize(state, opt_params=opt_params)
if qubits is None:
q_circuit.append(gate.definition, q_circuit.qubits)
else:
q_circuit.append(gate.definition, qubits)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
https://arxiv.org/abs/2108.10182
"""
import qiskit
from qclib.state_preparation.util.tree_utils import children
def output(angle_tree, output_qubits):
"""Define output qubits"""
if angle_tree:
output_qubits.insert(0, angle_tree.qubit) # qiskit little-endian
if angle_tree.left:
output(angle_tree.left, output_qubits)
else:
output(angle_tree.right, output_qubits)
def _add_register(angle_tree, qubits, start_level):
if angle_tree:
angle_tree.qubit = qubits.pop(0)
if angle_tree.level < start_level:
_add_register(angle_tree.left, qubits, start_level)
_add_register(angle_tree.right, qubits, start_level)
else:
if angle_tree.left:
_add_register(angle_tree.left, qubits, start_level)
else:
_add_register(angle_tree.right, qubits, start_level)
def add_register(circuit, angle_tree, start_level):
"""
Organize qubit registers, grouping by "output" and "ancilla" types.
"""
level = 0
level_nodes = []
nodes = [angle_tree]
while len(nodes) > 0: # count nodes per level
level_nodes.append(len(nodes))
nodes = children(nodes)
level += 1
noutput = level # one output qubits per level
nqubits = sum(level_nodes[:start_level]) # bottom-up qubits
# top-down qubits: (number of sub-states) * (number of qubits per sub-state)
nqubits += level_nodes[start_level] * (noutput - start_level)
nancilla = nqubits - noutput
output_register = qiskit.QuantumRegister(noutput, name="output")
circuit.add_register(output_register)
qubits = [*output_register[::-1]]
if nancilla > 0:
ancilla_register = qiskit.QuantumRegister(nancilla, name="ancilla")
circuit.add_register(ancilla_register)
qubits.extend([*ancilla_register[::-1]])
_add_register(angle_tree, qubits, start_level)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the baa.py module.
"""
from test.test_baa_lowrank import TestBaaLowRank
import datetime
import os
from unittest import TestCase
import numpy as np
import qiskit
from qiskit import QiskitError
from qiskit.circuit.random import random_circuit
from qclib.entanglement import geometric_entanglement, \
meyer_wallach_entanglement
from qclib.state_preparation import BaaLowRankInitialize
from qclib.state_preparation.lowrank import cnot_count as schmidt_cnots
from qclib.state_preparation.util.baa import adaptive_approximation
from qclib.util import get_state
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
use_parallel = os.getenv('QLIB_TEST_PARALLEL', 'False') == 'True'
def get_vector(e_lower: float, e_upper: float, num_qubits: int,
start_depth_multiplier=1, measure='meyer_wallach'):
entanglement = -1.0
if isinstance(start_depth_multiplier, int):
multiplier = start_depth_multiplier
elif isinstance(start_depth_multiplier, (tuple, list, np.ndarray)):
assert len(start_depth_multiplier) > 1
multiplier = np.random.randint(start_depth_multiplier[0], start_depth_multiplier[1])
else:
raise ValueError("start_depth_multiplier must be either an int or an array-like of int.")
iteration = 0
entanglements = []
vector = np.ndarray(shape=(0,))
while e_lower > entanglement or entanglement > e_upper:
np.random.seed()
q_circuit: qiskit.QuantumCircuit = random_circuit(num_qubits, multiplier * num_qubits)
vector = get_state(q_circuit)
if measure == 'geometric':
entanglement = geometric_entanglement(vector)
elif measure == 'meyer_wallach':
entanglement = meyer_wallach_entanglement(vector)
else:
raise ValueError(f'Entanglement Measure {measure} unknown.')
iteration += 1
if iteration > 100:
multiplier += 1
iteration = 0
if not use_parallel:
print(
f'{multiplier} ({np.min(entanglements):.4f}-{np.max(entanglements):.4f})',
end='\n', flush=True
)
entanglements = []
else:
entanglements.append(entanglement)
if not use_parallel:
print('.', end='', flush=True)
if not use_parallel:
print(
f'Final {multiplier} ({np.min(entanglements):.4f}-{np.max(entanglements):.4f})',
end='\n', flush=True
)
return vector, entanglement, multiplier * num_qubits
def initialize_loss(fidelity_loss, state_vector=None, n_qubits=5, strategy='brute_force',
use_low_rank=False):
if state_vector is None:
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
opt_params = {'max_fidelity_loss': fidelity_loss,
'strategy': strategy, 'use_low_rank': use_low_rank}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
fidelity = TestBaaLowRank.fidelity(state_vector, state)
node = adaptive_approximation(state_vector, max_fidelity_loss=fidelity_loss,
strategy=strategy, use_low_rank=use_low_rank)
try:
basis_circuit = qiskit.transpile(
circuit, basis_gates=['rx', 'ry', 'rz', 'cx'], optimization_level=0
)
cnots = len([d[0] for d in basis_circuit.data if d[0].name == 'cx'])
depth = basis_circuit.depth()
except QiskitError as ex:
print(ex)
return -1, -1, -1, node
return cnots, depth, round(1 - fidelity, 4), node
def execute_experiment(exp_idx, num_qubits, entanglement_bounds,
max_fidelity_losses, return_state=False,
start_depth_multiplier=1):
print(f"Starting {exp_idx, num_qubits, entanglement_bounds, max_fidelity_losses}")
# State Generation
state_vector, entanglement, depth = get_vector(
*entanglement_bounds, num_qubits, start_depth_multiplier=start_depth_multiplier,
measure='geometric'
)
mw_entanglement = meyer_wallach_entanglement(state_vector)
geo_entanglement = geometric_entanglement(state_vector)
cnots = schmidt_cnots(state_vector)
if not use_parallel:
print(
f"Found state for entanglement bounds {entanglement} in {entanglement_bounds}. "
f"State preparation needs {cnots}."
)
# Benchmark against real Algorithm
real_cnots_benchmark, real_depth_benchmark, real_fidelity_loss_benchmark, _ = initialize_loss(
state_vector=state_vector, fidelity_loss=0.0, use_low_rank=False
)
data_result = []
for max_fidelity_loss in max_fidelity_losses:
for use_low_rank in [False, True]:
for strategy in ['brute_force', 'greedy']:
if not use_parallel:
print(
f"[{max_fidelity_loss}] {strategy.upper()} "
f"{'With' if use_low_rank else 'No'} Low Rank Processing....", end=''
)
start_time = datetime.datetime.now()
real_cnots, real_depth, real_fidelity_loss, node = initialize_loss(
state_vector=state_vector, fidelity_loss=max_fidelity_loss,
use_low_rank=use_low_rank, strategy=strategy
)
end_time = datetime.datetime.now()
duration = (end_time - start_time).total_seconds()
vector_data = list(
zip(node.ranks, [list(v.shape) for v in node.vectors])
)
data = [
exp_idx, use_low_rank, strategy, num_qubits, depth, cnots, geo_entanglement,
mw_entanglement, max_fidelity_loss, node.total_saved_cnots,
node.total_fidelity_loss, vector_data, real_cnots, real_cnots_benchmark,
real_depth, real_depth_benchmark, real_fidelity_loss,
real_fidelity_loss_benchmark, duration
]
if not use_parallel:
print(f"in {duration} secs")
data_result.append(data)
# Experiment transcription
data_result = np.asarray(data_result, dtype=object)
print(f"Done {exp_idx, num_qubits, entanglement_bounds, max_fidelity_losses}")
if return_state:
return data_result, state_vector
return data_result
class TestBaa(TestCase):
def test_node_state_vector(self):
"""
The method Node.state_vector() is an important function for analytics, but it was wrong. The ordering
of the qubits must be taken into account. One example, visible to the human eye, was a probability
distribution, the log-normal. For a max-fidelity-loss of 0.09, the ordering is computed with qubits
[(1,), (3,), (0, 2, 4, 5, 6)] and partitions [None, None, (1, 4)].
The resulting state has an actual fidelity loss of about 0.0859261062108.
The fix is to take the ordering into account. Here we test that for this example, the
fidelity is actually correct.
"""
from qclib.state_preparation.util import baa
# geometric measure = 0.11600417225836746
state = [0.07790067, 0.12411293, 0.10890448, 0.09848761, 0.05027826, 0.05027438,
0.03067742, 0.11846638, 0.09868947, 0.10711022, 0.01826258, 0.12535963,
0.11613662, 0.05865527, 0.05427737, 0.05451262, 0.07021045, 0.09220849,
0.08365776, 0.06869252, 0.09956702, 0.04754114, 0.0688004, 0.07704547,
0.08596225, 0.11279128, 0.05687908, 0.09127936, 0.09797266, 0.02743385,
0.09921588, 0.05256358, 0.03246542, 0.1239935, 0.12508287, 0.11444701,
0.07025331, 0.03978115, 0.10529168, 0.08444882, 0.04446722, 0.08957199,
0.02360472, 0.12138094, 0.06475262, 0.10360775, 0.07106703, 0.09179565,
0.09411756, 0.05472767, 0.12533861, 0.1120676, 0.12337869, 0.12040975,
0.0984252, 0.12221594, 0.03786564, 0.05635093, 0.02707025, 0.07260295,
0.07935725, 0.06630651, 0.11587787, 0.07602843, 0.06746749, 0.09377139,
0.04778426, 0.11400727, 0.03475503, 0.12645201, 0.11185863, 0.05674245,
0.00945899, 0.11494597, 0.10701826, 0.10868207, 0.11178804, 0.03463689,
0.07621068, 0.04332871, 0.11825607, 0.10049395, 0.07322158, 0.03209064,
0.0709839, 0.07258655, 0.10872672, 0.10163697, 0.11989633, 0.08747055,
0.04401971, 0.10750071, 0.11102557, 0.09536318, 0.11176607, 0.08944697,
0.09203053, 0.0832302, 0.02029422, 0.04181051, 0.02256621, 0.10154549,
0.07136789, 0.0907753, 0.12126382, 0.06355451, 0.08154299, 0.110643,
0.06088612, 0.03531675, 0.06851802, 0.05110969, 0.12273343, 0.11442741,
0.10130534, 0.11882721, 0.11411204, 0.05498105, 0.12025703, 0.09348119,
0.11437924, 0.12049476, 0.07178074, 0.04222706, 0.06077118, 0.08318802,
0.11512578, 0.1180934]
node = baa.adaptive_approximation(state, use_low_rank=True, max_fidelity_loss=0.09, strategy='brute_force')
fidelity = np.vdot(state, node.state_vector())**2
self.assertAlmostEqual(node.total_fidelity_loss, 1 - fidelity, places=4)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the baa_lowrank.py module.
"""
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister, transpile
from qiskit_aer import AerSimulator
from qclib.util import get_state
from qclib.state_preparation import BaaLowRankInitialize
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestBaaLowRank(TestCase):
@staticmethod
def fidelity(state1, state2):
bra = np.conj(state1)
ket = state2
return np.power(np.abs(bra.dot(ket)), 2)
@staticmethod
def get_counts(circuit):
n_qubits = circuit.num_qubits
classical_reg = ClassicalRegister(n_qubits)
circuit.add_register(classical_reg)
circuit.measure(list(range(n_qubits)), classical_reg)
backend = AerSimulator()
counts = backend.run(
transpile(circuit, backend),
shots=8192
).result().get_counts()
counts_with_zeros = {}
for i in range(2**n_qubits):
pattern = f'{i:0{n_qubits}b}'
if pattern in counts:
counts_with_zeros[pattern] = counts[pattern]
else:
counts_with_zeros[pattern] = 0.0
sum_values = sum(counts.values())
return [ value/sum_values for (key, value) in counts_with_zeros.items() ]
def _test_initialize_loss(self, fidelity_loss, state_vector=None,
n_qubits=5, strategy='brute_force', use_low_rank=False):
if state_vector is None:
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
opt_params = {'max_fidelity_loss':fidelity_loss,
'strategy' : strategy,
'use_low_rank':use_low_rank}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
fidelity = TestBaaLowRank.fidelity(state_vector, state)
self.assertTrue(round(fidelity,2)>=round(1-fidelity_loss,2)*0.99)
def test_initialize_loss_brute_force(self):
for loss in range(5, 15):
self._test_initialize_loss(loss/100, n_qubits=5, strategy='brute_force')
def test_initialize_loss_brute_force_low_rank(self):
for loss in range(5, 15):
self._test_initialize_loss(loss/100, n_qubits=5, strategy='brute_force',
use_low_rank=True)
def test_initialize_loss_greedy(self):
for loss in range(5, 15):
self._test_initialize_loss(loss/100, n_qubits=5, strategy='greedy')
def test_initialize_loss_greedy_low_rank(self):
for loss in range(5, 15):
self._test_initialize_loss(loss/100, n_qubits=5, strategy='greedy',
use_low_rank=True)
def test_initialize_loss_fixed_n3(self):
state_vector = [-0.33*1j,0,-0.44-0.44*1j,0.24+0.23*1j,0,0,0,0.62-0.01*1j]
state_vector = state_vector/np.linalg.norm(state_vector)
for loss in [0.1, 0.28, 0.9]:
self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force')
self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy')
def test_initialize_loss_fixed_n4(self):
state_vector = [0.04214906+0.25870366j, 0.18263984+0.05596082j, 0.17202687+0.1843925j ,
0.24972444+0.04666321j, 0.03311006+0.28233458j, 0.26680588+0.22211721j,
0.07205056+0.04556719j, 0.27982261+0.01626855j, 0.22908475+0.25461504j,
0.14290823+0.2425394j , 0.14213592+0.08282699j, 0.0068727 +0.03378424j,
0.2016483 +0.298073j , 0.07520782+0.0639856j , 0.01026576+0.07669651j,
0.31755857+0.09279232j]
state_vector = state_vector/np.linalg.norm(state_vector)
for loss in [0.1, 0.15, 0.18, 0.2]:
self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force')
self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy')
def test_initialize_loss_fixed_n5(self):
state_vector = [0.17777766+0.10171662j, 0.19896424+0.10670792j, 0.07982054+0.19653055j,
0.18155708+0.05746777j, 0.04259147+0.17093567j, 0.21551328+0.08246133j,
0.09549255+0.1117806j , 0.20562749+0.12218064j, 0.16191832+0.01653411j,
0.12255337+0.14109365j, 0.20090638+0.11119666j, 0.19851901+0.04543331j,
0.06842539+0.16671467j, 0.03209685+0.16839388j, 0.01707365+0.20060943j,
0.03853768+0.08183117j, 0.00073591+0.10084589j, 0.09524694+0.18785593j,
0.06005853+0.06977443j, 0.01553849+0.05363906j, 0.10294799+0.12558734j,
0.20142903+0.06801796j, 0.05282011+0.20879126j, 0.11257846+0.20746226j,
0.17737416+0.03461382j, 0.01689154+0.06600272j, 0.06428148+0.06199636j,
0.1163249 +0.160533j , 0.14177201+0.10456823j, 0.03156739+0.04567818j,
0.02078566+0.02023752j, 0.18967059+0.03469463j]
state_vector = state_vector/np.linalg.norm(state_vector)
for loss in [0.1, 0.12, 0.14, 0.16, 0.2]:
self._test_initialize_loss(loss, state_vector=state_vector, strategy='brute_force')
self._test_initialize_loss(loss, state_vector=state_vector, strategy='greedy')
def test_initialize_no_loss(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = BaaLowRankInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_ame(self):
""" Test initialization of a absolutely maximally entangled state"""
state_vector = [1, 1, 1, 1,1,-1,-1, 1, 1,-1,-1, 1, 1, 1,1,1,
1, 1,-1,-1,1,-1, 1,-1,-1, 1,-1, 1,-1,-1,1,1]
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = BaaLowRankInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_measurement_no_loss(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = BaaLowRankInitialize(state_vector).definition
state = TestBaaLowRank.get_counts(circuit)
self.assertTrue(np.allclose( np.power(np.abs(state_vector),2), state,
rtol=1e-01, atol=0.005))
def test_compare_strategies(self):
fidelities1 = []
fidelities2 = []
for n_qubits in range(3,7):
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
for loss in range(10, 20):
opt_params = {'max_fidelity_loss' : loss/100, 'strategy' : 'brute_force'}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
fidelity1 = TestBaaLowRank.fidelity(state_vector, state)
opt_params = {'max_fidelity_loss' : loss/100, 'strategy' : 'greedy'}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
fidelity2 = TestBaaLowRank.fidelity(state_vector, state)
fidelities1.append(fidelity1)
fidelities2.append(fidelity2)
self.assertTrue(np.allclose(fidelities1, fidelities2, rtol=0.14, atol=0.0))
def test_large_state(self):
# Builds a separable state.
n_qubits = 16
state_vector1 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j
state_vector1 = state_vector1 / np.linalg.norm(state_vector1)
state_vector2 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j
state_vector2 = state_vector2 / np.linalg.norm(state_vector2)
state_vector = np.kron(state_vector1, state_vector2)
opt_params = {'max_fidelity_loss' : 0.1, 'strategy' : 'brute_force'}
circuit = BaaLowRankInitialize(state_vector, opt_params=opt_params).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test bidirectional state preparation """
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister
from qiskit_aer import AerSimulator
from qclib.state_preparation import BdspInitialize
from qclib.util import measurement
backend = AerSimulator()
SHOTS = 8192
class TestBdsp(TestCase):
""" Testing bdsp """
@staticmethod
def bdsp_experiment(state, split=None):
""" Run bdsp experiment """
opt_params = {'split': split}
circuit = BdspInitialize(state, opt_params=opt_params).definition
n_qubits = int(np.log2(len(state)))
classical_register = ClassicalRegister(n_qubits)
circuit.add_register(classical_register)
return measurement(circuit, n_qubits, classical_register, backend, SHOTS)
def test_bottom_up(self):
""" Testing bdsp """
vector = np.random.rand(16) + np.random.rand(16) * 1j
vector = vector / np.linalg.norm(vector)
state = TestBdsp.bdsp_experiment(vector, 1)
self.assertTrue(np.allclose(np.power(np.abs(vector), 2), state, rtol=1e-01, atol=0.005))
def test_top_down(self):
""" Testing bdsp """
vector = np.random.rand(16) + np.random.rand(16) * 1j
vector = vector / np.linalg.norm(vector)
state = TestBdsp.bdsp_experiment(vector, int(np.log2(len(vector))))
self.assertTrue(np.allclose(np.power(np.abs(vector), 2), state, rtol=1e-01, atol=0.005))
def test_sublinear(self):
""" Testing bdsp """
vector = np.random.rand(16) + np.random.rand(16) * 1j
vector = vector / np.linalg.norm(vector)
state = TestBdsp.bdsp_experiment(vector)
self.assertTrue(np.allclose(np.power(np.abs(vector), 2), state, rtol=1e-01, atol=0.005))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test blackbox state preparation """
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation.blackbox import BlackBoxInitialize
from qclib.util import get_state
class TestBlackbox(TestCase):
""" Test blackbox state preparation """
def test_blackbox(self):
""" Run blackbox state preparation """
initialize = BlackBoxInitialize.initialize
state = np.random.rand(16) - 0.5 + (np.random.rand(16) - 0.5) * 1j
state = state / np.linalg.norm(state)
q_circuit = QuantumCircuit(5)
initialize(q_circuit, state.tolist())
out = get_state(q_circuit)
out = out.reshape((len(out)//2, 2))
out = out[:, 0]
self.assertTrue(np.allclose(state, out, atol=0.02))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test divide-and-conquer state preparation """
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister
from qiskit_aer import AerSimulator
from qclib.state_preparation import DcspInitialize
from qclib.util import measurement
backend = AerSimulator()
SHOTS = 8192
class TestInitialize(TestCase):
""" Testing divide-and-conquer state preparation """
@staticmethod
def dcsp_experiment(state):
""" Run divide-and-conquer state preparation """
circuit = DcspInitialize(state).definition
n_qubits = int(np.log2(len(state)))
classical_register = ClassicalRegister(n_qubits)
circuit.add_register(classical_register)
return measurement(circuit, n_qubits, classical_register, backend, SHOTS)
def test_dcsp(self):
""" Testing divide-and-conquer state preparation """
vector = np.random.rand(16) + np.random.rand(16) * 1j
vector = vector / np.linalg.norm(vector)
state = TestInitialize.dcsp_experiment(vector)
self.assertTrue(np.allclose(np.power(np.abs(vector), 2), state, rtol=1e-01, atol=0.005))
|
https://github.com/qclib/qclib
|
qclib
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Isometry tests."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.quantum_info.random import random_unitary
from qiskit import BasicAer
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import execute
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.quantum_info import Operator
from qiskit.extensions.quantum_initializer.isometry import Isometry
@ddt
class TestIsometry(QiskitTestCase):
"""Qiskit isometry tests."""
@data(
np.eye(2, 2),
random_unitary(2, seed=868540).data,
np.eye(4, 4),
random_unitary(4, seed=16785).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=660477).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)],
random_unitary(8, seed=247924).data[:, 0:4],
random_unitary(8, seed=765720).data,
random_unitary(16, seed=278663).data,
random_unitary(16, seed=406498).data[:, 0:8],
)
def test_isometry(self, iso):
"""Tests for the decomposition of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.isometry(iso, q[:num_q_input], q[num_q_input:])
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
iso_desired = iso
self.assertTrue(np.allclose(iso_from_circuit, iso_desired))
@data(
np.eye(2, 2),
random_unitary(2, seed=99506).data,
np.eye(4, 4),
random_unitary(4, seed=673459).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=124090).data,
np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)],
random_unitary(8, seed=986292).data[:, 0:4],
random_unitary(8, seed=632121).data,
random_unitary(16, seed=623107).data,
random_unitary(16, seed=889326).data[:, 0:8],
)
def test_isometry_tolerance(self, iso):
"""Tests for the decomposition of isometries from m to n qubits with a custom tolerance"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
# Compute isometry with custom tolerance
qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3)
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
self.assertTrue(np.allclose(iso_from_circuit, iso))
@data(
np.eye(2, 2),
random_unitary(2, seed=272225).data,
np.eye(4, 4),
random_unitary(4, seed=592640).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=714210).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)],
random_unitary(8, seed=656745).data[:, 0:4],
random_unitary(8, seed=583813).data,
random_unitary(16, seed=101363).data,
random_unitary(16, seed=583429).data[:, 0:8],
)
def test_isometry_inverse(self, iso):
"""Tests for the inverse of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.append(Isometry(iso, 0, 0), q)
qc.append(Isometry(iso, 0, 0).inverse(), q)
result = Operator(qc)
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
if __name__ == "__main__":
unittest.main()
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the lowrank.py module.
"""
from unittest import TestCase
from itertools import combinations
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, transpile
from qiskit_aer import AerSimulator
from qclib.state_preparation import LowRankInitialize
from qclib.state_preparation.lowrank import cnot_count
from qclib.util import get_state
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestLowRank(TestCase):
@staticmethod
def mae(state, ideal):
"""
Mean Absolute Error
"""
return np.sum(np.abs(state-ideal))/len(ideal)
@staticmethod
def get_counts(circuit):
n_qubits = circuit.num_qubits
classical_reg = ClassicalRegister(n_qubits)
circuit.add_register(classical_reg)
circuit.measure(list(range(n_qubits)), classical_reg)
backend = AerSimulator()
counts = backend.run(
transpile(circuit, backend),
shots=8192
).result().get_counts()
counts_with_zeros = {}
for i in range(2**n_qubits):
pattern = f'{i:0{n_qubits}b}'
if pattern in counts:
counts_with_zeros[pattern] = counts[pattern]
else:
counts_with_zeros[pattern] = 0.0
sum_values = sum(counts.values())
return [value/sum_values for (key, value) in counts_with_zeros.items()]
def _test_initialize_mae(self, rank=0, max_mae=10**-15):
n_qubits = 5
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
qubits = list(range(n_qubits))
partitions = combinations(qubits, (n_qubits+1)//2)
for partition in partitions:
circuit = QuantumCircuit(n_qubits)
opt_params = {'lr': rank, 'partition': partition}
LowRankInitialize.initialize(circuit, state_vector, opt_params=opt_params)
state = get_state(circuit)
self.assertTrue(TestLowRank.mae(state, state_vector) < max_mae)
def _test_initialize_full_rank(self, n_qubits):
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
qubits = list(range(n_qubits))
partitions = combinations(qubits, (n_qubits+1)//2)
for partition in partitions:
circuit = QuantumCircuit(n_qubits)
opt_params = {'partition': partition}
LowRankInitialize.initialize(circuit, state_vector, opt_params=opt_params)
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_full_rank_6(self):
self._test_initialize_full_rank(6)
def test_initialize_rank_5(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = QuantumCircuit(5)
LowRankInitialize.initialize(circuit, state_vector, opt_params={'lr': 5})
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_real(self):
n_qubits = 5
state_vector = np.random.rand(2**n_qubits)
state_vector = state_vector / np.linalg.norm(state_vector)
qubits = list(range(n_qubits))
partitions = combinations(qubits, (n_qubits+1)//2)
for partition in partitions:
circuit = QuantumCircuit(n_qubits)
opt_params = {'partition': partition}
LowRankInitialize.initialize(circuit, state_vector, opt_params=opt_params)
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_rank_4(self):
self._test_initialize_mae(4, max_mae=10**-10)
def test_initialize_rank_3(self):
self._test_initialize_mae(3, max_mae=0.04)
def test_initialize_rank_2(self):
self._test_initialize_mae(2, max_mae=0.06)
def test_initialize_rank_1(self):
self._test_initialize_mae(1, max_mae=0.09)
def test_cnot_count(self):
n_qubits = 7
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = QuantumCircuit(n_qubits)
LowRankInitialize.initialize(circuit, state_vector)
transpiled_circuit = transpile(circuit, basis_gates=['u', 'cx'], optimization_level=0)
n_cx = transpiled_circuit.count_ops()['cx']
self.assertTrue(cnot_count(state_vector) == n_cx)
def test_cnot_count_rank_1(self):
# Builds a rank 1 state.
state_vector = [1]
for _ in range(5):
vec = np.random.rand(2) + np.random.rand(2) * 1j
vec = vec / np.linalg.norm(vec)
state_vector = np.kron(state_vector, vec)
circuit = QuantumCircuit(5)
LowRankInitialize.initialize(circuit, state_vector)
transpiled_circuit = transpile(circuit, basis_gates=['u', 'cx'], optimization_level=0)
self.assertTrue('cx' not in transpiled_circuit.count_ops())
def test_inverse(self):
n_qubits = 2
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
gate = LowRankInitialize(state_vector)
circuit = QuantumCircuit(n_qubits)
circuit.append(gate, list(range(n_qubits)))
circuit.append(gate.inverse(), list(range(n_qubits)))
state = get_state(circuit)
zero_state = [1]+[0]*(2**n_qubits-1)
self.assertTrue(np.allclose(zero_state, state))
def test_large_state(self):
# Builds a separable state.
n_qubits = 16
state_vector1 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j
state_vector1 = state_vector1 / np.linalg.norm(state_vector1)
state_vector2 = np.random.rand(2**(n_qubits//2)) + np.random.rand(2**(n_qubits//2)) * 1j
state_vector2 = state_vector2 / np.linalg.norm(state_vector2)
state_vector = np.kron(state_vector1, state_vector2)
circuit = QuantumCircuit(n_qubits)
LowRankInitialize.initialize(circuit, state_vector, opt_params={'lr': 1, 'svd':'auto'})
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the merge.py module.
"""
import unittest
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation import MergeInitialize
from qclib.util import get_state, build_state_dict
from qiskit import transpile
from scipy.sparse import random
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestMergeInitialize(unittest.TestCase):
""" Teste MergeInitialize Gate"""
def test_two_states_uniform(self):
state_vector = 1 / np.sqrt(2) * np.array([1, 0, 0, 0, 0, 1, 0, 0])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_superposition(self):
state_vector = 1 / np.sqrt(168) * np.array([0, 2, 0, 0, 8, 0, 0, 10])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_uniform_superposition(self):
state_vector = 1 / np.sqrt(3) * np.array([0, 1, 0, 0, 1, 0, 0, 1])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_three_states_superposition_with_complex_features(self):
state_vector = np.array([0, complex(np.sqrt(0.1), np.sqrt(0.1)), 0, 0,
complex(np.sqrt(0.1), np.sqrt(0.2)), 0, 0, np.sqrt(0.5)])
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
circ = QuantumCircuit(3)
initialize(circ, state_dict)
state = get_state(circ)
self.assertTrue(np.allclose(state_vector, state))
def test_raises_error_input_not_dict(self):
initialize = MergeInitialize.initialize
circ = QuantumCircuit()
with self.assertRaises(Exception):
initialize(circ, [])
def test_8qb_sparse(self):
state_dict = {
'01100000': 0.11496980229422502,
'10010000': 0.2012068017595738,
'11110000': 0.2552406117427385,
'11001000': 0.24483730989689545,
'00011000': 0.08064396530053637,
'01111000': 0.06609205232425505,
'10000100': 0.2567251902135311,
'00100010': 0.279179786457501,
'11110010': 0.14972323818181424,
'00000110': 0.054570286103576615,
'10101110': 0.1953959409811345,
'00011110': 0.2476316976925628,
'00111110': 0.2460713287965397,
'00010001': 0.2880964575493704,
'00011001': 0.11697558413298771,
'11100101': 0.15657582325155645,
'00101101': 0.05059343291713247,
'10011101': 0.21260965910383026,
'11100011': 0.16144719592639006,
'01110011': 0.24224885089395568,
'10011011': 0.07542653172823867,
'01111011': 0.2840232568261471,
'00100111': 0.2719803407586484,
'01100111': 0.14940066988379283,
'11010111': 0.2025293455684502,
'01001111': 0.06045929196877916
}
initialize = MergeInitialize.initialize
qc = QuantumCircuit(8)
initialize(qc, state_dict)
t_circuit = transpile(qc, basis_gates=['cx', 'u'])
def test_several_qubit_sizes(self):
for n_qubits in range(4, 12):
state_vector = random(1, 2 ** n_qubits, density=0.1, random_state=42).A.reshape(-1)
state_vector = state_vector / np.linalg.norm(state_vector)
state_dict = build_state_dict(state_vector)
initialize = MergeInitialize.initialize
qc = QuantumCircuit(n_qubits)
initialize(qc, state_dict)
state = get_state(qc)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test Probabilistic Quantum Memory"""
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qclib.memory.pqm import initialize as pqm
from qclib.state_preparation import LowRankInitialize
from qclib.util import get_counts
class TestPQM(TestCase):
""" Testing qclib.memory.pqm"""
@staticmethod
def _run_pqm(is_classical_pattern):
""" run PQM with classical or quantum input"""
# pqm memory data
data = [0, 1, 0, 0]
data = data / np.linalg.norm(data)
# initialize quantum registers
memory = QuantumRegister(2, 'm')
aux = QuantumRegister(1, 'c')
output = ClassicalRegister(1)
circ = QuantumCircuit(memory, aux, output)
# initialize data
init_gate = LowRankInitialize(data)
circ.append(init_gate, memory)
# initialize input pattern
bin_input = [1, 0]
if is_classical_pattern:
# run pqm recovery algorithm
pqm(circ, bin_input, memory, aux, is_classical_pattern=True)
else:
q_bin_input = QuantumRegister(2)
circ.add_register(q_bin_input)
# Pattern basis encoding
for k, bit in enumerate(bin_input):
if bit == 1:
circ.x(q_bin_input[k])
# run pqm recovery algorithm
pqm(circ, q_bin_input, memory, aux, is_classical_pattern=False)
# measure output and verify results
circ.measure(aux, output) # pylint: disable=maybe-no-member
counts = get_counts(circ)
return counts
def test_classical_input(self):
""" Testing PQM with classical input """
# classical input pattern
counts = TestPQM._run_pqm(True)
self.assertTrue(counts['0'] / 1024 == 1)
def test_quantum_input(self):
""" Testing PQM with quantum input """
# quantum input pattern
counts = TestPQM._run_pqm(False)
self.assertTrue(counts['0'] / 1024 == 1)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the svd.py module.
"""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation.svd import SVDInitialize
from qclib.util import get_state
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
class TestSVDInitialize(TestCase):
def _test_initialize(self, n_qubits):
state_vector = np.random.rand(2**n_qubits) + np.random.rand(2**n_qubits) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = QuantumCircuit(n_qubits)
SVDInitialize.initialize(circuit, state_vector)
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_initialize_6(self):
self._test_initialize(6)
def test_initialize_5(self):
self._test_initialize(5)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the topdown.py module.
"""
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister, transpile
from qiskit_aer import AerSimulator
from qclib.state_preparation import TopDownInitialize
from qclib.util import get_state, measurement
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
backend = AerSimulator()
SHOTS = 8192
class TestTopDown(TestCase):
@staticmethod
def measurement(circuit, n_qubits, classical_reg):
circuit.measure(list(range(n_qubits)), classical_reg)
job = backend.run(
transpile(circuit, backend),
shots=SHOTS,
optimization_level=3
)
counts = job.result().get_counts(circuit)
sum_values = sum(counts.values())
counts2 = {}
for i in range(2**n_qubits):
pattern = f'{i:0{n_qubits}b}'
if pattern in counts:
counts2[pattern] = counts[pattern]
else:
counts2[pattern] = 0.0
return [ value/sum_values for (key, value) in counts2.items() ]
@staticmethod
def topdown_experiment(state):
circuit = TopDownInitialize(state).definition
n_qubits = int(np.log2(len(state)))
classical_reg = ClassicalRegister(n_qubits)
circuit.add_register(classical_reg)
return measurement(circuit, n_qubits, classical_reg, backend, SHOTS)
def test_topdown_state_real(self):
state_vector = np.random.rand(32)
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_topdown_state_complex(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
def test_topdown_measure(self):
state_vector = np.random.rand(32) + np.random.rand(32) * 1j
state_vector = state_vector / np.linalg.norm(state_vector)
state = TestTopDown.topdown_experiment(state_vector)
self.assertTrue(np.allclose(np.power(np.abs(state_vector), 2), state,
rtol=1e-01, atol=0.005))
def test_topdown_fixed_state(self):
state_vector = [
0, np.sqrt(2 / 8) * np.exp(-1.0j * np.pi / 7),
np.sqrt(3 / 8) * np.exp(-1.0j * np.pi / 3), 0,
0, 0, np.sqrt(3 / 8), 0
]
circuit = TopDownInitialize(state_vector).definition
state = get_state(circuit)
self.assertTrue(np.allclose(state_vector, state))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the bergholm state preparation
"""
from unittest import TestCase
import random
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Statevector
from qclib.state_preparation import UCGInitialize
from qclib.state_preparation import UCGEInitialize
class TestUCGEInitialize(TestCase):
"""Test UCGEInitialize"""
@staticmethod
def _logical_swap(num_qubits, input_vector, new_order):
qubit_shape = [2] * num_qubits
reshaped_state = input_vector.reshape(qubit_shape)
swapped_vector = np.moveaxis(reshaped_state, new_order, range(len(new_order))).reshape(-1,)
return swapped_vector
def _test_compare_ucg_bipartition(self, num_qubits, input_vector1, input_vector2):
qubit_order = list(range(num_qubits))
random.shuffle(qubit_order)
input_vector = np.kron(input_vector1, input_vector2)
input_vector = self._logical_swap(num_qubits, input_vector, qubit_order)
circuit1 = QuantumCircuit(num_qubits)
UCGInitialize.initialize(circuit1, input_vector)
state1 = Statevector(circuit1)
circuit2 = QuantumCircuit(num_qubits)
UCGEInitialize.initialize(circuit2, input_vector)
state2 = Statevector(circuit2)
circuit1_tranpiled = transpile(circuit1, basis_gates=['u', 'cx'])
circuit2_transpiled = transpile(circuit2, basis_gates=['u', 'cx'])
self.assertTrue(np.allclose(state1, state2))
self.assertTrue(circuit1_tranpiled.depth() >= circuit2_transpiled.depth())
def test_compare_ucg_bipartition_real(self):
num_qubits = 8
input_vector1 = np.random.rand(2 ** (num_qubits//2))
input_vector1 = input_vector1 / np.linalg.norm(input_vector1)
input_vector2 = np.random.rand(2 ** (num_qubits//2))
input_vector2 = input_vector2 / np.linalg.norm(input_vector2)
self._test_compare_ucg_bipartition(num_qubits, input_vector1, input_vector2)
def test_compare_ucg_bipartition_complex(self):
num_qubits = 8
real_part = np.random.rand(2 ** (num_qubits//2))
imag_part = np.random.rand(2 ** (num_qubits//2))
input_vector1 = real_part + 1j * imag_part
input_vector1 = input_vector1 / np.linalg.norm(input_vector1)
real_part = np.random.rand(2 ** (num_qubits//2))
imag_part = np.random.rand(2 ** (num_qubits//2))
input_vector2 = real_part + 1j * imag_part
input_vector2 = input_vector2 / np.linalg.norm(input_vector2)
self._test_compare_ucg_bipartition(num_qubits, input_vector1, input_vector2)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for the bergholm state preparation
"""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qclib.state_preparation import UCGInitialize
from qclib.util import get_state
class TestUCGInitialize(TestCase):
"""Test UCGInitialize"""
def _test_ucg(self, n_qubits):
state = np.random.rand(2 ** n_qubits) + np.random.rand(2 ** n_qubits) * 1j
state = state / np.linalg.norm(state)
for target_state in range(2 ** n_qubits):
gate = UCGInitialize(state.tolist(),
opt_params={
"target_state": target_state
}
).definition
circuit = QuantumCircuit(n_qubits)
for j, bit in enumerate(f'{target_state:0{n_qubits}b}'[::-1]):
if bit == '1':
circuit.x(j)
circuit.append(gate, circuit.qubits)
output_state = get_state(circuit)
self.assertTrue(np.allclose(state, output_state))
def _test_ucg_preserve(self, n_qubits):
state = np.random.rand(2 ** n_qubits) + np.random.rand(2 ** n_qubits) * 1j
for target_state in range(1, 2 ** n_qubits):
state[target_state - 1] = 0
state = state / np.linalg.norm(state)
gate = UCGInitialize(state.tolist(),
opt_params={
"target_state": target_state,
"preserve_previous": True
}
).definition
circuit = QuantumCircuit(n_qubits)
for j, bit in enumerate(f'{target_state:0{n_qubits}b}'[::-1]):
if bit == '1':
circuit.x(j)
circuit.append(gate, circuit.qubits)
output_state = get_state(circuit)
self.assertTrue(np.allclose(output_state, state))
def test_ucg(self):
"""Test UCGInitialize"""
for n_qubits in range(3, 5):
self._test_ucg(n_qubits)
def test_ucg_preserve(self):
"""Test UCGInitialize with `preserve_previous`"""
for n_qubits in range(3, 5):
self._test_ucg_preserve(n_qubits)
def test_real(self):
"""Test UCGInitialize with four qubits and index 10"""
n_qubits = 4
state = np.random.rand(2 ** n_qubits)
state[0] = 0
state[1] = 0
state = state / np.linalg.norm(state)
initialize = UCGInitialize.initialize
circuit = QuantumCircuit(n_qubits)
circuit.x(1)
circuit.x(3)
initialize(circuit, state.tolist(), opt_params={"target_state": 10})
output_state = get_state(circuit)
self.assertTrue(np.allclose(output_state, state))
|
https://github.com/qclib/qclib
|
qclib
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""UnitaryGate tests"""
import json
import numpy
from numpy.testing import assert_allclose
import qiskit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.passes import CXCancellation
class TestUnitaryGate(QiskitTestCase):
"""Tests for the Unitary class."""
def test_set_matrix(self):
"""Test instantiation"""
try:
UnitaryGate([[0, 1], [1, 0]])
# pylint: disable=broad-except
except Exception as err:
self.fail(f"unexpected exception in init of Unitary: {err}")
def test_set_matrix_raises(self):
"""test non-unitary"""
try:
UnitaryGate([[1, 1], [1, 0]])
# pylint: disable=broad-except
except Exception:
pass
else:
self.fail("setting Unitary with non-unitary did not raise")
def test_set_init_with_unitary(self):
"""test instantiation of new unitary with another one (copy)"""
uni1 = UnitaryGate([[0, 1], [1, 0]])
uni2 = UnitaryGate(uni1)
self.assertEqual(uni1, uni2)
self.assertFalse(uni1 is uni2)
def test_conjugate(self):
"""test conjugate"""
ymat = numpy.array([[0, -1j], [1j, 0]])
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat))
def test_adjoint(self):
"""test adjoint operation"""
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix()))
class TestUnitaryCircuit(QiskitTestCase):
"""Matrix gate circuit tests."""
def test_1q_unitary(self):
"""test 1 qubit unitary matrix"""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
qc.x(qr[0])
qc.append(UnitaryGate(matrix), [qr[0]])
# test of qasm output
self.log.info(qc.qasm())
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
dag_nodes = dag.named_nodes("unitary")
self.assertTrue(len(dag_nodes) == 1)
dnode = dag_nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0],))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_2q_unitary(self):
"""test 2 qubit unitary matrix"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
qc.x(qr[0])
uni2q = UnitaryGate(matrix)
qc.append(uni2q, [qr[0], qr[1]])
passman = PassManager()
passman.append(CXCancellation())
qc2 = passman.run(qc)
# test of qasm output
self.log.info(qc2.qasm())
# test of text drawer
self.log.info(qc2)
dag = circuit_to_dag(qc)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1]))
assert_allclose(dnode.op.to_matrix(), matrix)
qc3 = dag_to_circuit(dag)
self.assertEqual(qc2, qc3)
def test_3q_unitary(self):
"""test 3 qubit unitary matrix on non-consecutive bits"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.x(qr[0])
uni3q = UnitaryGate(matrix)
qc.append(uni3q, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3]))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_1q_unitary_int_qargs(self):
"""test single qubit unitary matrix with 'int' and 'list of ints' qubits argument"""
sigmax = numpy.array([[0, 1], [1, 0]])
sigmaz = numpy.array([[1, 0], [0, -1]])
# new syntax
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.unitary(sigmax, 0)
qc.unitary(sigmax, qr[1])
qc.unitary(sigmaz, [0, 1])
# expected circuit
qc_target = QuantumCircuit(qr)
qc_target.append(UnitaryGate(sigmax), [0])
qc_target.append(UnitaryGate(sigmax), [qr[1]])
qc_target.append(UnitaryGate(sigmaz), [[0, 1]])
self.assertEqual(qc, qc_target)
def test_qobj_with_unitary_matrix(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.rx(numpy.pi / 4, qr[0])
uni = UnitaryGate(matrix)
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "unitary")
assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix)
# check conversion to dict
qobj_dict = qobj.to_dict()
class NumpyEncoder(json.JSONEncoder):
"""Class for encoding json str with complex and numpy arrays."""
def default(self, obj):
if isinstance(obj, numpy.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
# check json serialization
self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str))
def test_labeled_unitary(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
uni = UnitaryGate(matrix, label="xy")
qc.append(uni, [qr[0], qr[1]])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[0]
self.assertEqual(instr.name, "unitary")
self.assertEqual(instr.label, "xy")
def test_qasm_unitary_only_one_def(self):
"""test that a custom unitary can be converted to qasm and the
definition is only written once"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_twice(self):
"""test that a custom unitary can be converted to qasm and that if
the qasm is called twice it is the same every time"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_2q_unitary(self):
"""test that a 2 qubit custom unitary can be converted to qasm"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0], qr[1]])
qc.append(unitary_gate, [qr[1], qr[0]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n"
"qreg q0[2];\n"
"creg c0[1];\n"
"x q0[0];\n"
"unitary q0[0],q0[1];\n"
"unitary q0[1],q0[0];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_noop(self):
"""Test that an identity unitary can be converted to OpenQASM 2"""
qc = QuantumCircuit(QuantumRegister(3, "q0"))
qc.unitary(numpy.eye(8), qc.qubits)
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1,q2 { }\n"
"qreg q0[3];\n"
"unitary q0[0],q0[1],q0[2];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_unitary_decomposition(self):
"""Test decomposition for unitary gates over 2 qubits."""
qc = QuantumCircuit(3)
qc.unitary(random_unitary(8, seed=42), [0, 1, 2])
self.assertTrue(Operator(qc).equiv(Operator(qc.decompose())))
def test_unitary_decomposition_via_definition(self):
"""Test decomposition for 1Q unitary via definition."""
mat = numpy.array([[0, 1], [1, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_decomposition_via_definition_2q(self):
"""Test decomposition for 2Q unitary via definition."""
mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_control(self):
"""Test parameters of controlled - unitary."""
mat = numpy.array([[0, 1], [1, 0]])
gate = UnitaryGate(mat).control()
self.assertTrue(numpy.allclose(gate.params, mat))
self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mcg.LdMcSpecialUnitary """
from unittest import TestCase
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, transpile
from qiskit.circuit.library import RXGate
from qiskit.quantum_info import Operator
from qclib.gates.multitargetmcsu2 import MultiTargetMCSU2
class TestCMcSpecialUnitary(TestCase):
"""
Test cases for the decomposition of
Multicontrolled Special Unitary with linear depth
https://arxiv.org/pdf/2302.06377.pdf
"""
def _build_qiskit_circ(
self,
num_controls
):
""""default mode: target = controls"""
controls_list = list(range(num_controls))
target = num_controls
qiskit_circ = QuantumCircuit(num_controls + 3)
qiskit_circ.mcrx(0.7, controls_list, target)
qiskit_circ.mcrx(0.13, controls_list, target+1)
qiskit_circ.mcrx(0.5, controls_list, target+2)
return qiskit_circ
def _build_ldmcsu_circ(self, unitary_list, num_controls):
""""
default mode: target = controls
"""
controls_list = list(range(num_controls))
target = num_controls
ldmcsu_circ = QuantumCircuit(num_controls + 3)
MultiTargetMCSU2.multi_target_mcsu2(ldmcsu_circ, unitary_list[0], controls_list, target)
MultiTargetMCSU2.multi_target_mcsu2(ldmcsu_circ, unitary_list[1], controls_list, target + 1)
MultiTargetMCSU2.multi_target_mcsu2(ldmcsu_circ, unitary_list[2], controls_list, target + 2)
return ldmcsu_circ
def _build_cldmcsu_circ(self, unitary_list, num_controls):
""""
default mode: target = controls
"""
controls = QuantumRegister(num_controls)
target = QuantumRegister(len(unitary_list))
cldmcsu_circ = QuantumCircuit(controls, target)
MultiTargetMCSU2.multi_target_mcsu2(cldmcsu_circ, unitary_list, controls, target)
return cldmcsu_circ
def test_clcmcsu_3targets(self):
"""
Test for comparison of a cascade uf 3 multi-controlled SU(2) using
qiskit and cldmcsu implementations.
"""
num_controls = 7
unitary_list = [RXGate(0.7).to_matrix(), RXGate(0.13).to_matrix(), RXGate(0.5).to_matrix()]
qiskit_circ = self._build_qiskit_circ(num_controls)
cldmcsu_circ = self._build_cldmcsu_circ(unitary_list, num_controls)
qiskitt = transpile(qiskit_circ, basis_gates=['u', 'cx'], optimization_level=3)
cldmcsut = transpile(cldmcsu_circ, basis_gates=['u', 'cx'], optimization_level=3)
qiskit_ops = qiskitt.count_ops()
qclib_ops = cldmcsut.count_ops()
self.assertTrue(qiskit_ops['cx'] > qclib_ops['cx'])
cldmcsu_op = Operator(cldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(cldmcsu_op, qiskit_op))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mcg.LdMcSpecialUnitary """
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import RXGate
from qiskit.quantum_info import Operator
from qiskit.circuit.library import UnitaryGate
from scipy.stats import unitary_group
from qclib.gates.ldmcsu import LdMcSpecialUnitary, Ldmcsu
from qclib.gates.util import u2_to_su2
from qclib.util import get_cnot_count
NUM_CTRL = 6
def _generate_su_2():
"""
Returns random SU(2) matrix
"""
u_2 = unitary_group.rvs(2)
su_2, _ = u2_to_su2(u_2)
return su_2
class TestLcMcSpecialUnitary(TestCase):
"""
Test cases for the decomposition of
Multicontrolled Special Unitary with linear depth
by Barenco et al.
"""
def _build_qiskit_circuit(self, su2, num_controls, ctrl_state=None):
su2_gate = UnitaryGate(su2)
controls_list = list(range(num_controls))
target = num_controls
qiskit_circ = QuantumCircuit(num_controls + 1)
qiskit_circ.append(su2_gate.control(num_controls, ctrl_state=ctrl_state),
[*controls_list, target])
return qiskit_circ
def _compute_bound(self, num_qubits):
if num_qubits % 2 == 0:
return 28 * num_qubits - 88
return 28 * num_qubits - 92
def test_lcmcsu_op_for_trivial_control_state(self):
"""
Test LdMcSpecialUnitary open controls
"""
su2 = _generate_su_2()
num_controls = NUM_CTRL
ldmcsu_circ = LdMcSpecialUnitary(su2, num_controls).definition
qiskit_circ = self._build_qiskit_circuit(su2, num_controls)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
def test_lcmcsu_op_for_all_zero_control_states(self):
"""
Test LdMcSpecialUnitary with open controls
"""
su_2 = _generate_su_2()
num_controls = NUM_CTRL
ctrl_state = '0' * num_controls
ldmcsu_circ = LdMcSpecialUnitary(su_2, num_controls, ctrl_state=ctrl_state).definition
qiskit_circ = self._build_qiskit_circuit(su_2, num_controls, ctrl_state=ctrl_state)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
def test_lcmcsu_cnot_count(self):
"""
Test LdMcSpecialUnitary cx count
"""
su_2 = _generate_su_2()
for num_controls in range(8, 10):
ldmcsu_circ = LdMcSpecialUnitary(su_2, num_controls).definition
ldmcsu_count = get_cnot_count(ldmcsu_circ)
self.assertLessEqual(ldmcsu_count, self._compute_bound(num_controls+1))
class TestMcSpecialUnitary(TestCase):
"""
Test cases for the decomposition of
Multicontrolled Special Unitary with linear depth
https://arxiv.org/pdf/2302.06377.pdf
"""
def _build_qiskit_circuit(self, su2, num_controls, ctrl_state=None):
su2_gate = UnitaryGate(su2)
controls_list = list(range(num_controls))
target = num_controls
qiskit_circ = QuantumCircuit(num_controls + 1)
qiskit_circ.append(su2_gate.control(num_controls, ctrl_state=ctrl_state),
[*controls_list, target])
return qiskit_circ
def _compute_bound(self, num_qubits):
if num_qubits % 2 == 0:
return 28 * num_qubits - 88
return 28 * num_qubits - 92
def test_lcmcsu_op_for_trivial_control_state(self):
"""
Test LdMcSpecialUnitary open controls
"""
su2 = _generate_su_2()
num_controls = NUM_CTRL
ldmcsu_circ = Ldmcsu(su2, num_controls).definition
qiskit_circ = self._build_qiskit_circuit(su2, num_controls)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
def test_lcmcsu_op_for_all_zero_control_states(self):
"""
Test LdMcSpecialUnitary with open controls
"""
su_2 = _generate_su_2()
num_controls = NUM_CTRL
ctrl_state = '0' * num_controls
ldmcsu_circ = Ldmcsu(su_2, num_controls, ctrl_state=ctrl_state).definition
qiskit_circ = self._build_qiskit_circuit(su_2, num_controls, ctrl_state=ctrl_state)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
def test_lcmcsu_cnot_count(self):
"""
Test LdMcSpecialUnitary cx count
"""
su_2 = _generate_su_2()
for num_controls in range(8, 10):
ldmcsu_circ = Ldmcsu(su_2, num_controls).definition
ldmcsu_count = get_cnot_count(ldmcsu_circ)
self.assertTrue(ldmcsu_count <= 20 * (num_controls + 1)-38)
def test_lcmcsu_cnot_count_real_diagonal(self):
"""
Test LdMcSpecialUnitary cx count
"""
su_2 = RXGate(0.3).to_matrix()
for num_controls in range(8, 10):
ldmcsu_circ = Ldmcsu(su_2, num_controls).definition
ldmcsu_count = get_cnot_count(ldmcsu_circ)
self.assertTrue(ldmcsu_count <= 16 * (num_controls + 1)-40)
def test_lcmcsu_op_for_exception_unitary(self):
"""
Test Ldmcsu with Z gate
"""
su2 = np.array([[-1., 0.], [0., -1.]])
num_controls = 6
ldmcsu_circ = Ldmcsu(su2, num_controls).definition
qiskit_circ = self._build_qiskit_circuit(su2, num_controls)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
def test_lcmcsu_op_for_exception_unitary_2(self):
"""
Test Ldmcsu diagonal gate
"""
su2 = np.array([[np.e**(-1j*0.3), 0], [0, np.e**(1j*0.3)]])
num_controls = 6
ldmcsu_circ = Ldmcsu(su2, num_controls).definition
qiskit_circ = self._build_qiskit_circuit(su2, num_controls)
ldmcsu_op = Operator(ldmcsu_circ).data
qiskit_op = Operator(qiskit_circ).data
self.assertTrue(np.allclose(ldmcsu_op, qiskit_op))
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mc_gate """
from unittest import TestCase
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import MCXGate
import qclib.util
from qclib.gates.ldmcu import Ldmcu
class TestLinearToffoli(TestCase):
""" Testing qclib.gate.toffoli """
def test_controlled_gate(self):
""" Testing multi controlled gate """
gate_u = unitary_group.rvs(2)
controls = QuantumRegister(4)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
Ldmcu.ldmcu(circuit, gate_u, controls, target)
state = qclib.util.get_state(circuit)
self.assertTrue(np.isclose(state[15], gate_u[0, 0]))
self.assertTrue(np.isclose(state[31], gate_u[1, 0]))
controls2 = QuantumRegister(4)
target2 = QuantumRegister(1)
circuit2 = QuantumCircuit(controls2, target2)
circuit2.x(0)
circuit2.x(1)
circuit2.x(2)
circuit2.x(3)
circuit2.x(4)
Ldmcu.ldmcu(circuit2, gate_u, controls2, target2)
state = qclib.util.get_state(circuit2)
self.assertTrue(np.isclose(state[15], gate_u[0, 1]))
self.assertTrue(np.isclose(state[31], gate_u[1, 1]))
def test_linear_toffoli3(self):
""" Testing Toffoli control 111"""
gate_x = np.array([[0, 1], [1, 0]])
controls = QuantumRegister(3)
target = QuantumRegister(1)
circuit = QuantumCircuit(controls, target)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.x(0)
Ldmcu.ldmcu(circuit, gate_x, controls, target)
state = qclib.util.get_state(circuit)
exp_state = np.zeros(16, dtype=complex)
exp_state[7] = 1
self.assertTrue(np.allclose(state, exp_state))
def test_linear_toffoli2(self):
""" Testing Toffoli control 110"""
gate_x = np.array([[0, 1], [1, 0]])
controls2 = QuantumRegister(3)
target2 = QuantumRegister(1)
circuit2 = QuantumCircuit(controls2, target2)
circuit2 = qiskit.QuantumCircuit(4)
circuit2.x(2)
circuit2.x(3)
circuit2.x(0)
state1 = qclib.util.get_state(circuit2)
controls1 = QuantumRegister(3)
target1 = QuantumRegister(1)
circuit1 = qiskit.QuantumCircuit(controls1, target1)
Ldmcu.ldmcu(circuit1, gate_x, controls1, target1, ctrl_state='110')
circuit2.compose(circuit1, circuit2.qubits, inplace=True)
state2 = qclib.util.get_state(circuit2)
self.assertTrue(np.allclose(state1, state2))
def test_linear_toffoli1(self):
""" Testing Toffoli control 100"""
gate_x = np.array([[0, 1], [1, 0]])
circuit2 = qiskit.QuantumCircuit(4)
circuit2.x(0)
state1 = qclib.util.get_state(circuit2)
controls = QuantumRegister(3)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit, gate_x, controls, target, ctrl_state='100')
circuit2.compose(circuit, circuit2.qubits, inplace=True)
state2 = qclib.util.get_state(circuit2)
self.assertTrue(np.allclose(state1, state2))
def test_linear_toffoli0(self):
""" Testing Toffoli control 000"""
gate_x = np.array([[0, 1], [1, 0]])
controls = QuantumRegister(3)
target = QuantumRegister(1)
mcgate_circuit = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(mcgate_circuit, gate_x, controls, target, ctrl_state="000")
controls_2 = QuantumRegister(3)
target_2 = QuantumRegister(1)
qiskit_circuit = QuantumCircuit(controls_2, target_2)
qiskit_circuit.append(MCXGate(len(controls_2), ctrl_state='000'),
[*controls_2, target_2])
state_qiskit = qclib.util.get_state(qiskit_circuit)
state_mcgate = qclib.util.get_state(mcgate_circuit)
self.assertTrue(np.allclose(state_qiskit, state_mcgate))
def test_mct_toffoli(self):
""" compare qiskit.mct and toffoli depth with 7 qubits """
gate_x = np.array([[0, 1], [1, 0]])
qcirc1 = qiskit.QuantumCircuit(6)
qcirc1.mcx([0, 1, 2, 3, 4], 5)
t_qcirc1 = qiskit.transpile(qcirc1, basis_gates=['u', 'cx'])
controls = QuantumRegister(5)
target = QuantumRegister(1)
qcirc2 = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(qcirc2, gate_x, controls, target)
t_qcirc2 = qiskit.transpile(qcirc2, basis_gates=['u', 'cx'])
self.assertTrue(t_qcirc2.depth() < t_qcirc1.depth())
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mc_gate """
from unittest import TestCase
import numpy as np
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.quantum_info import Operator
import qclib.util
from qclib.gates.ldmcu import Ldmcu
from qclib.gates.mcu import MCU
class TestLinearU2(TestCase):
def _get_result_unitary(self, unitary, n_ctrl_base):
exponent = n_ctrl_base - 1
param = (2**exponent - 1) / 2**exponent
values, vectors = np.linalg.eig(unitary)
gate = (
np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T
)
gate = (
gate
+ np.power(values[1] + 0j, param)
* vectors[:, [1]]
@ vectors[:, [1]].conj().T
)
return gate
def test_get_num_qubits(self):
error = 0.1
u1 = np.array([[0, 1], [1, 0]])
ldmcu_approx = MCU(u1, num_controls=10, error=error)
self.assertTrue(ldmcu_approx._get_num_base_ctrl_qubits(u1, error), 4)
def test_mcz(self):
error = 0.1
u = np.array([[1, 0], [0, -1]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
controls = QuantumRegister(base_ctrl_qubits + 2)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
def test_mcx(self):
error = 0.1
u = np.array([[0, 1], [1, 0]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
controls = QuantumRegister(base_ctrl_qubits + 2)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
def test_mcz_cnot_count(self):
error = 0.01
u = np.array([[1, 0], [0, -1]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
for n_controls in range(base_ctrl_qubits + 60, base_ctrl_qubits + 62):
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_approx = qiskit.QuantumCircuit(controls, target)
MCU.mcu(circuit_approx, u, controls, target, error)
cnot_approx = qclib.util.get_cnot_count(circ=circuit_approx)
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_og = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit_og, u, controls, target)
cnot_og = qclib.util.get_cnot_count(circ=circuit_og)
self.assertLessEqual(cnot_approx, cnot_og)
def test_mcx_cnot_count(self):
error = 0.01
u = np.array([[0, 1], [1, 0]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
for n_controls in range(base_ctrl_qubits + 60, base_ctrl_qubits + 62):
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_approx = qiskit.QuantumCircuit(controls, target)
MCU.mcu(circuit_approx, u, controls, target, error)
cnot_approx = qclib.util.get_cnot_count(circ=circuit_approx)
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_og = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit_og, u, controls, target)
cnot_og = qclib.util.get_cnot_count(circ=circuit_og)
self.assertLessEqual(cnot_approx, cnot_og)
def test_to_compare_ldmcu_and_ldmcu_approx(self):
unitary = np.array([[0, 1], [1, 0]])
error = 1e-2
ldmcu_approx_test = MCU(unitary, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(unitary, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
ldmcu_circ = QuantumCircuit(controls, target)
Ldmcu.ldmcu(ldmcu_circ, unitary, controls, target)
ldmcu_approx_circ = QuantumCircuit(controls, target)
MCU.mcu(ldmcu_approx_circ, unitary, controls, target, error)
ldmcu_op = Operator(ldmcu_circ).data
ldmcu_approx_op = Operator(ldmcu_approx_circ).data
# absolute(a - b) <= (atol + r_tol * absolute(b)
self.assertTrue(np.allclose(ldmcu_op, ldmcu_approx_op, atol=error))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.