repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qsvm_datasets import *
from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit_aqua.input import get_input_instance
from qiskit_aqua import run_algorithm
# setup aqua logging
import logging
from qiskit_aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
from qiskit import IBMQ
IBMQ.load_accounts()
feature_dim=2 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20, test_size=10, n=feature_dim, gap=0.3, PLOT_DATA=True)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)
params = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM.Kernel'
},
'backend': {'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = datapoints[0] # 0 is data, 1 is labels
result = run_algorithm(params, algo_input)
print("testing success ratio: ", result['testing_accuracy'])
print("predicted classes:", result['predicted_classes'])
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=2, PLOT_DATA=True)
# n =2 is the dimension of each data point
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
label_to_class = {label:class_name for class_name, label in class_to_label.items()}
print(class_to_label, label_to_class)
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = datapoints[0]
result = run_algorithm(params, algo_input)
print("testing success ratio: ", result['testing_accuracy'])
print("ground truth: {}".format(map_label_to_class_name(datapoints[1], label_to_class)))
print("predicted: {}".format(result['predicted_classes']))
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance
from qiskit_aqua.input import get_input_instance
from qiskit_aqua.translators.ising import maxcut, tsp
# setup aqua logging
import logging
from qiskit_aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
# ignoring deprecation errors on matplotlib
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
from qiskit import IBMQ
IBMQ.load_accounts()
# Generating a graph of 4 nodes
n=4 # Number of nodes in graph
G=nx.Graph()
G.add_nodes_from(np.arange(0,n,1))
elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
# Computing the weight matrix from the random graph
w = np.zeros([n,n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i,j,default=0)
if temp != 0:
w[i,j] = temp['weight']
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i,j]*x[i]*(1-x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print('case = ' + str(x)+ ' cost = ' + str(cost))
colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute))
qubitOp, offset = maxcut.get_maxcut_qubitops(w)
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = qubitOp
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'SPSA',
'max_trials': 300
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': 10598},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'statevector_simulator'}
}
result = run_algorithm(params, algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
# run quantum algorithm with shots
params['algorithm']['operator_mode'] = 'grouped_paulis'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params, algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
plot_histogram(result['eigvecs'][0])
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance
from qiskit_aqua.input import get_input_instance
from qiskit_aqua.translators.ising import maxcut, tsp
# setup aqua logging
import logging
from qiskit_aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
# ignoring deprecation errors on matplotlib
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
from qiskit import IBMQ
IBMQ.load_accounts()
# Generating a graph of 3 nodes
n = 3
num_qubits = n ** 2
ins = tsp.random_tsp(n)
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
colors = ['r' for node in G.nodes()]
pos = {k: v for k, v in enumerate(ins.coord)}
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
print('distance\n', ins.w)
from itertools import permutations
def brute_force_tsp(w, N):
a=list(permutations(range(1,N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j,pre_j]
pre_j = j
distance = distance + w[pre_j,0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print('order = ' + str(order) + ' Distance = ' + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(ins.w, ins.dim)
print('Best order from brute force = ' + str(best_order) + ' with total distance = ' + str(best_distance))
def draw_tsp_solution(G, order, colors, pos):
G2 = G.copy()
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G2, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
draw_tsp_solution(G, best_order, colors, pos)
qubitOp, offset = tsp.get_tsp_qubitops(ins)
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = qubitOp
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
print('energy:', result['energy'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
draw_tsp_solution(G, z, colors, pos)
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'SPSA',
'max_trials': 300
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': 10598},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'statevector_simulator'}
}
result = run_algorithm(params,algo_input)
print('energy:', result['energy'])
print('time:', result['eval_time'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
draw_tsp_solution(G, z, colors, pos)
# run quantum algorithm with shots
params['algorithm']['operator_mode'] = 'grouped_paulis'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params,algo_input)
print('energy:', result['energy'])
print('time:', result['eval_time'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
plot_histogram(result['eigvecs'][0])
draw_tsp_solution(G, z, colors, pos)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit_aqua_chemistry import AquaChemistry
from qiskit import IBMQ
IBMQ.load_accounts()
# Input dictionary to configure Qiskit AQUA Chemistry for the chemistry problem.
aqua_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': '0.7_sto-3g.hdf5'},
'operator': {'name': 'hamiltonian'},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'COBYLA'},
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'},
'backend': {'name': 'statevector_simulator'}
}
solver = AquaChemistry()
result = solver.run(aqua_chemistry_dict)
print('Ground state energy: {}'.format(result['energy']))
for line in result['printable']:
print(line)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#importing array and useful math functions
import numpy as np
#importing circuits and registers
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
#importing backends and running environment
from qiskit import BasicAer, execute
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit import register
#import Qconfig and set APIToken and API url
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
register(qx_config['APItoken'], qx_config['url'])
from battleships_engine import *
title_screen()
device = ask_for_device()
from qiskit import get_backend
backend = get_backend(device)
shipPos = ask_for_ships()
# the game variable will be set to False once the game is over
game = True
# the variable bombs[X][Y] will hold the number of times position Y has been bombed by player X+1
bomb = [ [0]*5 for _ in range(2)] # all values are initialized to zero
# set the number of samples used for statistics
shots = 1024
# the variable grid[player] will hold the results for the grid of each player
grid = [{},{}]
while (game):
# ask both players where they want to bomb, and update the list of bombings so far
bomb = ask_for_bombs( bomb )
# now we create and run the quantum programs that implement this on the grid for each player
qc = []
for player in range(2):
# now to set up the quantum program to simulate the grid for this player
# set up registers and program
q = QuantumRegister(5)
c = ClassicalRegister(5)
qc.append( QuantumCircuit(q, c) )
# add the bombs (of the opposing player)
for position in range(5):
# add as many bombs as have been placed at this position
for n in range( bomb[(player+1)%2][position] ):
# the effectiveness of the bomb
# (which means the quantum operation we apply)
# depends on which ship it is
for ship in [0,1,2]:
if ( position == shipPos[player][ship] ):
frac = 1/(ship+1)
# add this fraction of a NOT to the QASM
qc[player].u3(frac * math.pi, 0.0, 0.0, q[position])
# Finally, measure them
for position in range(5):
qc[player].measure(q[position], c[position])
# compile and run the quantum program
job = execute(qc, backend, shots=shots)
if device=='ibmqx4':
print("\nWe've now get submitted the job to the quantum computer to see what happens to the ships of each player\n(it might take a while).\n")
else:
print("\nWe've now get submitted the job to the simulator to see what happens to the ships of each player.\n")
# and extract data
for player in range(2):
grid[player] = job.result().get_counts(qc[player])
game = display_grid ( grid, shipPos, shots )
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
print("Hello! I'm a code cell")
print('Set up started...')
%matplotlib notebook
import sys
sys.path.append('game_engines')
import hello_quantum
print('Set up complete!')
initialize = []
success_condition = {}
allowed_gates = {'0': {'NOT': 3}, '1': {}, 'both': {}}
vi = [[1], False, False]
qubit_names = {'0':'the only bit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {}
allowed_gates = {'0': {}, '1': {'NOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IZ': 0.0}
allowed_gates = {'0': {'CNOT': 0}, '1': {'CNOT': 0}, 'both': {}}
vi = [[], False, False]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'NOT': 0, 'CNOT': 0}, '1': {'NOT': 0, 'CNOT': 0}, 'both': {}}
vi = [[], False, True]
qubit_names = {'0':'the bit on the left', '1':'the bit on the right'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [ ["x","0"] ]
success_condition = {"ZI":1.0}
allowed_gates = { "0":{"x":3}, "1":{}, "both":{} }
vi = [[1],True,True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0}
allowed_gates = {'0': {'x': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'the only qubit', '1':None}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':None, '1':'the other qubit'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': 0.0}
allowed_gates = {'0': {'h': 3}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'x': 3, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'], ['z', '0']]
success_condition = {'XI': 1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {}, 'both': {}}
vi = [[1], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0']]
success_condition = {'IX': 1.0}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(pi/4)', '1']]
success_condition = {'IZ': -0.7071, 'IX': -0.7071}
allowed_gates = {'0': {}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[0], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1']]
success_condition = {'ZI': 0.0, 'IZ': 0.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, False]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h','0'],['h','1']]
success_condition = {'ZZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'XZ': -1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)', '1'], ['ry(-pi/4)','0']]
success_condition = {'ZI': -0.7071, 'IZ': -0.7071}
allowed_gates = {'0': {'x': 0}, '1': {'x': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '1'], ['x','0']]
success_condition = {'XI':1, 'IX':1}
allowed_gates = {'0': {'z': 0, 'h': 0}, '1': {'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'ZI': 1.0, 'IZ': -1.0}
allowed_gates = {'0': {'cx': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1']]
success_condition = {'XI': -1.0, 'IZ': 1.0}
allowed_gates = {'0': {'h': 0, 'cz': 0}, '1': {'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['x', '1'],['h', '1']]
success_condition = { }
allowed_gates = {'0':{'cz': 2}, '1':{'cz': 2}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x', '0']]
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['h', '0'],['h', '1']]
success_condition = {'XI': -1.0, 'IX': -1.0}
allowed_gates = {'0': {}, '1': {'z':0,'cx': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = []
success_condition = {'IZ': -1.0}
allowed_gates = {'0': {'x':0,'h':0,'cx':0}, '1': {'h':0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['ry(-pi/4)','0'],['ry(-pi/4)','0'],['ry(-pi/4)','0'],['x','0'],['x','1']]
success_condition = {'ZI': -1.0,'XI':0,'IZ':0.7071,'IX':-0.7071}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0'],['h','1']]
success_condition = {'IX':1,'ZI':-1}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':3}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = [['x','1']]
success_condition = {'IZ':1.0,'ZI':-1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names,shots=2000)
initialize = []
success_condition = {}
allowed_gates = {'0': {'ry(pi/4)': 4}, '1': {}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
initialize = [['x','0']]
success_condition = {'XX': 1.0}
allowed_gates = {'0': {'x': 0, 'z': 0, 'h': 0}, '1': {'x': 0, 'z': 0, 'h': 0}, 'both': {}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'ZI': -1.0}
allowed_gates = {'0': {'bloch':1, 'ry(pi/4)': 0}, '1':{}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0'],['h','1']]
success_condition = {'ZI': -1.0,'IZ': -1.0}
allowed_gates = {'0': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['h','0']]
success_condition = {'ZZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'unbloch':0,'cz':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['ry(pi/4)','0'],['ry(pi/4)','1']]
success_condition = {'ZI': 1.0,'IZ': 1.0}
allowed_gates = {'0': {'bloch':0, 'z':0, 'ry(pi/4)': 1}, '1': {'bloch':0, 'x':0, 'ry(pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = [['x','0'],['h','1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {}, '1': {'bloch':0, 'cx':0, 'ry(pi/4)': 1, 'ry(-pi/4)': 1}, 'both': {'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
initialize = []
success_condition = {'IZ': 1.0,'IX': 1.0}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import random
def setup_variables ():
### Replace this section with anything you want ###
r = random.random()
A = r*(2/3)
B = r*(1/3)
### End of section ###
return A, B
def hash2bit ( variable, hash ):
### Replace this section with anything you want ###
if hash=='V':
bit = (variable<0.5)
elif hash=='H':
bit = (variable<0.25)
bit = str(int(bit))
### End of section ###
return bit
shots = 8192
def calculate_P ( ):
P = {}
for hashes in ['VV','VH','HV','HH']:
# calculate each P[hashes] by sampling over `shots` samples
P[hashes] = 0
for shot in range(shots):
A, B = setup_variables()
a = hash2bit ( A, hashes[0] ) # hash type for variable `A` is the first character of `hashes`
b = hash2bit ( B, hashes[1] ) # hash type for variable `B` is the second character of `hashes`
P[hashes] += (a!=b) / shots
return P
P = calculate_P()
print(P)
def bell_test (P):
sum_P = sum(P.values())
for hashes in P:
bound = sum_P - P[hashes]
print("The upper bound for P['"+hashes+"'] is "+str(bound))
print("The value of P['"+hashes+"'] is "+str(P[hashes]))
if P[hashes]<=bound:
print("The upper bound is obeyed :)\n")
else:
if P[hashes]-bound < 0.1:
print("This seems to have gone over the upper bound, but only by a little bit :S\nProbably just rounding errors or statistical noise.\n")
else:
print("!!!!! This has gone well over the upper bound :O !!!!!\n")
bell_test(P)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def initialize_program ():
qubit = QuantumRegister(2)
A = qubit[0]
B = qubit[1]
bit = ClassicalRegister(2)
a = bit[0]
b = bit[1]
qc = QuantumCircuit(qubit, bit)
return A, B, a, b, qc
def hash2bit ( variable, hash, bit, qc ):
if hash=='H':
qc.h( variable )
qc.measure( variable, bit )
initialize = []
success_condition = {'ZZ':-0.7071,'ZX':-0.7071,'XZ':-0.7071,'XX':-0.7071}
allowed_gates = {'0': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, '1': {'bloch':0, 'x':0, 'z':0, 'h':0, 'cx':0, 'ry(pi/4)': 0, 'ry(-pi/4)': 0}, 'both': {'cz':0, 'unbloch':0}}
vi = [[], True, True]
qubit_names = {'0':'A', '1':'B'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names, mode='line')
import numpy as np
def setup_variables ( A, B, qc ):
for line in puzzle.program:
eval(line)
shots = 8192
from qiskit import execute
def calculate_P ( backend ):
P = {}
program = {}
for hashes in ['VV','VH','HV','HH']:
A, B, a, b, program[hashes] = initialize_program ()
setup_variables( A, B, program[hashes] )
hash2bit ( A, hashes[0], a, program[hashes])
hash2bit ( B, hashes[1], b, program[hashes])
# submit jobs
job = execute( list(program.values()), backend, shots=shots )
# get the results
for hashes in ['VV','VH','HV','HH']:
stats = job.result().get_counts(program[hashes])
P[hashes] = 0
for string in stats.keys():
a = string[-1]
b = string[-2]
if a!=b:
P[hashes] += stats[string] / shots
return P
device = 'qasm_simulator'
from qiskit import Aer, IBMQ
try:
IBMQ.load_accounts()
except:
pass
try:
backend = Aer.get_backend(device)
except:
backend = IBMQ.get_backend(device)
print(backend.status())
P = calculate_P( backend )
print(P)
bell_test( P )
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
device = 'ibmq_16_melbourne'
from qiskit import IBMQ
IBMQ.load_accounts()
backend = IBMQ.get_backend(device)
num = backend.configuration()['n_qubits']
coupling_map = backend.configuration()['coupling_map']
print('number of qubits\n',num,'\n')
print('list of pairs of qubits that are directly connected\n',coupling_map)
if device in ['ibmqx2','ibmqx4']:
pos = { 0: (1,1), 1: (1,0), 2: (0.5,0.5), 3: (0,0), 4: (0,1) }
elif device in ['ibmqx5']:
pos = { 0: (0,0), 1: (0,1), 2: (1,1), 3: (2,1), 4: (3,1), 5: (4,1), 6: (5,1), 7: (6,1),
8: (7,1), 9: (7,0), 10: (6,0), 11: (5,0), 12: (4,0), 13: (3,0), 14: (2,0), 15: (1,0) }
elif device in ['ibmq_16_melbourne']:
pos = { 0: (0,1), 1: (1,1), 2: (2,1), 3: (3,1), 4: (4,1), 5: (5,1), 6: (6,1),
7: (7,0), 8: (6,0), 9: (5,0), 10: (4,0), 11: (3,0), 12: (2,0), 13: (1,0) }
import sys
sys.path.append('game_engines')
from universal import layout
grid = layout(num,coupling_map,pos)
grid.plot()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qp = QuantumCircuit(qr,cr)
qp.rx( np.pi/2,qr[0])
qp.cx(qr[0],qr[1])
qp.measure(qr,cr)
circuit_drawer(qp)
from qiskit import execute
from qiskit import Aer
job = execute(qp,backend=Aer.get_backend('qasm_simulator'))
results = job.result().get_counts()
print(results)
pairs = grid.matching()
print(pairs)
import random
qr = QuantumRegister(num)
cr = ClassicalRegister(num)
qp = QuantumCircuit(qr,cr)
for pair in pairs:
qp.ry( (1+2*random.random())*np.pi/4,qr[pair[0]]) # angle generated randonly between pi/4 and 3pi/4
qp.cx(qr[pair[0]],qr[pair[1]])
qp.measure(qr,cr)
from qiskit import execute
job = execute(qp,backend=IBMQ.get_backend('ibmq_qasm_simulator'))
results = job.result().get_counts()
probs = grid.calculate_probs(results)
grid.plot(probs=probs)
job = execute(qp,backend=backend)
results = job.result().get_counts()
probs = grid.calculate_probs(results)
grid.plot(probs=probs)
def mitigate(probs):
av_prob = {}
for j in range(num): # for each qubit, work out which neighbour it agrees with most
neighbours = []
for pair in grid.links:
if j in grid.links[pair]:
neighbours.append(pair)
(guessed_pair,val) = (None,1)
for pair in neighbours:
if probs[pair]<val:
guessed_pair = pair
val = probs[pair]
# then find the average probability of a 1 for the two
av_prob[j] = (probs[grid.links[guessed_pair][0]]+probs[grid.links[guessed_pair][1]])/2
# replace the probabilities for all qubits with these averages
for j in range(num):
probs[j] = av_prob[j]
return probs
probs = mitigate(probs)
grid.plot(probs=probs)
pair_labels = {}
colors = {}
for node in grid.pos:
if type(node)==str:
pair_labels[node] = node
colors[node] = (0.5,0.5,0.5)
chosen_pairs = []
m = 0
while len(chosen_pairs)<len(pairs):
m += 1
print('\nMOVE',m)
grid.plot(probs=probs,labels=pair_labels,colors=colors)
pair = str.upper(input(" > Type the name of a pair of qubits whose numbers are the same (or very similar)...\n"))
chosen_pairs.append( pair )
colors[pair] = (0.5,0.5,0.5)
for j in range(2):
colors[grid.links[pair][j]] = (0.5,0.5,0.5)
grid.plot(probs=probs,labels=pair_labels,colors=colors)
success = True
for pair in chosen_pairs:
success = success and ( (grid.links[pair] in pairs) or (grid.links[pair][::-1] in pairs) )
if success:
input("\n ** You got all the correct pairs! :) **\n\n Press any key to continue\n")
else:
input("\n ** You didn't get all the correct pairs! :( **\n\n Press any key to continue\n")
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# useful math functions
from math import pi, cos, acos, sqrt
# importing the QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, get_backend
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
M = 16 # Maximum number of physical qubits available
numberOfCoins = 8 # This number should be up to M-1, where M is the number of qubits available
indexOfFalseCoin = 6 # This should be 0, 1, ..., numberOfCoins - 1, where we use Python indexing
if numberOfCoins < 4 or numberOfCoins >= M:
raise Exception("Please use numberOfCoins between 4 and ", M-1)
if indexOfFalseCoin < 0 or indexOfFalseCoin >= numberOfCoins:
raise Exception("indexOfFalseCoin must be between 0 and ", numberOfCoins-1)
# Creating registers
# numberOfCoins qubits for the binary query string and 1 qubit for working and recording the result of quantum balance
qr = QuantumRegister(numberOfCoins+1)
# for recording the measurement on qr
cr = ClassicalRegister(numberOfCoins+1)
circuitName = "QueryStateCircuit"
queryStateCircuit = QuantumCircuit(qr, cr)
N = numberOfCoins
# Create uniform superposition of all strings of length N
for i in range(N):
queryStateCircuit.h(qr[i])
# Perform XOR(x) by applying CNOT gates sequentially from qr[0] to qr[N-1] and storing the result to qr[N]
for i in range(N):
queryStateCircuit.cx(qr[i], qr[N])
# Measure qr[N] and store the result to cr[N]. We continue if cr[N] is zero, or repeat otherwise
queryStateCircuit.measure(qr[N], cr[N])
# we proceed to query the quantum beam balance if the value of cr[0]...cr[N] is all zero
# by preparing the Hadamard state of |1>, i.e., |0> - |1> at qr[N]
queryStateCircuit.x(qr[N]).c_if(cr, 0)
queryStateCircuit.h(qr[N]).c_if(cr, 0)
# we rewind the computation when cr[N] is not zero
for i in range(N):
queryStateCircuit.h(qr[i]).c_if(cr, 2**N)
k = indexOfFalseCoin
# Apply the quantum beam balance on the desired superposition state (marked by cr equal to zero)
queryStateCircuit.cx(qr[k], qr[N]).c_if(cr, 0)
# Apply Hadamard transform on qr[0] ... qr[N-1]
for i in range(N):
queryStateCircuit.h(qr[i]).c_if(cr, 0)
# Measure qr[0] ... qr[N-1]
for i in range(N):
queryStateCircuit.measure(qr[i], cr[i])
backend = "local_qasm_simulator"
shots = 1 # We perform a one-shot experiment
results = execute(queryStateCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
for key in answer.keys():
if key[0:1] == "1":
raise Exception("Fail to create desired superposition of balanced query string. Please try again")
plot_histogram(answer)
from collections import Counter
for key in answer.keys():
normalFlag, _ = Counter(key[1:]).most_common(1)[0] #get most common label
for i in range(2,len(key)):
if key[i] != normalFlag:
print("False coin index is: ", len(key) - i - 1)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from game_engines.quantum_slot import quantum_slot_machine
quantum_slot_machine()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from IPython.display import YouTubeVideo
YouTubeVideo('U6_wSh_-EQc', width=960, height=490)
!pip install qiskit --quiet
!pip install qiskit-aer --quiet
!pip install pylatexenc --quiet
# @markdown ### **1. Import `Qiskit` and essential packages for UI demonstration** { display-mode: "form" }
from abc import abstractmethod, ABCMeta # For define pure virtual functions
from IPython.display import clear_output
from ipywidgets import Output, Button, HBox, VBox, HTML, Dropdown
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_aer import AerSimulator
# @markdown ### **2. `Board` class for essential quantum operations** { display-mode: "form" }
class Board:
def __init__(self, size=3, simulator=None):
# Initialize the quantum circuit with one qubit and classical bit for each cell
self.size = size
self.simulator = simulator
self.superposition_count = 0
self.cells = [[' ' for _ in range(size)] for _ in range(size)] # Initialize the board representation
self.qubits = QuantumRegister(size**2, 'q')
self.bits = ClassicalRegister(size**2, 'c')
self.circuit = QuantumCircuit(self.qubits, self.bits)
''' For a 3x3 board, the winning lines are:
- Horizontal lines: (0, 1, 2), (3, 4, 5), (6, 7, 8)
- Vertical lines: (0, 3, 6), (1, 4, 7), (2, 5, 8)
- Diagonal lines: (0, 4, 8), (2, 4, 6)
'''
self.winning_lines = [tuple(range(i, size**2, size)) for i in range(size)] + \
[tuple(range(i * size, (i + 1) * size)) for i in range(size)] + \
[tuple(range(0, size**2, size + 1)), tuple(range(size - 1, size**2 - 1, size - 1))]
def make_classical_move(self, row, col, player_mark, is_collapsed=False):
if self.cells[row][col] == ' ' or is_collapsed: # Check if the cell is occupied
self.cells[row][col] = player_mark
index = row * self.size + col
if player_mark == 'X': self.circuit.x(self.qubits[index])
else: self.circuit.id(self.qubits[index])
return True
return False
def make_swap_move(self, row1, col1, row2, col2, **kwargs):
if self.cells[row1][col1] != ' ' and self.cells[row2][col2] != ' ':
indices = [row1 * self.size + col1, row2 * self.size + col2]
self.circuit.swap(self.qubits[indices[0]], self.qubits[indices[1]])
self.cells[row1][col1], self.cells[row2][col2] = self.cells[row2][col2], self.cells[row1][col1]
return True
return False
def make_superposition_move(self, row, col, player_mark, **kwargs):
if self.cells[row][col] == ' ':
index = row * self.size + col
self.circuit.h(self.qubits[index])
self.cells[row][col] = player_mark + '?'
self.superposition_count += 1
return True
return False
def make_entangled_move(self, *positions, risk_level, player_mark, **kwargs):
# Entangle the quantum states of 2 or 3 cells based on the risk level
pos_count = len(positions)
if pos_count not in [2, 3] or risk_level not in [1, 2, 3, 4] or len(set(positions)) != pos_count or \
(pos_count == 2 and risk_level not in [1, 3]) or (pos_count == 3 and risk_level not in [2, 4]) or \
any(self.cells[row][col] != ' ' for row, col in positions): return False
indices = [row * self.size + col for row, col in positions]
self.circuit.h(self.qubits[indices[0]])
if pos_count == 2:
# Pairwise Entanglement with Bell state for 2 qubits:
# Lv1. |Ψ+⟩ = (∣01⟩ + ∣10⟩)/√2 | Lv3. |Φ+⟩ = (∣00⟩ + ∣11⟩)/√2
if risk_level == 1: self.circuit.x(self.qubits[indices[1]])
self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]])
else:
# Triple Entanglement with GHZ state for 3 qubits:
# Lv2. (∣010⟩ + ∣101⟩)/√2 | Lv4. (∣000⟩ + ∣111⟩)/√2
if risk_level == 2:
self.circuit.x(self.qubits[indices[1]])
self.circuit.x(self.qubits[indices[2]])
# Apply CNOT chain to entangle all 3 qubits
self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]])
self.circuit.cx(self.qubits[indices[1]], self.qubits[indices[2]])
for row, col in positions: self.cells[row][col] = player_mark + '?'
self.superposition_count += pos_count
return True
def can_be_collapsed(self):
# If superpositions/entanglement cells form a potential winning line => collapse
for line in self.winning_lines:
if all(self.cells[i // self.size][i % self.size].endswith('?') for i in line):
return True
return False
def collapse_board(self):
# Update the board based on the measurement results and apply the corresponding classical moves
self.circuit.barrier()
self.circuit.measure(self.qubits, self.bits) # Measure all qubits to collapse them to classical states
transpiled_circuit = transpile(self.circuit, self.simulator)
job = self.simulator.run(transpiled_circuit, memory=True)
counts = job.result().get_counts()
max_state = max(counts, key=counts.get)[::-1] # Get the state with the highest probability
for i in range(self.size ** 2):
row, col = divmod(i, self.size)
if self.cells[row][col].endswith('?'):
self.circuit.reset(self.qubits[i])
self.make_classical_move(row, col, 'X' if max_state[i] == '1' else 'O', is_collapsed=True)
self.superposition_count = 0
return counts
def check_win(self):
# Dynamic implementation for above logic with dynamic winning lines
for line in self.winning_lines:
# Check if all cells in the line are the same and not empty
first_cell = self.cells[line[0] // self.size][line[0] % self.size]
if first_cell not in [' ', 'X?', 'O?']:
is_same = all(self.cells[i // self.size][i % self.size] == first_cell for i in line)
if is_same: return line
# If no spaces and no superpositions left => 'Draw'
# If all cells are filled but some are still in superpositions => collapse_board
if all(self.cells[i // self.size][i % self.size] not in [' '] for i in range(self.size**2)):
if self.superposition_count <= 0: return 'Draw'
return self.superposition_count
return None
# @markdown ### **3. `QuantumT3Widgets` class for game interface**
class QuantumT3Widgets(metaclass=ABCMeta):
def __init__(self, board, current_player, quantum_move_mode):
self.board = board
self.current_player = current_player
self.quantum_move_mode = quantum_move_mode
self.log = Output(layout={'margin': '10px 0 0 0'})
self.histogram_output = Output(layout={'margin': '0 0 10px 10px'})
self.circuit_output = Output()
self.create_widgets()
def create_widgets(self):
# Create widgets for each cell and controls for game actions
self.buttons = []
for row in range(self.board.size):
self.buttons.append([])
for col in range(self.board.size):
button = Button(
description = ' ',
layout = {'width': '100px', 'height': '100px', 'border': '1px solid black'},
style = {'button_color': 'lightgray', 'font_weight': 'bold', 'text_color': 'white'}
)
button.on_click(self.create_on_cell_clicked(row, col))
self.buttons[row].append(button)
self.create_action_buttons()
self.game_info = HTML(f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>')
self.board_histogram_widget = HBox(
[VBox([VBox([HBox(row) for row in self.buttons]), self.game_info]), self.histogram_output],
layout = {'display': 'flex', 'justify_content': 'center', 'align_items': 'flex-end'}
)
display(VBox([self.board_histogram_widget, self.action_buttons, self.log, self.circuit_output]))
def create_action_buttons(self):
self.reset_btn = Button(description='Reset', button_style='danger')
self.collapse_btn = Button(description='Collapse', button_style='warning')
self.classical_btn = Button(description='Classical Move', button_style='primary')
self.swap_btn = Button(description='SWAP Move', button_style='info')
self.superposition_btn = Button(description='Superposition', button_style='success')
self.entangled_btn = Button(description='Entanglement', button_style='success')
self.entangled_options = Dropdown(options=[
('', 0), # Qubits collapse to opposite states (not consecutive)
('Lv1. PAIRWAISE: ∣Ψ+⟩ = (∣01⟩ + ∣10⟩) / √2', 1), # Qubits collapse to opposite states (not consecutive)
('Lv2. TRIPLE: GHZ_Xs = (∣010⟩ + ∣101⟩) / √2', 2),
('Lv3. PAIRWAISE: ∣Φ+⟩ = (∣00⟩ + ∣11⟩) / √2', 3), # Can form consecutive winning cells or accidentally help the opponent
('Lv4. TRIPLE: GHZ = (∣000⟩ + ∣111⟩) / √2', 4),
], value=0, disabled=True)
self.entangled_options.observe(self.update_entangled_options, names='value')
self.reset_btn.on_click(self.on_reset_btn_clicked)
self.collapse_btn.on_click(self.on_collapse_btn_clicked)
self.classical_btn.on_click(self.create_on_move_clicked('CLASSICAL'))
self.swap_btn.on_click(self.create_on_move_clicked('SWAP', 'Select 2 cells to swap their states.'))
self.superposition_btn.on_click(self.create_on_move_clicked('SUPERPOSITION', 'Select a cell to put in superposition.'))
self.entangled_btn.on_click(self.create_on_move_clicked('ENTANGLED', 'Select 2/3 cells based on risk level to entangle.'))
self.action_buttons = HBox([
self.reset_btn, self.collapse_btn, self.classical_btn, self.swap_btn,
self.superposition_btn, self.entangled_btn, self.entangled_options
])
@abstractmethod # Pure virtual functions => Must be overridden in the derived classes
def on_reset_btn_clicked(self, btn=None):
raise NotImplementedError('on_reset_btn_clicked method is not implemented.')
@abstractmethod # Pure virtual functions => Must be overridden in the derived classes
def on_collapse_btn_clicked(self, btn=None):
raise NotImplementedError('on_collapse_btn_clicked method is not implemented.')
@abstractmethod # Pure virtual functions => Must be overridden in the derived classes
def on_move_clicked(self, mode, message=''):
raise NotImplementedError('on_move_clicked method is not implemented.')
@abstractmethod # Pure virtual functions => Must be overridden in the derived classes
def on_cell_clicked(self, btn, row, col):
raise NotImplementedError('on_cell_clicked method is not implemented.')
def update_entangled_options(self, change):
with self.log:
self.entangled_options.disabled = change.new != 0
for row in self.buttons:
for button in row: button.disabled = change.new == 0
# Check if there are enough empty cells for the selected operation
empty_count = sum(cell == ' ' for row in self.board.cells for cell in row)
total_empty_required = {1: 2, 2: 3, 3: 2, 4: 3} # Total empty cells required for each risk level
if change.new == 0: return
elif empty_count < total_empty_required[change.new]:
print(f'Not enough empty cells to perform entanglement with risk level {change.new}. Please select another.')
self.entangled_options.value = 0
else:
print(f'Risk Level {change.new} ACTIVATED =>', end=' ')
if change.new in [1, 3]: print(f'Select 2 cells (qubits) for this PAIRWAISE entanglement.')
else: print(f'Select 3 cells (qubits) for this TRIPLE entanglement.')
def create_on_move_clicked(self, mode, message=''):
def on_move_clicked(btn):
with self.log:
try: self.on_move_clicked(mode, message)
except Exception as e: print(f'ERROR: {e}')
return on_move_clicked
def create_on_cell_clicked(self, row, col):
def on_cell_clicked(btn):
with self.log:
try: self.on_cell_clicked(btn, row, col)
except Exception as e: print(f'ERROR: {e}')
return on_cell_clicked
def display_circuit(self):
with self.circuit_output:
clear_output(wait=True)
display(self.board.circuit.draw('mpl', fold=-1, initial_state=True))
def display_histogram(self, counts):
with self.histogram_output:
clear_output(wait=True)
display(plot_histogram(counts, figsize=(9, 4)))
# @markdown ### **4. `QuantumT3GUI` class for game flow and interaction between players and `Board`**
class QuantumT3GUI(QuantumT3Widgets):
def __init__(self, size=3, simulator=None):
super().__init__(Board(size, simulator), 'X', 'CLASSICAL')
self.quantum_moves_selected = [] # Selected cells for operation on multi-qubit gates
self.game_over = False
def buttons_disabled(self, is_disabled=True):
for btn in self.action_buttons.children[1:]: btn.disabled = is_disabled
for row in self.buttons:
for btn in row: btn.disabled = is_disabled
def update_entire_board(self):
for row in range(self.board.size):
for col in range(self.board.size):
cell = self.board.cells[row][col]
color_map = {'X': 'dodgerblue', 'O': 'purple', '?': 'green', ' ': 'lightgray'}
self.buttons[row][col].description = cell if cell != ' ' else ' '
self.buttons[row][col].style.button_color = color_map[cell[-1]]
def clean_incompleted_quantum_moves(self):
for row, col in self.quantum_moves_selected:
if self.board.cells[row][col] == ' ':
self.buttons[row][col].description = ' '
self.buttons[row][col].style.button_color = 'lightgray'
self.quantum_moves_selected = []
def on_reset_btn_clicked(self, btn=None):
with self.log:
clear_output(wait=True)
self.board = Board(self.board.size, self.board.simulator)
self.current_player = 'X'
self.quantum_move_mode = 'CLASSICAL'
self.quantum_moves_selected = []
self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>'
self.game_over = False
self.update_entire_board()
self.buttons_disabled(False)
self.entangled_options.disabled = True
with self.histogram_output: clear_output()
with self.circuit_output: clear_output()
print('Game reset. New game started.')
def on_collapse_btn_clicked(self, btn=None):
with self.log:
if self.quantum_moves_selected:
print('Please complete the current quantum operation before measuring the board.')
return
clear_output(wait=True)
counts = self.board.collapse_board()
self.display_histogram(counts)
self.update_entire_board() # Update the board cells with the collapsed states
self.check_win()
print('Board measured and quantum states collapsed.')
def on_move_clicked(self, mode, message=''):
clear_output(wait=True)
self.quantum_move_mode = mode
self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>'
self.clean_incompleted_quantum_moves()
for row in self.buttons:
for button in row: button.disabled = mode == 'ENTANGLED'
if mode == 'ENTANGLED': self.entangled_options.value = 0
self.entangled_options.disabled = mode != 'ENTANGLED'
print(f'{mode} mode ACTIVATED' + (f': {message}' if message else ''))
def on_cell_clicked(self, btn, row, col):
if self.quantum_move_mode == 'CLASSICAL':
if self.board.make_classical_move(row, col, self.current_player):
btn.description = self.board.cells[row][col]
btn.style.button_color = 'dodgerblue' if self.current_player == 'X' else 'purple'
self.check_win()
else: print('That position is already occupied. Please choose another.')
elif self.quantum_move_mode == 'SUPERPOSITION':
if self.board.cells[row][col] == ' ':
btn.description = self.current_player + '?'
btn.style.button_color = 'green'
self.make_quantum_move_wrapper(
pos=(row, col), board_func=self.board.make_superposition_move,
success_msg='Cell is now in superposition state.')
else: print('Invalid SUPERPOSITION move. Cell must be empty.')
elif len(self.quantum_moves_selected) < 3: # Multi-qubit gates operation
self.quantum_moves_selected.append((row, col)) # Store the selected cell of operation
print(f'Cell ({row + 1}, {col + 1}) selected for {self.quantum_move_mode} move.')
if self.quantum_move_mode == 'SWAP' and len(self.quantum_moves_selected) == 2:
flat_pos = sum(self.quantum_moves_selected, ()) # Flatten the tuple to match 4 arguments in Board.make_swap_move
pos1, pos2 = self.quantum_moves_selected
self.make_quantum_move_wrapper(
pos=flat_pos, board_func=self.board.make_swap_move,
success_msg=f'SWAPPED Cell {pos1} to {pos2}', success_func=self.swap_on_board,
failure_msg='Invalid SWAP move. Both cells must be non-empty.')
elif self.quantum_move_mode == 'ENTANGLED':
if self.board.cells[row][col] == ' ':
btn.description = self.current_player + '?'
btn.style.button_color = 'green'
total_empty_required = {1: 2, 2: 3, 3: 2, 4: 3} # Total empty cells required for each risk level
if len(self.quantum_moves_selected) == total_empty_required[self.entangled_options.value]:
self.make_quantum_move_wrapper(
pos=self.quantum_moves_selected, board_func=self.board.make_entangled_move,
success_msg='These positions are now entangled and in a superposition state.',
failure_msg='Invalid ENTANGLEMENT move. Duplicated cell selection.')
else:
clear_output(wait=True)
print('Invalid ENTANGLEMENT move. A position is already occupied.')
self.quantum_moves_selected.pop() # Remove the invalid cell from the selected list
def swap_on_board(self):
row1, col1 = self.quantum_moves_selected[0][0], self.quantum_moves_selected[0][1]
row2, col2 = self.quantum_moves_selected[1][0], self.quantum_moves_selected[1][1]
# Swap the description and color of the selected cells
self.buttons[row1][col1].description, self.buttons[row2][col2].description = \
self.buttons[row2][col2].description, self.buttons[row1][col1].description
self.buttons[row1][col1].style.button_color, self.buttons[row2][col2].style.button_color = \
self.buttons[row2][col2].style.button_color, self.buttons[row1][col1].style.button_color
def make_quantum_move_wrapper(self, pos, board_func, success_msg='', success_func=None, failure_msg=''):
if board_func(*pos, risk_level=self.entangled_options.value, player_mark=self.current_player):
if success_msg: print(success_msg)
if success_func: success_func()
if self.board.can_be_collapsed():
print('Perform automatic board measurement and collapse the states.')
self.quantum_moves_selected = []
self.on_collapse_btn_clicked()
else: self.check_win()
else:
clear_output(wait=True)
if failure_msg: print(failure_msg)
self.clean_incompleted_quantum_moves()
def check_win(self):
self.quantum_moves_selected = []
while not self.game_over: # Check if the game is over after each move
self.display_circuit()
result = self.board.check_win()
if result == 'Draw': # All cells are filled but no winner yet
self.game_over = True
print("Game Over. It's a draw!")
elif type(result) == tuple: # A player wins
self.game_over = True
for cell_index in result:
row, col = divmod(cell_index, self.board.size)
self.buttons[row][col].style.button_color = 'orangered'
print(f'Game Over. {self.board.cells[row][col]} wins!')
elif type(result) == int: # All cells are filled but some are still in superpositions
print(f'All cells are filled but {result} of them still in superpositions => Keep Collapsing...')
self.quantum_moves_selected = []
self.on_collapse_btn_clicked() # Automatically collapse the board
break
else: # Switch players if no winner yet then continue the game
self.current_player = 'O' if self.current_player == 'X' else 'X' # Switch players
self.game_info.value = f'<b>Current Player: {self.current_player} / Quantum Mode: {self.quantum_move_mode}</b>'
break
if self.game_over: self.buttons_disabled(True)
game = QuantumT3GUI(size=3, simulator=AerSimulator())
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import Aer, IBMQ
import getpass, random, numpy, math
def title_screen ():
print("\n\n\n\n\n\n\n\n")
print(" ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗██╗ ██╗███╗ ███╗ ")
print(" ██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██║ ██║████╗ ████║ ")
print(" ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ██║ ██║██╔████╔██║ ")
print(" ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ██║ ██║██║╚██╔╝██║ ")
print(" ╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ╚██████╔╝██║ ╚═╝ ██║ ")
print(" ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ")
print("")
print(" ██████╗ █████╗ ████████╗████████╗██╗ ███████╗███████╗██╗ ██╗██╗██████╗ ███████╗")
print(" ██╔══██╗██╔══██╗╚══██╔══╝╚══██╔══╝██║ ██╔════╝██╔════╝██║ ██║██║██╔══██╗██╔════╝")
print(" ██████╔╝███████║ ██║ ██║ ██║ █████╗ ███████╗███████║██║██████╔╝███████╗")
print(" ██╔══██╗██╔══██║ ██║ ██║ ██║ ██╔══╝ ╚════██║██╔══██║██║██╔═══╝ ╚════██║")
print(" ██████╔╝██║ ██║ ██║ ██║ ███████╗███████╗███████║██║ ██║██║██║ ███████║")
print(" ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚══════╝")
print("")
print(" ___ ___ _ _ ")
print(" | _ ) _ _ | \ ___ __ ___ __| | ___ | |__ _ _ ")
print(" | _ \| || | | |) |/ -_)/ _|/ _ \/ _` |/ _ \| / /| || |")
print(" |___/ \_, | |___/ \___|\__|\___/\__,_|\___/|_\_\ \_,_|")
print(" |__/ ")
print("")
print(" A game played on a real quantum computer!")
print("")
print("")
randPlace = input("> Press Enter to play...\n").upper()
def ask_for_device ():
d = input("Do you want to play on the real device? (y/n)\n").upper()
if (d=="Y"):
device = IBMQ.get_backend('ibmq_5_tenerife') # if real, we use ibmqx4
else:
device = Aer.get_backend('qasm_simulator') # otherwise, we use a simulator
return device
def ask_for_ships ():
# we'll start with a 'press enter to continue' type command. But it hides a secret! If you input 'R', the positions will be chosen randomly
randPlace = input("> Press Enter to start placing ships...\n").upper()
# The variable ship[X][Y] will hold the position of the Yth ship of player X+1
shipPos = [ [-1]*3 for _ in range(2)] # all values are initialized to the impossible position -1|
# loop over both players and all three ships for each
for player in [0,1]:
# if we chose to bypass player choice and do random, we do that
if randPlace=="R":
randPos = random.sample(range(5), 3)
for ship in [0,1,2]:
shipPos[player][ship] = randPos[ship]
#print(randPos) #uncomment if you want a sneaky peek at where the ships are
else:
for ship in [0,1,2]:
# ask for a position for each ship, and keep asking until a valid answer is given
choosing = True
while (choosing):
# get player input
position = getpass.getpass("Player " + str(player+1) + ", choose a position for ship " + str(ship+1) + " (0, 1, 2, 3 or 4)\n" )
# see if the input is valid and ask for another if not
if position.isdigit(): # valid answers have to be integers
position = int(position)
if (position in [0,1,2,3,4]) and (not position in shipPos[player]): # they need to be between 0 and 5, and not used for another ship of the same player
shipPos[player][ship] = position
choosing = False
print ("\n")
elif position in shipPos[player]:
print("\nYou already have a ship there. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
return shipPos
def ask_for_bombs ( bomb ):
input("> Press Enter to place some bombs...\n")
# ask both players where they want to bomb
for player in range(2):
print("\n\nIt's now Player " + str(player+1) + "'s turn.\n")
# keep asking until a valid answer is given
choosing = True
while (choosing):
# get player input
position = input("Choose a position to bomb (0, 1, 2, 3 or 4)\n")
# see if this is a valid input. ask for another if not
if position.isdigit(): # valid answers have to be integers
position = int(position)
if position in range(5): # they need to be between 0 and 5, and not used for another ship of the same player
bomb[player][position] = bomb[player][position] + 1
choosing = False
print ("\n")
else:
print("\nThat's not a valid position. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
return bomb
def display_grid ( grid, shipPos, shots ):
# since this function has been called, the game must still be on
game = True
# look at the damage on all qubits (we'll even do ones with no ships)
damage = [ [0]*5 for _ in range(2)] # this will hold the prob of a 1 for each qubit for each player
# for this we loop over all strings of 5 bits for each player
for player in range(2):
for bitString in grid[player].keys():
# and then over all positions
for position in range(5):
# if the string has a 1 at that position, we add a contribution to the damage
# remember that the bit for position 0 is the rightmost one, and so at bitString[4]
if (bitString[4-position]=="1"):
damage[player][position] += grid[player][bitString]/shots
# give results to players
for player in [0,1]:
input("\nPress Enter to see the results for Player " + str(player+1) + "'s ships...\n")
# report damage for qubits that are ships, and which have significant damage
# ideally this would be non-zero damage, but noise means it can happen for ships that haven't been hit
# so we choose 5% as the threshold
display = [" ? "]*5
# loop over all qubits that are ships
for position in shipPos[player]:
# if the damage is high enough, display the damage
if ( damage[player][position] > 0.1 ):
if (damage[player][position]>0.9):
display[position] = "100%"
else:
display[position] = str(int( 100*damage[player][position] )) + "% "
#print(position,damage[player][position])
print("Here is the percentage damage for ships that have been bombed.\n")
print(display[ 4 ] + " " + display[ 0 ])
print(" |\ /|")
print(" | \ / |")
print(" | \ / |")
print(" | " + display[ 2 ] + " |")
print(" | / \ |")
print(" | / \ |")
print(" |/ \|")
print(display[ 3 ] + " " + display[ 1 ])
print("\n")
print("Ships with 95% damage or more have been destroyed\n")
print("\n")
# if a player has all their ships destroyed, the game is over
# ideally this would mean 100% damage, but we go for 95% because of noise again
if (damage[player][ shipPos[player][0] ]>.9) and (damage[player][ shipPos[player][1] ]>.9) and (damage[player][ shipPos[player][2] ]>.9):
print ("***All Player " + str(player+1) + "'s ships have been destroyed!***\n\n")
game = False
if (game is False):
print("")
print("=====================================GAME OVER=====================================")
print("")
return game
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# -*- coding: utf-8 -*-
"""Additional composite gates used in quantum tic tac toe"""
import numpy as np
def x_bus(qc,*bus):
"""Negates a whole bus"""
for q in bus:
qc.x(q)
def bus_or(qc,target,*busses):
"""Negates target if any of input busses is totally true, can add overall phase. Page 16 of reference"""
if len(busses)==1:
qc.cnx(qc,*busses[0],target)
elif len(busses) == 2:
#negate everything
qc.x_bus(qc,*busses[0],*busses[1],target)
qc.ry(np.pi/4,target)
qc.any_x(qc,*busses[1],target)
qc.ry(np.pi/4,target)
qc.any_x(qc,*busses[0],target)
qc.ry(-np.pi/4,target)
qc.any_x(qc,*busses[1],target)
qc.ry(-np.pi/4,target)
qc.x_bus(qc,*busses[0],*busses[1])
elif len(busses) >= 3:
#Need to negate all qubits, do so for each bus
for bus in busses:
qc.x_bus(qc,*bus)
#Then negate the target also
qc.x(target)
qc.ry(np.pi/4,target)
qc.any_x(qc,*busses[1],target)
qc.ry(np.pi/4,target)
#Recursiveness here:
qc.bus_or(qc,target,*busses[:-1])
qc.ry(-np.pi/4,target)
qc.any_x(qc,*busses[1],target)
qc.ry(-np.pi/4,target)
for bus in busses:
qc.x_bus(qc,*bus)
#No need to negate target again
def any_x(qc,*qubits):
"""Negate last qubit if any of initial qubits are 1."""
qc.x_bus(qc,*qubits)
qc.cnx(qc,*qubits)
qc.x_bus(qc,*qubits[:-1])
def cry(qc,theta,q1,q2):
"""Controlled ry"""
qc.ry(theta/2,q2)
qc.cx(q1,q2)
qc.ry(-theta/2,q2)
qc.cx(q1,q2)
def cnx(qc,*qubits):
"""Control n-1 qubits, apply 'not' to last one
Follows:
@article{PhysRevA.52.3457,
title = {Elementary gates for quantum computation},
author = {Barenco, Adriano and Bennett, Charles H. and Cleve, Richard and DiVincenzo, David P. and Margolus, Norman and Shor, Peter and Sleator, Tycho and Smolin, John A. and Weinfurter, Harald},
doi = {10.1103/PhysRevA.52.3457},
url = {https://link.aps.org/doi/10.1103/PhysRevA.52.3457}
}
Follwing Lemma 7.9, which uses Lemma 5.1 and 4.3
"""
if len(qubits) >= 3:
last = qubits[-1]
#A matrix: (made up of a and Y rotation, lemma4.3)
qc.crz(np.pi/2,qubits[-2],qubits[-1])
#cry
qc.cry(qc,np.pi/2,qubits[-2],qubits[-1])
#Control not gate
qc.cnx(qc,*qubits[:-2],qubits[-1])
#B matrix (cry again, but opposite angle)
qc.cry(qc,-np.pi/2,qubits[-2],qubits[-1])
#Control
qc.cnx(qc,*qubits[:-2],qubits[-1])
#C matrix (final rotation)
qc.crz(-np.pi/2,qubits[-2],qubits[-1])
elif len(qubits)==3:
qc.ccx(*qubits)
elif len(qubits)==2:
qc.cx(*qubits)
if __name__ == "__main__":
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import CompositeGate, available_backends, execute
q = QuantumRegister(5, "qr")
q2 = QuantumRegister(1, "qr")
print(len(q2))
c = ClassicalRegister(5, "cr")
qc = QuantumCircuit(q, c)
qc.cry = cry
qc.cnx = cnx
qc.any_x = any_x
qc.x_bus = x_bus
qc.bus_or = bus_or
#qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.h(q[-1])
qc.bus_or(qc,q[0],[q[1],q[2],q[3]],[q[4]])
qc.measure(q,c)
job_sim = execute(qc, "local_qasm_simulator",shots=100)
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))
print(qc.qasm())
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import IBMQ
from qiskit import BasicAer as Aer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
import copy
from ipywidgets import widgets
from IPython.display import display, clear_output
try:
IBMQ.load_accounts()
except:
pass
class run_game():
# Implements a puzzle, which is defined by the given inputs.
def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False):
"""
initialize
List of gates applied to the initial 00 state to get the starting state of the puzzle.
Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'.
Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit.
success_condition
Values for pauli observables that must be obtained for the puzzle to declare success.
allowed_gates
For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch').
Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times.
vi
Some visualization information as a three element list. These specify:
* which qubits are hidden (empty list if both shown).
* whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
* whether the correlation circles (the four in the middle) are shown.
qubit_names
The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names.
eps=0.1
How close the expectation values need to be to the targets for success to be declared.
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
verbose=False
"""
def get_total_gate_list():
# Get a text block describing allowed gates.
total_gate_list = ""
for qubit in allowed_gates:
gate_list = ""
for gate in allowed_gates[qubit]:
if required_gates[qubit][gate] > 0 :
gate_list += ' ' + gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")"
elif allowed_gates[qubit][gate]==0:
gate_list += ' '+gate + ' '
if gate_list!="":
if qubit=="both" :
gate_list = "\nAllowed symmetric operations:" + gate_list
else :
gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list
total_gate_list += gate_list +"\n"
return total_gate_list
def get_success(required_gates):
# Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used.
success = True
grid.get_rho()
if verbose:
print(grid.rho)
for pauli in success_condition:
success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps)
for qubit in required_gates:
for gate in required_gates[qubit]:
success = success and (required_gates[qubit][gate]==0)
return success
def get_command(gate,qubit):
# For a given gate and qubit, return the string describing the corresoinding Qiskit string.
if qubit=='both':
qubit = '1'
qubit_name = qubit_names[qubit]
for name in qubit_names.values():
if name!=qubit_name:
other_name = name
# then make the command (both for the grid, and for printing to screen)
if gate in ['x','y','z','h']:
real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+qubit_name+')'
elif gate in ['ry(pi/4)','ry(-pi/4)']:
real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])'
clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')'
elif gate in ['cz','cx','swap']:
real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])'
clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')'
return [real_command,clean_command]
clear_output()
bloch = [None]
# set up initial state and figure
grid = pauli_grid(backend=backend,shots=shots,mode=mode)
for gate in initialize:
eval( get_command(gate[0],gate[1])[0] )
required_gates = copy.deepcopy(allowed_gates)
# determine which qubits to show in figure
if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1
shown_qubit = 1
elif allowed_gates['1']=={} : # and vice versa
shown_qubit = 0
else :
shown_qubit = 2
# show figure
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']}
all_allowed_gates_raw = []
for q in ['0','1','both']:
all_allowed_gates_raw += list(allowed_gates[q])
all_allowed_gates_raw = list(set(all_allowed_gates_raw))
all_allowed_gates = []
for g in ['bloch','unbloch']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in ['x','y','z','h','cz','cx']:
if g in all_allowed_gates_raw:
all_allowed_gates.append( g )
for g in all_allowed_gates_raw:
if g not in all_allowed_gates:
all_allowed_gates.append( g )
gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates)
qubit = widgets.ToggleButtons(options=[''])
action = widgets.ToggleButtons(options=[''])
boxes = widgets.VBox([gate,qubit,action])
display(boxes)
if vi[1]:
print('\nYour quantum program so far\n')
self.program = []
def given_gate(a):
# Action to be taken when gate is chosen. This sets up the system to choose a qubit.
if gate.value:
if gate.value in allowed_gates['both']:
qubit.options = description['qubit'] + ["not required"]
qubit.value = "not required"
else:
allowed_qubits = []
for q in ['0','1']:
if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']):
allowed_qubits.append(q)
allowed_qubit_names = []
for q in allowed_qubits:
allowed_qubit_names += [qubit_names[q]]
qubit.options = description['qubit'] + allowed_qubit_names
def given_qubit(b):
# Action to be taken when qubit is chosen. This sets up the system to choose an action.
if qubit.value not in ['',description['qubit'][0],'Success!']:
action.options = description['action']+['Apply operation']
def given_action(c):
# Action to be taken when user confirms their choice of gate and qubit.
# This applied the command, updates the visualization and checks whether the puzzle is solved.
if action.value not in ['',description['action'][0]]:
# apply operation
if action.value=='Apply operation':
if qubit.value not in ['',description['qubit'][0],'Success!']:
# translate bit gates to qubit gates
if gate.value=='NOT':
q_gate = 'x'
elif gate.value=='CNOT':
q_gate = 'cx'
else:
q_gate = gate.value
if qubit.value=="not required":
q = qubit_names['1']
else:
q = qubit.value
q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required")
if q_gate in ['bloch','unbloch']:
if q_gate=='bloch':
bloch[0] = q01
else:
bloch[0] = None
else:
command = get_command(q_gate,q01)
eval(command[0])
if vi[1]:
print(command[1])
self.program.append( command[1] )
if required_gates[q01][gate.value]>0:
required_gates[q01][gate.value] -= 1
grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list())
success = get_success(required_gates)
if success:
gate.options = ['Success!']
qubit.options = ['Success!']
action.options = ['Success!']
plt.close(grid.fig)
else:
gate.value = description['gate'][0]
qubit.options = ['']
action.options = ['']
gate.observe(given_gate)
qubit.observe(given_qubit)
action.observe(given_action)
class pauli_grid():
# Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'.
def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'):
"""
backend=Aer.get_backend('qasm_simulator')
Backend to be used by Qiskit to calculate expectation values (defaults to local simulator).
shots=1024
Number of shots used to to calculate expectation values.
mode='circle'
Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line').
"""
self.backend = backend
self.shots = shots
self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)}
self.rho = {}
for pauli in self.box:
self.rho[pauli] = 0.0
for pauli in ['ZI','IZ','ZZ']:
self.rho[pauli] = 1.0
self.qr = QuantumRegister(2)
self.cr = ClassicalRegister(2)
self.qc = QuantumCircuit(self.qr, self.cr)
self.mode = mode
# colors are background, qubit circles and correlation circles, respectively
if self.mode=='line':
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
else:
self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)]
self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0])
self.ax = self.fig.add_subplot(111)
plt.axis('off')
self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w')
self.lines = {}
for pauli in self.box:
w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 )
b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 )
c = {}
c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) )
c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) )
self.lines[pauli] = {'w':w,'b':b,'c':c}
def get_rho(self):
# Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'.
bases = ['ZZ','ZX','XZ','XX']
results = {}
for basis in bases:
temp_qc = copy.deepcopy(self.qc)
for j in range(2):
if basis[j]=='X':
temp_qc.h(self.qr[j])
temp_qc.barrier(self.qr)
temp_qc.measure(self.qr,self.cr)
job = execute(temp_qc, backend=self.backend, shots=self.shots)
results[basis] = job.result().get_counts()
for string in results[basis]:
results[basis][string] = results[basis][string]/self.shots
prob = {}
# prob of expectation value -1 for single qubit observables
for j in range(2):
for p in ['X','Z']:
pauli = {}
for pp in 'IXZ':
pauli[pp] = (j==1)*pp + p + (j==0)*pp
prob[pauli['I']] = 0
for basis in [pauli['X'],pauli['Z']]:
for string in results[basis]:
if string[(j+1)%2]=='1':
prob[pauli['I']] += results[basis][string]/2
# prob of expectation value -1 for two qubit observables
for basis in ['ZZ','ZX','XZ','XX']:
prob[basis] = 0
for string in results[basis]:
if string[0]!=string[1]:
prob[basis] += results[basis][string]
for pauli in prob:
self.rho[pauli] = 1-2*prob[pauli]
def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""):
"""
rho = None
Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc.
labels = None
Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes.
bloch = None
If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit
hidden = []
Which qubits have their circles hidden (empty list if both shown).
qubit = True
Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles).
corr = True
Whether the correlation circles (the four in the middle) are shown.
message
A string of text that is displayed below the grid.
"""
def see_if_unhidden(pauli):
# For a given Pauli, see whether its circle should be shown.
unhidden = True
# first: does it act non-trivially on a qubit in `hidden`
for j in hidden:
unhidden = unhidden and (pauli[j]=='I')
# second: does it contain something other than 'I' or 'Z' when only bits are shown
if qubit==False:
for j in range(2):
unhidden = unhidden and (pauli[j] in ['I','Z'])
# third: is it a correlation pauli when these are not allowed
if corr==False:
unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I'))
return unhidden
def add_line(line,pauli_pos,pauli):
"""
For mode='line', add in the line.
line = the type of line to be drawn (X, Z or the other one)
pauli = the box where the line is to be drawn
expect = the expectation value that determines its length
"""
unhidden = see_if_unhidden(pauli)
coord = None
p = (1-self.rho[pauli])/2 # prob of 1 output
# in the following, white lines goes from a to b, and black from b to c
if unhidden:
if line=='Z':
a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 )
c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 8
coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2
elif line=='X':
a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] )
c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2
else:
a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) )
c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) )
b = ( (1-p)*a[0] + p*c[0] , (1-p)*a[1] + p*c[1] )
lw = 9
self.lines[pauli]['w'].pop(0).remove()
self.lines[pauli]['b'].pop(0).remove()
self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw )
self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw )
return coord
l = 0.9 # line length
r = 0.6 # circle radius
L = 0.98*np.sqrt(2) # box height and width
if rho==None:
self.get_rho()
# draw boxes
for pauli in self.box:
if 'I' in pauli:
color = self.colors[1]
else:
color = self.colors[2]
self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) )
# draw circles
for pauli in self.box:
unhidden = see_if_unhidden(pauli)
if unhidden:
if self.mode=='line':
self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) )
else:
prob = (1-self.rho[pauli])/2
self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) )
# update bars if required
if self.mode=='line':
if bloch in ['0','1']:
for other in 'IXZ':
px = other*(bloch=='1') + 'X' + other*(bloch=='0')
pz = other*(bloch=='1') + 'Z' + other*(bloch=='0')
z_coord = add_line('Z',pz,pz)
x_coord = add_line('X',pz,px)
for j in self.lines[pz]['c']:
self.lines[pz]['c'][j].center = (x_coord,z_coord)
self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04
px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1')
pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1')
add_line('Z',pz,pz)
add_line('X',px,px)
else:
for pauli in self.box:
for j in self.lines[pauli]['c']:
self.lines[pauli]['c'][j].radius = 0.0
if pauli in ['ZI','IZ','ZZ']:
add_line('Z',pauli,pauli)
if pauli in ['XI','IX','XX']:
add_line('X',pauli,pauli)
if pauli in ['XZ','ZX']:
add_line('ZX',pauli,pauli)
self.bottom.set_text(message)
if labels:
for pauli in box:
plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli)
self.ax.set_xlim([-3,3])
self.ax.set_ylim([0,6])
self.fig.canvas.draw()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
%matplotlib notebook
import hello_quantum
grid = hello_quantum.pauli_grid()
grid.update_grid()
for gate in [['x','1'],['h','0'],['z','0'],['h','1'],['z','1']]:
command = 'grid.qc.'+gate[0]+'(grid.qr['+gate[1]+'])'
eval(command)
grid.update_grid()
grid = hello_quantum.pauli_grid(mode='line')
grid.update_grid()
initialize = [['x', '0'],['cx', '1']]
success_condition = {'IZ': 1.0}
allowed_gates = {'0': {'h':0}, '1': {'h':0}, 'both': {'cz': 1}}
vi = [[], True, True]
qubit_names = {'0':'qubit 0', '1':'qubit 1'}
puzzle = hello_quantum.run_game(initialize, success_condition, allowed_gates, vi, qubit_names)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
"""A quantum tic tac toe running in command line"""
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import CompositeGate
from qiskit import execute
import numpy as np
from composite_gates import cry,cnx,any_x,bus_or,x_bus
class Move():
def __init__(self,indices,player,q1=None,q2=None):
"""A data structure for game moves"""
self.indices = indices
self.player=player
self.q1=q1
self.q2=q2
def __str__(self):
return str([self.indices,self.player,self.q1,self.q2])
class Board():
def __init__(self,x,y,print_info=False):
#quantum register, classical register, quantum circuit.
self.print_info=print_info
self.q = QuantumRegister(1)
self.c = ClassicalRegister(1)
self.qc = QuantumCircuit(self.q, self.c)
self.qc.cry = cry
self.qc.x_bus = x_bus
self.qc.cnx = cnx
self.qc.any_x = any_x
self.qc.bus_or = bus_or
#the dimensions of the bord
self.x=x
self.y=y
#To keep track of what is in each cell, no entanglement etc.
#Provides a graphic of the game state.
self.cells = np.empty((x,y),dtype=object)
self.cells[:]='' #Initially game is empty.
self.game_full = False
self.moves = []
def __str__(self):
return str(self.cells)
def add_move(self,indices,player):
"""Adds a move if it is non-clashing, otherwise passes it on"""
for index in indices:
if index[0] >= self.x:
return 'Index out of range'
if index[1] >= self.y:
return 'Index out of range'
status = self._add_move(indices,player)
if status=='ok':
if player==0:
char = 'X'
elif player==1:
char = 'O'
char+=str(len(self.moves))
for index in indices:
s = self.cells[index[0],index[1]]
if s: #If the cell has some text
#Add char with a comma
self.cells[index[0],index[1]]+=' '+char
else: #cell is empty so just add char
self.cells[index[0],index[1]]+=char
print(self.cells)
return status
def _add_move(self,indices,player):
"""Actually adds the move if not clashing,
otherwise passes it to _add_clashing_move"""
if len(indices)==2:
if indices[0]==indices[1]:
indices = [indices[0]]
num=len(indices)
caught_clashes = False #turns true if all moves are safe clashes
for existing_move in self.moves:
for index in indices:
if index in existing_move.indices:
if len(existing_move.indices)==1:
return 'overfull'
#This move will ALWAYS be there, if it can.
#hence, overfull.
else:
#captures any clash
caught_clashes = True
if caught_clashes:
return self._add_clashing_move(indices,player)
else:
#Reach this section if there are no clashes at all
if num==1:
self.moves.append(Move(indices,player)) #No control needed
return 'ok'
else:
self.q.size+=2 #indicator qubit, and move qubit
q1 = self.q[self.q.size-2] #To make this readable...
q2 = self.q[self.q.size-1]
self.qc.h(q1) #the last qubit in register.
self.qc.x(q2)
self.qc.cx(q1,q2)
self.moves.append(Move(indices,player,q1,q2))
return 'ok'
def _add_clashing_move(self,indices,player):
"""Adds a clashing move"""
if len(indices)==1: #100% of qubit is on one clashing spot.
#This spot COULD be occupied.
self.q.size+=1 #Only one bit needed, move happens or not.
index = indices[0]
bus = []
for existing_move in self.moves:
if index in existing_move.indices:
if index==existing_move.indices[0]:
bus.append(existing_move.q1)
elif index==existing_move.indices[1]:
bus.append(existing_move.q2)
#Now if any entry on the bus is true, our qubit is false.
self.qc.x(self.q[self.q.size-1]) # make it 1
self.qc.any_x(self.qc,*bus,self.q[self.q.size-1])
#negate is any dependents are true.
#So the new move can happen if none of the others happen.
self.moves.append(Move(indices,player,self.q[self.q.size-1]))
return 'ok'
elif len(indices)==2:
#Check first spot is not occupied, then second spot if first
#is not occupied.
self.q.size+=2 #Two bits needed (maybe) for each index.
#This can be optimized, in effect only one qubit is needed,
#and its result indicates the selected qubit.
#However, then some control qubit is needed too.
#Since there are moves that could possibly be erased completely!
bus0 = []
bus1 = []
for existing_move in self.moves:
if indices[0] in existing_move.indices:
if indices[0]==existing_move.indices[0]:
bus0.append(existing_move.q1)
elif indices[0]==existing_move.indices[1]:
bus0.append(existing_move.q2)
if indices[1] in existing_move.indices:
if indices[1]==existing_move.indices[0]:
bus1.append(existing_move.q1)
elif indices[1]==existing_move.indices[1]:
bus1.append(existing_move.q2)
#Now if any entry on the bus is true, our first qubit is false.
q1 = self.q[self.q.size-2] #a bit easier to look at (:
q2 = self.q[self.q.size-1]
if bus0:
self.qc.x(q1)
self.qc.cnx(self.qc,*bus0,q1)
else: self.qc.h(q1)
#And now the second qubit is 1 only if none of its competitors
#are 1, and likewise if the previous qubit is zero.
self.qc.x(q2)
self.qc.bus_or(self.qc,q2,bus1,[q1])
self.moves.append(Move(indices,player,q1,q2))
return 'ok'
def run(self):
"""Game loop"""
self.running=True
if self.print_info:
print("Welcome to Quantum tic tac toe!")
print("At each turn choose if to make one or two moves.")
print("Playing one move at a time is a classic tic tac toe game.")
print("At each turn the game state is printed.")
print("This constitutes a 3x3 grid (standard game!).")
print("You will see empty cells if no move was made on that part of the board.")
print("Moves made by X are marked with Xi, 'i' some number.")
print("e.g. X3 is the third move, played by X. When a move is made in a super position,")
print("You will see its label, say X3, appear in several places.")
print("This means your move is in a superposition of two classical moves!")
print("A superposition of classical moves does not guarantee that a spot is occupied,")
print("so other players can attempt to occupy it too.")
print("Then the new move will be anti-correlated with the move already in that spot.")
print("And so the game branches out into many simultaneous states.")
print("The outcome is then computed by simulation...")
print("so don't make too many quantum moves or it will take long to compute!")
print("Enter 'q' at any time to quit")
print("Enter 'end' to end the game, and compute the winner(s).")
print("Good luck!")
while self.running:
self.ask_player(0)
self.ask_player(1)
if self.game_full:
self.compute_winner()
def ask_player(self,player):
"""Ask a player for move details"""
asking=False
if self.running:
asking = True
while asking:
if player==0:
player_name = 'X'
elif player==1:
player_name = 'O'
print("PLAYER "+player_name+" :")
cells = self.question('Play in 1 or 2 cells?')
if cells=='1':
x = int(self.question('x index:'))
y = int(self.question('y index:'))
status = self.add_move([[y,x]],player)
if status == 'ok':
asking = False
else: print(status)
elif cells=='2':
x1 = int(self.question('x1 index:'))
y1 = int(self.question('y1 index:'))
x2 = int(self.question('x2 index:'))
y2 = int(self.question('y2 index:'))
status = self.add_move([[y1,x1],[y2,x2]],player)
if status == 'ok':
asking = False
else: print(status)
if not self.running:
asking=False
def question(self,text):
"""ask user a question"""
if self.running:
answer = input(text)
if answer=='q':
self.running=False
return None
elif answer=='end':
self.game_full = True
self.running = False
else:
return answer
else: return None
def compute_winner(self):
"""Find overall game winner, by finding winners of each outcome"""
self.c.size = self.q.size #Make them the same
self.qc.measure(self.q, self.c) #Measure
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.qc, backend=backend, shots=100)
sim_result = job_sim.result()
print("simulation: ", sim_result)
print(sim_result.get_counts(self.qc))
self.counts = sim_result.get_counts(self.qc)
for count in self.counts: #Takes key names
c = list(count)[:-1] #splits key '1011' => ['1','0','1','1']
c = c[::-1] #invert it so it goes 0 up...
#Ignore the last bit since I dont know how to get rid of it
#It is zero always.
#The reason it is included is that I create a quantum register and
#then start adding operations, quantum registers need at least one bit.
counter = 0
weight = self.counts[count]
empty = np.zeros((self.x,self.y),dtype=str)
for m in self.moves:
if m.player == 0:
char = 'x'
elif m.player==1:
char = 'o'
result = []
if m.q1:
result.append(c[counter])
counter+=1
if m.q2:
result.append(c[counter])
counter+=1
#print(result)
if len(result) == len(m.indices):
#print(m)
if result[0]=='1':
empty[m.indices[0][0],m.indices[0][1]] = char
if len(result)>1:
if result[1]=='1':
if result[0]=='1':
print('problem! a move appeard in two places.')
print(m)
empty[m.indices[1][0],m.indices[1][1]] = char
elif not result: #Then it was a classcal move
empty[m.indices[0][0],m.indices[0][1]] = char
xscore,oscore=self.winners(empty)
print('X wins: '+str(xscore))
print('O wins: '+str(oscore))
print('Shots: '+str(weight))
print(empty)
def winners(self,empty):
"""Compute winners of a board"""
oscore = 0
xscore = 0
for x in range(self.x):
if empty[x,1]==empty[x,0] and empty[x,2]==empty[x,1]:
if empty[x,0]=='o':
oscore+=1
elif empty[x,0]=='x':
xscore +=1
for y in range(self.y):
if empty[1,y]==empty[0,y] and empty[2,y]==empty[0,y]:
if empty[0,y]=='o':
oscore+=1
elif empty[0,y]=='x':
xscore +=1
if empty[0,0]==empty[1,1] and empty[1,1]==empty[2,2]:
if empty[0,0]=='o':
oscore+=1
elif empty[0,0]=='x':
xscore += 1
if empty[2,0]==empty[1,1] and empty[1,1]==empty[0,2]:
if empty[2,0]=='o':
oscore+=1
elif empty[2,0]=='x':
xscore += 1
return [xscore,oscore]
def _populate_board(self):
"""Automatically populate as below, for testing purposes"""
self.add_move([[2,2],[0,0]],1)
self.add_move([[1,1],[1,2]],0)
self.add_move([[1,2],[2,1]],1)
self.add_move([[2,1]],0)
self.add_move([[0,1]],1)
self.add_move([[1,0]],0)
self.add_move([[2,0]],1)
self.add_move([[2,2]],0)
self.add_move([[0,0]],1)
self.add_move([[0,2]],0)
self.add_move([[1,1]],1)
self.add_move([[1,2]],0)
if __name__=="__main__":
B= Board(3,3)
B.run()
#B._populate_board()
#a = B.compute_winner()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import json
from urllib.parse import urlencode
from urllib.request import urlopen
from qiskit import *
from qiskit.tools.monitor import job_monitor
import ipywidgets as widgets
from IPython.display import display
import threading
import os
script_dir = os.path.dirname(__file__)
IBMQ.load_accounts(hub=None)
__all__ = ['quantum_slot_machine']
def quantum_slot_machine():
"""A slot machine that uses random numbers generated
by quantum mechanical processses.
"""
qslot = widgets.VBox(children=[slot, opts])
qslot.children[0].children[1].children[7].children[1]._qslot = qslot
qslot.children[0].children[1].children[7].children[1].on_click(pull_slot)
ibmq_thread = threading.Thread(target=get_ibmq_ints, args=(qslot,))
ibmq_thread.start()
display(qslot)
def get_slot_values(backend, qslot):
if backend == 'qasm_simulator':
back = BasicAer.get_backend('qasm_simulator')
q = QuantumRegister(9, name='q')
c = ClassicalRegister(9, name='c')
qc = QuantumCircuit(q, c)
for kk in range(9):
qc.h(q[kk])
qc.measure(q, c)
job = execute(qc, backend=back, shots=1)
result = job.result()
counts = list(result.get_counts().keys())[0]
return int(counts[0:3], 2), int(counts[3:6], 2), int(counts[6:9], 2)
elif backend == 'ibmq_5_tenerife':
int1 = qslot.children[0]._stored_ints.pop(0)
int2 = qslot.children[0]._stored_ints.pop(0)
int3 = qslot.children[0]._stored_ints.pop(0)
if len(qslot.children[0]._stored_ints) == 0:
ibmq_thread = threading.Thread(target=get_ibmq_ints, args=(qslot,))
ibmq_thread.start()
return int1, int2, int3
elif backend == 'ANU QRNG':
URL = 'https://qrng.anu.edu.au/API/jsonI.php'
url = URL + '?' + urlencode({'type': 'hex16',
'length': 3,
'size': 1})
data = json.loads(urlopen(url).read().decode('ascii'))
rngs = [int(bin(int(kk, 16))[2:].zfill(8)[:3], 2)
for kk in data['data']]
return rngs[0], rngs[1], rngs[2]
else:
raise Exception('Invalid backend choice.')
def set_images(a, b, c, qslot):
slot0 = qslot.children[0].children[1].children[1]
slot1 = qslot.children[0].children[1].children[3]
slot2 = qslot.children[0].children[1].children[5]
slot0.value = qslot.children[0]._images[a]
slot1.value = qslot.children[0]._images[b]
slot2.value = qslot.children[0]._images[c]
def update_credits(change, qslot):
qslot.children[0]._credits += change
qslot.children[1].children[1].value = front_str + \
str(qslot.children[0]._credits)+back_str
def compute_payout(ints, qslot):
out = 1
#Paytable
# all sevens
if all([x == 7 for x in ints]):
value = 700
# all watermelons
elif all([x == 6 for x in ints]):
value = 200
# all strawberry
elif all([x == 5 for x in ints]):
value = 10
# all orange
elif all([x == 4 for x in ints]):
value = 20
# all lemon
elif all([x == 3 for x in ints]):
value = 60
# all grape
elif all([x == 2 for x in ints]):
value = 15
# all cherry
elif all([x == 1 for x in ints]):
value = 40
# all bell
elif all([x == 0 for x in ints]):
value = 80
# two bells
elif sum([x == 0 for x in ints])== 2:
value = 5
# two bells
elif sum([x == 0 for x in ints]) == 1:
value = 1
else:
value = 0
if value:
update_credits(value, qslot)
# if no credits left
if qslot.children[0]._credits <= 0:
qslot.children[1].children[1].value = front_str + \
"LOSE"+back_str
out = 0
return out
def pull_slot(b):
qslot = b._qslot
update_credits(-1, qslot)
b.disabled = True
set_images(-1, -1, -1, qslot)
backend = qslot.children[1].children[0].value
ints = get_slot_values(backend, qslot)
set_images(ints[0], ints[1], ints[2], qslot)
alive = compute_payout(ints, qslot)
if alive:
b.disabled = False
# generate new ibm q values
def get_ibmq_ints(qslot):
qslot.children[1].children[0].options = ['qasm_simulator', 'ANU QRNG']
qslot.children[1].children[0].value = 'qasm_simulator'
back = IBMQ.get_backend('ibmq_5_tenerife')
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q, c)
for kk in range(3):
qc.h(q[kk])
qc.measure(q, c)
job = execute(qc, backend=back, shots=300, memory=True)
qslot.children[1].children[2].clear_output()
with qslot.children[1].children[2]:
job_monitor(job)
qslot.children[0]._stored_ints = [
int(kk, 16) for kk in job.result().results[0].data.memory]
qslot.children[1].children[0].options = ['qasm_simulator', 'ibmq_5_tenerife', 'ANU QRNG']
#top
top_file = open(script_dir+"/machine/slot_top.png", "rb")
top_image = top_file.read()
slot_top = widgets.Image(
value=top_image,
format='png',
width='100%',
height='auto',
layout=widgets.Layout(margin='0px 0px 0px 0px')
)
#bottom
bottom_file = open(script_dir+"/machine/slot_bottom.png", "rb")
bottom_image = bottom_file.read()
slot_bottom = widgets.Image(
value=bottom_image,
format='png',
width='100%',
height='auto',
layout=widgets.Layout(margin='0px 0px 0px 0px')
)
#left
left_file = open(script_dir+"/machine/slot_left.png", "rb")
left_image = left_file.read()
left = widgets.Image(
value=left_image,
format='png',
width='auto',
height='auto',
margin='0px 0px 0px 0px'
)
#left
right_file = open(script_dir+"/machine/slot_right.png", "rb")
right_image = right_file.read()
right = widgets.Image(
value=right_image,
format='png',
width='auto',
height='auto',
margin='0px 0px 0px 0px'
)
#mid
mid_file = open(script_dir+"/machine/slot_middle.png", "rb")
mid_image = mid_file.read()
mid = widgets.Image(
value=mid_image,
format='png',
width='auto',
height='auto',
margin='0px 0px 0px 0px'
)
#symbols
blank_sym = open(script_dir+"/symbols/blank.png", "rb")
blank_img = blank_sym.read()
slot0 = widgets.Image(
value=blank_img,
format='png',
width='auto',
height='auto',
max_width='175px',
max_height='175px'
)
slot1 = widgets.Image(
value=blank_img,
format='png',
width='auto',
height='auto',
max_width='175px',
max_height='175px'
)
slot2 = widgets.Image(
value=blank_img,
format='png',
width='auto',
height='auto',
max_width='175px',
max_height='175px'
)
#arm
arm_upper_file = open(script_dir+"/machine/slot_handle_upper.png", "rb")
arm__upper_image = arm_upper_file.read()
arm_upper = widgets.Image(
value=arm__upper_image,
format='png',
width='auto')
arm_lower_file = open(script_dir+"/machine/slot_handle_lower.png", "rb")
arm__lower_image = arm_lower_file.read()
arm_lower = widgets.Image(
value=arm__lower_image,
format='png',
width='auto')
arm_button = widgets.Button(description='PUSH', button_style='danger',
layout=widgets.Layout(width='120px', height='auto', margin='0px 35px'))
arm_button.style.font_weight = 'bold'
arm = widgets.VBox(children=[arm_upper, arm_button, arm_lower],
layout=widgets.Layout(width='auto',
margin='0px 0px 0px 0px'))
items = [left, slot0, mid, slot1, mid, slot2, right, arm]
box_layout = widgets.Layout(display='flex',
flex_flow='row',
align_items='center',
width='auto',
margin='0px 0px 0px 0px')
slot_middle = widgets.Box(children=items, layout=box_layout)
slot = widgets.VBox(children=[slot_top, slot_middle, slot_bottom],
layout=widgets.Layout(display='flex',
flex_flow='column',
align_items='center',
width='auto',
margin='0px 0px 0px 0px'))
slot._stored_ints = []
imgs = ['waiting.png', 'bell.png', 'cherry.png', 'grape.png', 'lemon.png', 'orange.png',
'strawberry.png', 'watermelon.png', 'seven.png']
slot._images = {}
for kk, img in enumerate(imgs):
slot._images[kk-1] = open(script_dir+"/symbols/%s" % img, "rb").read()
slot._credits = 20
solver = widgets.Dropdown(
options=['qasm_simulator', 'ibmq_5_tenerife', 'ANU QRNG'],
value='qasm_simulator',
description='',
disabled=False,
layout=widgets.Layout(width='25%', padding='10px')
)
front_str = "<div style = 'background-color:#000000; height:70px; text-align:right;padding:10px' > <p style='color:#FFFFFF; font-size: 60px;margin: 10px'>"
back_str = "</p></div>"
payout = widgets.HTML(
value=front_str+str(20)+back_str,
placeholder='',
description='',
layout=widgets.Layout(width='33%', height='70px')
)
out = widgets.Output(layout=widgets.Layout(width='33%', padding='10px'))
opts = widgets.HBox(children=[solver, payout, out],
layout=widgets.Layout(width='100%',
justify_content='center',
border='2px solid black'))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qr = qiskit.QuantumRegister(1)
cr = qiskit.ClassicalRegister(1)
program = qiskit.QuantumCircuit(qr, cr)
program.measure(qr,cr)
job = qiskit.execute( program, qiskit.BasicAer.get_backend('qasm_simulator') )
print( job.result().get_counts() )
qiskit.IBMQ.load_accounts()
backend = qiskit.providers.ibmq.least_busy(qiskit.IBMQ.backends(simulator=False))
print("We'll use the least busy device:",backend.name())
job = qiskit.execute( program, backend )
print( job.result().get_counts() )
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
#Set up the quantum and classical registers, and combine them into a circuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]) #Create a superposition on the single quantum bit
qc.measure(qr[0], cr[0]) #Measure the single bit, and store its value in the clasical bit
from qiskit import register, available_backends, get_backend
#Import the config file (Qconfig.py) to retrieve the API token and API url
try:
import sys
sys.path.append('../') #Parent directory
import Qconfig
qx_config = {
'APItoken': Qconfig.APItoken,
'url': Qconfig.config['url']}
except Exception as e:
print(e)
qx_config = {
'APItoken':'YOUR_TOKEN_HERE',
'url':'https://quantumexperience.ng.bluemix.net/api'}
#Setup API
register(qx_config['APItoken'], qx_config['url'])
backend = 'ibmq_qasm_simulator' #Replace 'ibmq_qasm_simulator' with 'ibmqx5' to run on the quantum computer
shots_sim = 100 #Adjust this number as desired, with effects as described above
job_sim = execute(qc, backend, shots=shots_sim) #Run job on chosen backend for chosen number of shots
stats_sim = job_sim.result().get_counts() #Retrieve results
#Select '0' to represent 'laurel'
if '0' not in stats_sim.keys():
stats_sim['laurel'] = 0
else:
stats_sim['laurel'] = stats_sim.pop('0')
#Which leaves '1' to represent 'yanny'
if '1' not in stats_sim.keys():
stats_sim['yanny'] = 0
else:
stats_sim['yanny'] = stats_sim.pop('1')
plot_histogram(stats_sim)
from pydub import AudioSegment
from pydub.playback import play
#Import two tracks
laurel = AudioSegment.from_wav('laurel_or_yanny_audio_files/laurel.wav')
yanny = AudioSegment.from_wav('laurel_or_yanny_audio_files/yanny.wav')
play(laurel) #Listen to the laurel-specific track
play(yanny) #Listen to the yanny-specific track
#Modify the volumes based on the results of the experiment
laurel = laurel + ((100*stats_sim['laurel']/shots_sim)-50) #Laurel
yanny = yanny + ((100*stats_sim['yanny']/shots_sim)-50) #Yanny
#Mix the two together and play the result
mixed = laurel.overlay(yanny)
play(mixed)
mixed.export('laurel_or_yanny_audio_files/quantumLaurelYanny.wav', format='wav')
print("Installed packages are as the following")
!python --version
print()
!conda list 'qiskit|IBMQuantumExperience|numpy|scipy'
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# begin with importing essential libraries for IBM Q
from qiskit import IBMQ, BasicAer
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
# set up Quantum Register and Classical Register for 3 qubits
q = QuantumRegister(3)
c = ClassicalRegister(3)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
def answer(result):
for key in result.keys():
state = key
print('The Quantum 8-ball says:')
if state == '000':
print('It is certain.')
elif state == '001':
print('Without a doubt.')
elif state == '010':
print('Yes - definitely.')
elif state == '011':
print('Most likely.')
elif state == '100':
print("Don't count on it.")
elif state == '101':
print('My reply is no.')
elif state == '110':
print('Very doubtful.')
else:
print('Concentrate and ask again.')
from qiskit import execute
job = execute(qc, backend=BasicAer.get_backend('qasm_simulator'), shots=1)
result = job.result().get_counts(qc)
answer(result)
# load IBM Q account
IBMQ.load_accounts()
# define the least busy device
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
print("The least busy device:",backend.name())
job = execute(qc, backend=backend, shots=1)
result = job.result().get_counts(qc)
answer(result)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
# set up registers and program
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
# rightmost eight (qu)bits have ')' = 00101001
qc.x(qr[0])
qc.x(qr[3])
qc.x(qr[5])
# second eight (qu)bits have superposition of
# '8' = 00111000
# ';' = 00111011
# these differ only on the rightmost two bits
qc.h(qr[9]) # create superposition on 9
qc.cx(qr[9],qr[8]) # spread it to 8 with a CNOT
qc.x(qr[11])
qc.x(qr[12])
qc.x(qr[13])
# measure
for j in range(16):
qc.measure(qr[j], cr[j])
from qiskit import register, available_backends, get_backend
#import Qconfig and set APIToken and API url
try:
import sys
sys.path.append("../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except Exception as e:
print(e)
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
#set api
register(qx_config['APItoken'], qx_config['url'])
backend = "ibmq_qasm_simulator"
shots_sim = 128
job_sim = execute(qc, backend, shots=shots_sim)
stats_sim = job_sim.result().get_counts()
plot_histogram(stats_sim)
import matplotlib.pyplot as plt
%matplotlib inline
plt.rc('font', family='monospace')
def plot_smiley (stats, shots):
for bitString in stats:
char = chr(int( bitString[0:8] ,2)) # get string of the leftmost 8 bits and convert to an ASCII character
char += chr(int( bitString[8:16] ,2)) # do the same for string of rightmost 8 bits, and add it to the previous character
prob = stats[bitString] / shots # fraction of shots for which this result occurred
# create plot with all characters on top of each other with alpha given by how often it turned up in the output
plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300)
if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots)
print(str(prob)+"\t"+char)
plt.axis('off')
plt.show()
plot_smiley(stats_sim, shots_sim)
backends = available_backends()
backend = get_backend('ibmqx5')
print('Status of ibmqx5:',backend.status)
if backend.status["operational"] is True:
print("\nThe device is operational, so we'll submit the job.")
shots_device = 1000
job_device = execute(qc, backend, shots=shots_device)
stats_device = job_device.result().get_counts()
else:
print("\nThe device is not operational. Try again later.")
plot_smiley(stats_device, shots_device)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import getpass, time
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
try:
register(qx_config['APItoken'], qx_config['url'])
print('\nYou have access to great power!')
print(available_backends({'local': False, 'simulator': False}))
except:
print('Something went wrong.\nDid you enter a correct token?')
backend = least_busy(available_backends({'simulator': False, 'local': False}))
print("The least busy backend is " + backend)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
job_exp = execute(qc, backend=backend, shots=1024, max_credits=3)
lapse = 0
interval = 30
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
plot_histogram(job_exp.result().get_counts(qc))
print('You have made entanglement!')
circuit_drawer(qc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
YEAST = "----------------------------------MM----------------------------"
PROTOZOAN = "--MM---------------M------------MMMM---------------M------------"
BACTERIAL = "---M---------------M------------MMMM---------------M------------"
import sys
import numpy as np
import math
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import execute
def encode_bitstring(bitstring, qr, cr, inverse=False):
"""
create a circuit for constructing the quantum superposition of the bitstring
"""
n = math.ceil(math.log2(len(bitstring))) + 1 #number of qubits
assert n > 2, "the length of bitstring must be at least 2"
qc = QuantumCircuit(qr, cr)
#the probability amplitude of the desired state
desired_vector = np.array([ 0.0 for i in range(2**n) ]) #initialize to zero
amplitude = np.sqrt(1.0/2**(n-1))
for i, b in enumerate(bitstring):
pos = i * 2
if b == "1" or b == "M":
pos += 1
desired_vector[pos] = amplitude
if not inverse:
qc.initialize(desired_vector, [ qr[i] for i in range(n) ] )
qc.barrier(qr)
else:
qc.initialize(desired_vector, [ qr[i] for i in range(n) ] ).inverse() #invert the circuit
for i in range(n):
qc.measure(qr[i], cr[i])
print()
return qc
n = math.ceil(math.log2(len(YEAST))) + 1 #number of qubits
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
qc_yeast = encode_bitstring(YEAST, qr, cr)
qc_protozoan = encode_bitstring(PROTOZOAN, qr, cr)
qc_bacterial = encode_bitstring(BACTERIAL, qr, cr)
circs = {"YEAST": qc_yeast, "PROTOZOAN": qc_protozoan, "BACTERIAL": qc_bacterial}
inverse_qc_yeast = encode_bitstring(YEAST, qr, cr, inverse=True)
inverse_qc_protozoan = encode_bitstring(PROTOZOAN, qr, cr, inverse=True)
inverse_qc_bacterial = encode_bitstring(BACTERIAL, qr, cr, inverse=True)
inverse_circs = {"YEAST": inverse_qc_yeast, "PROTOZOAN": inverse_qc_protozoan, "BACTERIAL": inverse_qc_bacterial}
from qiskit import IBMQ, BasicAer
key = "PROTOZOAN" #the name of the code used as key to find similar ones
# use local simulator
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
combined_circs = {}
count = {}
most_similar, most_similar_score = "", -1.0
for other_key in inverse_circs:
if other_key == key:
continue
combined_circs[other_key] = circs[key] + inverse_circs[other_key] #combined circuits to look for similar codes
job = execute(combined_circs[other_key], backend=backend,shots=shots)
st = job.result().get_counts(combined_circs[other_key])
if "0"*n in st:
sim_score = st["0"*n]/shots
else:
sim_score = 0.0
print("Similarity score of",key,"and",other_key,"is",sim_score)
if most_similar_score < sim_score:
most_similar, most_similar_score = other_key, sim_score
print("[ANSWER]", key,"is most similar to", most_similar)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
from qiskit.providers.aer.noise.errors.standard_errors import amplitude_damping_error
from qiskit.providers.aer.noise.errors.standard_errors import phase_damping_error
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.characterization.coherence import T1Fitter, T2StarFitter, T2Fitter
from qiskit.ignis.characterization.coherence import t1_circuits, t2_circuits, t2star_circuits
# 12 numbers ranging from 10 to 1000, logarithmically spaced
# extra point at 1500
num_of_gates = np.append((np.logspace(1, 3, 12)).astype(int), np.array([1500]))
gate_time = 0.1
# Select the qubits whose T1 are to be measured
qubits = [0]
# Generate experiments
circs, xdata = t1_circuits(num_of_gates, gate_time, qubits)
# Set the simulator with amplitude damping noise
t1 = 25.0
gamma = 1 - np.exp(-gate_time/t1)
error = amplitude_damping_error(gamma)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 200
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponential
# The correct answers are a=1, and c=0, and t1=25/15 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t1 = t1*1.2
initial_a = 1.0
initial_c = 0.0
fit = T1Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t1, initial_c],
fit_bounds=([0, 0, -1], [2, initial_t1*2, 1]))
fit.plot(0)
# 50 points linearly spaced in two regions (fine and coarse)
# 30 from 10->150, 20 from 160->450
num_of_gates = np.append((np.linspace(10, 150, 30)).astype(int), (np.linspace(160,450,20)).astype(int))
gate_time = 0.1
# Select the qubits whose T2* are to be measured
qubits = [0]
# Generate experiments
circs, xdata, osc_freq = t2star_circuits(num_of_gates, gate_time, qubits, nosc=5)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an oscillator
# The correct answers are a=0.5, f=osc_freq, phi=0, c=0.5, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
initial_f = osc_freq
initial_phi = -np.pi/20
fit = T2StarFitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_f, initial_phi, initial_c],
fit_bounds=([-0.5, 0, 0, -np.pi, -0.5],
[1.5, 2*t2, 2*osc_freq, np.pi, 1.5]))
fit.plot(0)
# 50 points linearly spaced to 300
num_of_gates = (np.linspace(10, 300, 50)).astype(int)
gate_time = 0.1
# Select the qubits whose T2 are to be measured
qubits = [0]
# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
fit = T2Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_c],
fit_bounds=([-0.5, 0, -0.5],
[1.5, 2*t2, 1.5]))
fit.plot(0)
num_of_gates = (np.linspace(1, 30, 30)).astype(int)
gate_time = 0.1
# Select the qubits whose T2 are to be measured
qubits = [0]
# Echo parameters
n_echos = 5
alt_phase_echo = True
# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits, n_echos, alt_phase_echo)
backend = qiskit.Aer.get_backend('qasm_simulator')
# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location
initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
fit = T2Fitter(backend_result, xdata, qubits,
fit_p0=[initial_a, initial_t2, initial_c],
fit_bounds=([-0.5, 0, -0.5],
[1.5, 2*t2, 1.5]))
fit.plot(0)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
CompleteMeasFitter, MeasurementFilter)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=1
max_qubits=3
skip_qubits=1
max_circuits=3
num_shots=1000
use_XX_YY_ZZ_gates = True
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
gate_counts_plots = True
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
import os,json
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
import time
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "Hamiltonian Simulation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
num_gates = 0
depth = 0
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits and subcircuits for display
QC_ = None
XX_ = None
YY_ = None
ZZ_ = None
XXYYZZ_ = None
# import precalculated data to compare against
filename = os.path.join("precalculated_data.json")
with open(filename, 'r') as file:
data = file.read()
precalculated_data = json.loads(data)
############### Circuit Definition
def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z):
'''
Construct a Qiskit circuit for Hamiltonian Simulation
:param n_spins:The number of spins to simulate
:param K: The Trotterization order
:param t: duration of simulation
:return: return a Qiskit circuit for this Hamiltonian
'''
num_qubits = n_spins
secret_int = f"{K}-{t}"
# allocate qubits
qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins);
qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}")
tau = t / K
# start with initial state of 1010101...
for k in range(0, n_spins, 2):
qc.x(qr[k])
qc.barrier()
# loop over each trotter step, adding gates to the circuit defining the hamiltonian
for k in range(K):
# the Pauli spin vector product
[qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)]
[qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)]
qc.barrier()
# Basic implementation of exp(i * t * (XX + YY + ZZ))
if _use_XX_YY_ZZ_gates:
# XX operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# YY operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# ZZ operation on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# Use an optimal XXYYZZ combined operator
# See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf
else:
# optimized XX + YY + ZZ operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j % 2, n_spins - 1, 2):
qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
qc.barrier()
# measure all the qubits used in the circuit
for i_qubit in range(n_spins):
qc.measure(qr[i_qubit], cr[i_qubit])
# save smaller circuit example for display
global QC_
if QC_ == None or n_spins <= 6:
if n_spins < 9: QC_ = qc
return qc
############### XX, YY, ZZ Gate Implementations
# Simple XX gate on q0 and q1 with angle 'tau'
def xx_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate")
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
# save circuit example for display
global XX_
XX_ = qc
return qc
# Simple YY gate on q0 and q1 with angle 'tau'
def yy_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate")
qc.s(qr[0])
qc.s(qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.sdg(qr[0])
qc.sdg(qr[1])
# save circuit example for display
global YY_
YY_ = qc
return qc
# Simple ZZ gate on q0 and q1 with angle 'tau'
def zz_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate")
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
# save circuit example for display
global ZZ_
ZZ_ = qc
return qc
# Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau'
def xxyyzz_opt_gate(tau):
alpha = tau; beta = tau; gamma = tau
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt")
qc.rz(3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(3.1416*gamma - 3.1416/2, qr[0])
qc.ry(3.1416/2 - 3.1416*alpha, qr[1])
qc.cx(qr[0], qr[1])
qc.ry(3.1416*beta - 3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(-3.1416/2, qr[0])
# save circuit example for display
global XXYYZZ_
XXYYZZ_ = qc
return qc
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(num_qubits):
# we have precalculated the correct distribution that a perfect quantum computer will return
# it is stored in the json file we import at the top of the code
correct_dist = precalculated_data[f"Qubits - {num_qubits}"]
return correct_dist
num_state_qubits=1 #(default) not exposed to users
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
# validate parameters (smallest circuit is 2 qubits)
max_qubits = max(2, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
global _use_XX_YY_ZZ_gates
_use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates
if _use_XX_YY_ZZ_gates:
print("... using unoptimized XX YY ZZ gates")
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# reset random seed
np.random.seed(0)
# determine number of circuits to execute for this group
num_circuits = max(1, max_circuits)
print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}")
numckts.append(num_circuits)
# parameters of simulation
#### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA #########
w = precalculated_data['w'] # strength of disorder
k = precalculated_data['k'] # Trotter error.
# A large Trotter order approximates the Hamiltonian evolution better.
# But a large Trotter order also means the circuit is deeper.
# For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation.
t = precalculated_data['t'] # time of simulation
#######################################################################
for circuit_id in range(num_circuits):
print("*********************************************")
print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}")
#creation of Quantum Circuit.
ts = time.time()
h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1]
h_z = precalculated_data['h_z'][:num_qubits]
qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z)
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
#Correct distribution to compare with counts
correct_dist = analyzer(num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if _use_XX_YY_ZZ_gates:
print("\nXX, YY, ZZ =")
print(XX_); print(YY_); print(ZZ_)
else:
print("\nXXYYZZ_opt =")
print(XXYYZZ_)
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
CompleteMeasFitter, MeasurementFilter)
# Generate the calibration circuits
qr = qiskit.QuantumRegister(5)
meas_calibs, state_labels = complete_meas_cal(qubit_list=[2,3,4], qr=qr, circlabel='mcal')
state_labels
# Execute the calibration circuits without noise
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
# The calibration matrix without noise is the identity matrix
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Generate a noise model for the 5 qubits
noise_model = noise.NoiseModel()
for qi in range(5):
read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]])
noise_model.add_readout_error(read_err, [qi])
# Execute the calibration circuits
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
# Calculate the calibration matrix with the noise model
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Plot the calibration matrix
meas_fitter.plot_calibration()
# What is the measurement fidelity?
print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity())
# What is the measurement fidelity of Q0?
print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity(
label_list = [['000','001','010','011'],['100','101','110','111']]))
# Make a 3Q GHZ state
cr = ClassicalRegister(3)
ghz = QuantumCircuit(qr, cr)
ghz.h(qr[2])
ghz.cx(qr[2], qr[3])
ghz.cx(qr[3], qr[4])
ghz.measure(qr[2],cr[0])
ghz.measure(qr[3],cr[1])
ghz.measure(qr[4],cr[2])
job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model)
results = job.result()
# Results without mitigation
raw_counts = results.get_counts()
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes classes
import qiskit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
#Generate RB circuits (2Q RB)
#number of qubits
nQ=2
rb_opts = {}
#Number of Cliffords in the sequence
rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175]
#Number of seeds (random sequences)
rb_opts['nseeds'] = 5
#Default pattern
rb_opts['rb_pattern'] = [[0,1]]
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
print(rb_circs[0][0])
# Create a new circuit without the measurement
qc = qiskit.QuantumCircuit(*rb_circs[0][-1].qregs,*rb_circs[0][-1].cregs)
for i in rb_circs[0][-1][0:-nQ]:
qc._attach(i)
# The Unitary is an identity (with a global phase)
backend = qiskit.Aer.get_backend('unitary_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
basis_gates_str = ','.join(basis_gates)
job = qiskit.execute(qc, backend=backend, basis_gates=basis_gates_str)
print(np.around(job.result().get_unitary(),3))
# Run on a noisy simulator
noise_model = NoiseModel()
# Depolarizing_error
dp = 0.002
noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 1), ['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(depolarizing_error(dp, 2), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
qobj_list = []
# Create the RB fitter
rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern'])
for rb_seed,rb_circ_seed in enumerate(rb_circs):
qobj = qiskit.compile(rb_circ_seed,
backend=backend,
basis_gates=basis_gates_str)
job = backend.run(qobj, noise_model=noise_model)
qobj_list.append(qobj)
# Add data to the fitter
rb_fit.add_data(job.result())
print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc']))
plt.figure(figsize=(8, 6))
ax = plt.subplot(1, 1, 1)
# Plot the essence by calling plot_rb_data
rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(nQ), fontsize=18)
plt.show()
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0])
for i in range(len(basis_gates)):
print("Number of %s gates per Clifford: %f"%(basis_gates[i],
np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]])))
# Prepare lists of the number of qubits and the errors
ngates = np.zeros(7)
ngates[0:3] = gates_per_cliff[0][0:3]
ngates[3:6] = gates_per_cliff[1][0:3]
ngates[6] = gates_per_cliff[0][3]
gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int)
gate_errs = np.zeros(len(gate_qubits))
gate_errs[[1,4]] = dp/2 #convert from depolarizing error to epg (1Q)
gate_errs[[2,5]] = 2*dp/2 #convert from depolarizing error to epg (1Q)
gate_errs[6] = dp*3/4 #convert from depolarizing error to epg (2Q)
#Calculate the predicted epc
pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs)
print("Predicted 2Q Error per Clifford: %e"%pred_epc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import itertools
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import Aer
import qiskit.ignis.verification.tomography as tomo
from qiskit.quantum_info import state_fidelity
I = np.array([[1,0],[0,1]])
X = np.array([[0,1],[1,0]])
Y = np.array([[0,-1j],[1j,0]])
Z = np.array([[1,0],[0,-1]])
def HS_product(A,B):
return 0.5*np.trace(np.conj(B).T @ A)
PX0 = 0.5*np.array([[1, 1], [1, 1]])
PX1 = 0.5*np.array([[1, -1], [-1, 1]])
PY0 = 0.5*np.array([[1, -1j], [1j, 1]])
PY1 = 0.5*np.array([[1, 1j], [-1j, 1]])
PZ0 = np.array([[1, 0], [0, 0]])
PZ1 = np.array([[0, 0], [0, 1]])
projectors = [PX0, PX1, PY0, PY1, PZ0, PZ1]
M = np.array([p.flatten() for p in projectors])
M
M_dg = np.conj(M).T
linear_inversion_matrix = np.linalg.inv(M_dg @ M) @ M_dg
projectors_2 = [np.kron(p1, p2) for (p1, p2) in itertools.product(projectors, repeat = 2)]
M_2 = np.array([p.flatten() for p in projectors_2])
M_dg_2 = np.conj(M_2).T
linear_inversion_matrix_2 = np.linalg.inv(M_dg_2 @ M_2) @ M_dg_2
q2 = QuantumRegister(2)
bell = QuantumCircuit(q2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
bell.qasm()
qst_bell = tomo.state_tomography_circuits(bell, q2)
job = qiskit.execute(qst_bell, Aer.get_backend('qasm_simulator'), shots=5000)
statefit = tomo.StateTomographyFitter(job.result(), qst_bell)
statefit.data
p, M, weights = statefit._fitter_data(True, 0.5)
M_dg = np.conj(M).T
linear_inversion_matrix = np.linalg.inv(M_dg @ M) @ M_dg
rho_bell = linear_inversion_matrix @ p
rho_bell = np.reshape(rho_bell, (4, 4))
print(rho_bell)
job = qiskit.execute(bell, Aer.get_backend('statevector_simulator'))
psi_bell = job.result().get_statevector(bell)
F_bell = state_fidelity(psi_bell, rho_bell)
print('Fit Fidelity linear inversion =', F_bell)
rho_cvx_bell = statefit.fit(method='cvx')
F_bell = state_fidelity(psi_bell, rho_cvx_bell)
print('Fit Fidelity CVX fit =', F_bell)
rho_mle_bell = statefit.fit(method='lstsq')
F_bell = state_fidelity(psi_bell, rho_mle_bell)
print('Fit Fidelity MLE fit =', F_bell)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit import register, available_backends, get_backend
#import Qconfig and set APIToken and API url
import sys
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
#set api
register(qx_config['APItoken'], qx_config['url'])
import math, scipy, copy, time
import numpy as np
def AddDelay (script,q,num,delay):
for _ in range(delay):
for address in range(num):
script.iden(q[address])
def AddCnot(script,q,control,target,device):
# set the coupling map
# b in coupling_map[a] means a CNOT with control qubit a and target qubit b can be implemented
# this is essentially just copy and pasted from
# https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx3
# https://github.com/IBM/qiskit-qx-info/tree/master/backends/ibmqx5
# but with a few stylistic changes
coupling_map = {}
coupling_map['ibmqx3'] = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 5: [], 6: [7, 11], 7: [10],
8: [7], 9: [10, 8], 10:[], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14:[], 15: [0, 14]}
coupling_map['ibmqx5'] = {0:[],1:[0,2], 2:[3], 3:[4, 14], 4:[], 5:[4], 6:[5,7,11], 7:[10],
8:[7], 9:[8, 10], 10:[], 11:[10], 12:[5, 11, 13], 13:[4, 14], 14:[], 15:[0, 2, 14]}
simulator = (device not in ['ibmqx3','ibmqx5'])
# if simulator, just do the CNOT
if simulator:
script.cx(q[control], q[target])
# same if the coupling map allows it
elif target in coupling_map[device][control]:
script.cx(q[control], q[target])
# if it can be done the other way round we conjugate with Hadamards
elif ( control in coupling_map[device][target] ):
script.h(q[control])
script.h(q[target])
script.cx(q[target], q[control])
script.h(q[control])
script.h(q[target])
else:
print('Qubits ' + str(control) + ' and ' + str(target) + ' cannot be entangled.')
def GetAddress (codeQubit,offset,simulator):
if (simulator):
address = 2*codeQubit + offset
else:
address = (5-2*codeQubit-offset)%16
#address = (6+2*codeQubit+offset)%16 # this can be used to go clockwise instead
return address
def RunRepetition(bit,d,device,delay,totalRuns):
# set the number of shots to use on the backend
shots = 8192
# determine whether a simulator is used
simulator = (device not in ['ibmqx3','ibmqx5'])
# if the simulator is used, we declare the minimum number of qubits required
if (simulator):
num = 2*d
# for the real device there are always 16
else:
num = 16
repetitionScript = [] # we create a batch job of totalRuns identical runs
for run in range(totalRuns):
# set up registers and program
q = QuantumRegister(num)
c = ClassicalRegister(num)
repetitionScript.append( QuantumCircuit(q, c) )
# now we insert all the quantum gates to be applied
# a barrier is inserted between each section of the code to prevent the complilation doing things we don't want it to
# the stored bit is initialized by repeating it across all code qubits same state
# since qubits are automatically initialized as 0, we just need to do Xs if b=1
if (bit==1):
for codeQubit in range(d):
repetitionScript[run].x( q[GetAddress(codeQubit,0,simulator)] )
# also do it for the single qubit on the end for comparision
repetitionScript[run].x( q[GetAddress(d-1,1,simulator)] )
repetitionScript[run].barrier()
# if the code is simulated add rotations for error like effects (and a barrier)
AddDelay(repetitionScript[run],q,num,delay)
# we then start the syndrome measurements by doing CNOTs between each code qubit and the next ancilla along the line
for codeQubit in range(d-1):
AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,1,simulator),device)
repetitionScript[run].barrier()
# if the code is simulated add rotations for error like effects (and a barrier)
AddDelay(repetitionScript[run],q,num,delay)
# next we perform CNOTs between each code qubit and the previous ancilla along the line
for codeQubit in range(1,d):
AddCnot(repetitionScript[run],q,GetAddress(codeQubit,0,simulator),GetAddress(codeQubit,-1,simulator),device)
repetitionScript[run].barrier()
# if the code is simulated add rotations for error like effects (and a barrier)
AddDelay(repetitionScript[run],q,num,delay)
# all qubits are then measured
for address in range(num):
repetitionScript[run].measure(q[address], c[address])
# noise is turned on if simulator is used
#repetitionScript[run].noise(int(simulator))
# run the job (if the device is available)
backends = available_backends()
backend = get_backend(device)
print('Status of '+device+':',backend.status)
dataNeeded = True
while dataNeeded==True:
if backend.status["available"] is True:
print("\nThe device is available, so the following job is being submitted.\n")
print(repetitionScript[1].qasm())
shots_device = 1000
job = execute(repetitionScript, backend, shots=shots, skip_translation=True)
results = []
for run in range(totalRuns):
results.append( job.result().get_counts(repetitionScript[run]) )
dataNeeded = False
else:
print("\nThe device is not available, so we will wait for a while.")
time.sleep(600)
# the raw data states the number of runs for which each outcome occurred
# we convert this to fractions before output.
for run in range(totalRuns):
for key in results[run].keys():
results[run][key] = results[run][key]/shots
# return the results
return results
def AddProbToResults(prob,string,results):
if string not in results.keys():
results[string] = 0
results[string] += prob
def CalculateError(encodedBit,results,table):
# total prob of error will be caculated by looping over all strings
# some will end up being ignored, so we'll also need to renormalize
error = 0
renorm = 1
# all strings from our sample are looped over
for string in results.keys():
# we find the probability P(string|encodedBit) from the lookup table
right = 0
if string in table[encodedBit].keys():
right = table[encodedBit][string]
# as is the probability P(string|!encodedBit)
wrong = 0
if string in table[(encodedBit+1)%2].keys():
wrong = table[(encodedBit+1)%2][string]
# if this is a string for which P(string|!encodedBit)>P(string|encodedBit), the decoding fails
# the probabilty for this sample is then added to the error
if (wrong>right):
error += results[string]
# if P(string|!encodedBit)=P(string|encodedBit)=0 we have no data to decode, so we should ignore this sample
# otherwise if P(string|!encodedBit)=P(string|encodedBit), the decoder randomly chooses between them
# P(failure|string) is therefore 0.5 in this case
elif (wrong==right):
if wrong==0:
renorm -= results[string]
else:
error += 0.5*results[string]
# otherwise the decoding succeeds, and we don't care about that
if renorm==0:
error = 1
else:
error = error/renorm
return error
def GetData(device,minSize,maxSize,totalRuns,delay):
# loop over code sizes that will fit on the chip (d=3 to d=8)
for d in range(minSize,maxSize+1):
print("\n\n**d = " + str(d) + "**")
# get data for each encoded bit value
for bit in range(2):
# run the job and put results in resultsRaw
results = RunRepetition(bit,d,device,delay,totalRuns)
delayString = ""
if delay>0:
delayString = '_delay='+str(delay)
for run in range(totalRuns):
f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt', 'w')
f.write( str(results[run]) )
f.close()
def ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay):
# determine whether a simulator is used
simulator = (device not in ['ibmqx3','ibmqx5'])
# initialize list used to store the calculated means and variances for results from the codes
codeResults = [[[0]*4 for _ in range(j)] for j in range(minSize,maxSize+1)]
singleResults = [[[0]*2 for _ in range(16)] for _ in range(minSize,maxSize+1)]
# singleResults[d-minSize][j][0] is the probability of state 1 for qubit j when used in a code of distance d
# singleResults[d-minSize][j][1] is the variance for the above
# the results will show that the case of partial decoding requires more analysis
# for this reason we will also output combinedCodeResults, which is all runs of codeResults combined
# here we initialize list of combined results from the code only case
combinedResultsCode = [[{} for _ in range(minSize,maxSize+1) ] for _ in range(2)]
for d in range(minSize,maxSize+1):
# we loop over code sizes and runs to create the required dictionaries of data:
# resultsFull, resultsCode and resultsSingle (and well as the things used to make them)
# the results that come fresh from the backend
resultsVeryRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)]
resultsRaw = [[{} for _ in range(2)] for run in range(0,totalRuns)]
# the results from the full code (including ancillas)
# resultsFull[k] gives results for the effective distance d-k code obtained by ignoring the last k code qubits and ancillas
resultsFull = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)]
# the same but with ancilla results excluded
resultsCode = [[[{} for _ in range(d)] for _ in range(2)] for run in range(0,totalRuns)]
# results each single bit
resultsSingle = [[[{} for _ in range(16)] for _ in range(2)] for run in range(0,totalRuns)]
for run in range(0,totalRuns):
# we get results for both possible encoded bits
for bit in range(2):
delayString = ""
if delay>0:
delayString = '_delay='+str(delay)
# get results for this run from file
f = open('Repetition_Code_Results/'+device+'/results_d=' + str(d) + delayString + '_run=' + str(run) + '_bit=' + str(bit) + '.txt')
resultsVeryRaw[run][bit] = eval(f.read())
f.close()
# loop over all keys in the raw results and look at the ones without strings as values
# since all such entries should have a bit string as a key, we call it stringVeryRaw
for stringVeryRaw in resultsVeryRaw[run][bit].keys():
if resultsVeryRaw[run][bit][stringVeryRaw] is not str:
# create a new dictionary in which each key is padded to a bit string of length 16
stringRaw = stringVeryRaw.rjust(16,'0')
resultsRaw[run][bit][stringRaw] = resultsVeryRaw[run][bit][stringVeryRaw]
# now stringRaw only has data in the correct format
# let's loop over its entries and process stuff
for stringRaw in resultsRaw[run][bit].keys():
# get the prob corresponding to this string
probToAdd = resultsRaw[run][bit][stringRaw]
# first we deal with resultsFull and resultsCode
# loop over all truncated codes relevant for this d
for k in range(d):
# distance of this truncated code
dd = d-k
# extract the bit string relevant for resultsFull
# from left to right this will alternate between code and ancilla qubits in increasing order
stringFull = ''
for codeQubit in range(dd): # add bit value for a code qubit...
stringFull += stringRaw[15-GetAddress(codeQubit,0,simulator)]
if (codeQubit!=(d-1)): #...and then the ancilla next to it (if we haven't reached the end of the code)
stringFull += stringRaw[15-GetAddress(codeQubit,1,simulator)]
# remove ancilla bits from this to get the string for resultsCode
stringCode = ""
for n in range(dd):
stringCode += stringFull[2*n]
AddProbToResults(probToAdd,stringFull,resultsFull[run][bit][k])
AddProbToResults(probToAdd,stringCode,resultsCode[run][bit][k])
# now we'll do results single
# the qubits are listed in the order they are in the code
# so for each code qubit
for jj in range(8):
# loop over it and its neighbour
for offset in range(2):
stringSingle = stringRaw[15-GetAddress(jj,offset,simulator)]
AddProbToResults(probToAdd,stringSingle,resultsSingle[run][bit][2*jj+offset])
# combined this run's resultsCode with the total, using the k=0 values
for stringCode in resultsCode[run][bit][0].keys():
probToAdd = resultsCode[run][bit][0][stringCode]/10
AddProbToResults(probToAdd,stringCode,combinedResultsCode[bit][d-minSize])
for run in range(0,totalRuns):
# initialize list used to store the calculated means and variances for results from the codes
codeSample = [[0]*2 for _ in range(d)]
# here
# codeSample gives the results
# codeSample[0] gives results for the whole code
# codeSample[k][0] is the error prob when decoding uses both code and ancilla qubits
# codeSample[k][1] is the error prob when decoding uses only code qubits
singleSample = [0]*16
# singleSample[j] is the probability of state 1 for qubit j when the required bit value is encoded
# write results in
for k in range(d):
# calculate look up tables by averaging over all other runs
fullTable = [{} for _ in range(2)]
codeTable = [{} for _ in range(2)]
for b in range(2):
for r in [rr for rr in range(totalRuns) if rr!=run]:
for string in resultsFull[r][b][k]:
AddProbToResults(resultsFull[r][b][k][string]/(totalRuns-1),string,fullTable[b])
for string in resultsCode[r][b][k]:
AddProbToResults(resultsCode[r][b][k][string]/(totalRuns-1),string,codeTable[b])
# then calculate corresponding errors
codeSample[k][0] = CalculateError(encodedBit,resultsFull[run][encodedBit][k],fullTable)
codeSample[k][1] = CalculateError(encodedBit,resultsCode[run][encodedBit][k],codeTable)
for j in range(16):
if '1' in resultsSingle[run][encodedBit][j].keys():
singleSample[j] = resultsSingle[run][encodedBit][j]['1']
# add results from this run to the overall means and variances
for k in range(d):
for l in range(2):
codeResults[d-minSize][k][2*l] += codeSample[k][l] / totalRuns # means
codeResults[d-minSize][k][2*l+1] += codeSample[k][l]**2 / totalRuns # variances
for j in range(16):
singleResults[d-minSize][j][0] += singleSample[j] / totalRuns
singleResults[d-minSize][j][1] += singleSample[j]**2 / totalRuns
# finish the variances by subtracting the square of the mean
for k in range(d):
for l in range(1,2,4):
codeResults[d-minSize][k][l] -= codeResults[d-minSize][k][l-1]**2
for j in range(16):
singleResults[d-minSize][j][1] -= singleResults[d-minSize][j][0]**2
# return processed results
return codeResults, singleResults, combinedResultsCode
def MakeGraph(X,Y,y,axisLabel,labels=[],legendPos='upper right',verbose=False,log=False,tall=False):
from matplotlib import pyplot as plt
plt.rcParams.update({'font.size': 30})
markers = ["o","^","h","D","*"]
# if verbose, print the numbers to screen
if verbose==True:
print("\nX values")
print(X)
for j in range(len(Y)):
print("\nY values for "+labels[j])
print(Y[j])
print("\nError bars")
print(y[j])
print("")
# convert the variances of varY into widths of error bars
for j in range(len(y)):
for k in range(len(y[j])):
y[j][k] = math.sqrt(y[j][k]/2)
if tall:
plt.figure(figsize=(20,20))
else:
plt.figure(figsize=(20,10))
# add in the series
for j in range(len(Y)):
marker = markers[j%len(markers)]
if labels==[]:
plt.errorbar(X, Y[j], marker = marker, markersize=20, yerr = y[j], linewidth=5)
else:
plt.errorbar(X, Y[j], label=labels[j], marker = marker, markersize=20, yerr = y[j], linewidth=5)
plt.legend(loc=legendPos)
# label the axes
plt.xlabel(axisLabel[0])
plt.ylabel(axisLabel[1])
# make sure X axis is fully labelled
plt.xticks(X)
# logarithms if required
if log==True:
plt.yscale('log')
# make the graph
plt.show()
plt.rcParams.update(plt.rcParamsDefault)
# set device to use
# this also sets the maximum d. We only go up to 6 on the simulator
userInput = input("Do you want results for a real device? (input Y or N) If not, results will be from a simulator. \n").upper()
if (userInput=="Y"):
device = 'ibmqx3'
else:
device = 'ibmq_qasm_simulator'
# determine the delay
userInput = input("What value of the delay do you want results for? \n").upper()
delay = 0
try:
delay = int(userInput)
except:
pass
# determine the code sizes to be considered
userInput = input("What is the minimum size code you wish to consider? (input 3, 4, 5, 6, 7 or 8) \n").upper()
if userInput in ['3','4','5','6','7','8']:
minSize = int(userInput)
else:
minSize = 3
userInput = input("What is the maximum size code you wish to consider? (input a number no less than the minimum, but no larger than 8) \n").upper()
if userInput in ['3','4','5','6','7','8']:
maxSize = int(userInput)
else:
maxSize = 8
# determine whether data needs to be taken
if device=='ibmqx5':
dataAlready = True
else:
userInput = input("Do you want to process saved data? (Y/N) If not, new data will be obtained. \n").upper()
if (userInput=="Y"):
dataAlready = True
else:
dataAlready = False
# set number of runs used for stats
# totalRuns is for a repetition code of length d
totalRuns = 10
# if we need data, we get it
if (dataAlready==False):
# get the required data for the desired number of runs
GetData(device,minSize,maxSize,totalRuns,delay)
codeResults = [[],[]]
singleResults = [[],[]]
for encodedBit in range(2):
try:
codeResults[encodedBit], singleResults[encodedBit], combinedResultsCode = ProcessData(device,encodedBit,minSize,maxSize,totalRuns,delay)
except Exception as e:
print(e)
# plot for single qubit data for each code distance
for d in range(minSize,maxSize+1):
X = range(16)
Y = []
y = []
# a series for each encoded bit
for encodedBit in range(2):
Y.append([singleResults[encodedBit][d-minSize][j][0] for j in range(16)])
y.append([singleResults[encodedBit][d-minSize][j][1] for j in range(16)])
# make graph
print("\n\n***Final state of each qubit for code of distance d = " + str(d) + "***")
MakeGraph(X,Y,y,['Qubit position in code','Probability of 1'])
for encodedBit in range(2): # separate plots for each encoded bit
X = range(minSize,maxSize+1)
Y = []
y = []
for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial
Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(minSize,maxSize+1)])
y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(minSize,maxSize+1)])
# minimum error value for the single qubit memory is found and plotted as a comparsion (with max error bars)
simulator = (device not in ['ibmqx3','ibmqx5'])
minSingle = min([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][0] for d in range(minSize,maxSize+1)])
maxSingle = max([singleResults[encodedBit][d-minSize][GetAddress(d-1,1,simulator)][1] for d in range(minSize,maxSize+1)])
Y.append([minSingle]*(maxSize-minSize+1))
y.append([maxSingle]*(maxSize-minSize+1))
print("\n\n***Encoded " + str(encodedBit) + "***")
MakeGraph(X,Y,y,['Code distance, d','Error probability, P'],
labels=['Full decoding','Partial decoding','Single qubit memory'],legendPos='lower left',log=True,verbose=True)
for encodedBit in range(2): # separate plots for each encoded bit
for decoding in ['full','partial']:
dec = (decoding=='partial') # this is treated as 0 if full and 1 if partial
X = range(1,maxSize+1)
Y = []
y = []
labels = []
for d in range(minSize,maxSize+1):# series for each code size
seriesY = [math.nan]*(maxSize)
seriesy = [math.nan]*(maxSize)
for k in range(d):
seriesY[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+0]
seriesy[d-k-1] = codeResults[encodedBit][d-minSize][k][2*dec+1]
Y.append(seriesY)
y.append(seriesy)
labels.append('d='+str(d))
print("\n\n***Encoded " + str(encodedBit) + " with " + dec*"partial" + (1-dec)*"full" + " decoding***")
MakeGraph(X,Y,y,['Effective code distance','Logical error probability'],
labels=labels,legendPos = 'upper right')
def MakeModelTables (q,d):
# outputs an array of two dictionaries for the lookup table for a simple model of a distance d code
# q[0] is prob of 0->1 noise, and q[1] is prob of 1->0
# no disinction is made between strings with the same number of errors
# the prob for all are assigned to a single string, all with 0s on the left and 1s on the right
modelResults = [{},{}]
bit = ["0","1"]
for encodedBit in range(2):
for errors in range(d+1):
if encodedBit==0:
string = "0"*(d-errors)+"1"*errors
else:
string = "0"*errors+"1"*(d-errors)
modelResults[encodedBit][string] = scipy.special.binom(d,errors) * q[encodedBit]**errors * (1-q[encodedBit])**(d-errors)
return modelResults
def TotalLogical (p0,d,p1=0): # outputs total logical error prob for a single or two round code
P0 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[0], MakeModelTables([p0,p0],d) )
P1 = CalculateError( encodedBit, MakeModelTables([p0,p0],d)[1], MakeModelTables([p1,p1],d) )
return P0*(1-P1) + P1*(1-P0)
for encodedBit in range(2): # separate plots for each encoded bit
p = [0]*2 # here is where we'll put p_0 and p_1
bar = [0]*2
for dec in [1,0]: # dec=0 corresponds to full decoding, and 1 to partial
# get the results we want to fit to
realResults = [codeResults[encodedBit][d-minSize][0][2*dec] for d in range(minSize,maxSize+1)]
# search possible values intul we find a minimum (assumed to be global)
# first we do the partial decoding to get p (which is stored in p[0])
# then the full decoding to get p[1]=p_1
minimizing = True
delta = 0.001
q = delta
diff =[math.inf,math.inf]
while minimizing:
q += delta # set new q
diff[0] = diff[1] # copy diff value for last p
# calculate diff for new q
diff[1] = 0
for d in range(minSize,maxSize+1):
if dec==1:
Q = TotalLogical(q,d)
else:
Q = TotalLogical(p[0]-q,d,p1=q)
diff[1] += ( math.log( realResults[d-minSize] ) - math.log( Q ) )**2
# see if a minimum has been found
minimizing = ( diff[0]>diff[1] )
# go back a step on p to get pSum
p[1-dec] = q - delta
# get diff per qubit
bar[1-dec] = math.exp(math.sqrt( diff[0]/(maxSize-minSize+1) ))
p[0] = p[0] - p[1] # put p_0 in p[0] (instead of p)
print("\n\n***Encoded " + str(encodedBit) + "***\n" )
for j in [0,1]:
print(" p_"+str(j)+" = " + str(p[j]) + " with fit values typically differing by a factor of " + str(bar[j]) + "\n")
plottedMinSize = max(4,minSize) # we won't print results for d=3 for clarity
X = range(plottedMinSize,maxSize+1)
Y = []
y = []
# original plots
for dec in range(2): # dec=0 corresponds to full decoding, and 1 to partial
# results from the device
Y.append([codeResults[encodedBit][d-minSize][0][2*dec+0] for d in range(plottedMinSize,maxSize+1)])
y.append([codeResults[encodedBit][d-minSize][0][2*dec+1] for d in range(plottedMinSize,maxSize+1)])
# fit lines
for dec in range(2):
if dec==1:
Y.append([TotalLogical(p[0]+p[1],d) for d in range(plottedMinSize,maxSize+1)])
else:
Y.append([TotalLogical(p[0],d,p1=p[1]) for d in range(plottedMinSize,maxSize+1)])
y.append([0]*(maxSize-plottedMinSize+1))
MakeGraph(X,Y,y,['Code distance, d','Error probability, P'],
labels=['Full decoding','Partial decoding','Full decoding (model)','Partial decoding (model)'],legendPos='lower left',log=True)
# for each code distance and each encoded bit value, we'll create a list of the probabilities for each possible number of errors
# list is initialized with zeros
errorNum = [[[0]*(d+1) for d in range(minSize,maxSize+1)] for _ in range(2)]
for d in range(minSize,maxSize+1):
for bit in range(2):
# for each code distance and each encoded bit value we look at all possible result strings
for string in combinedResultsCode[bit][d-minSize]:
# count the number of errors in each string
num = 0
for j in range(d):
num += ( int( string[j] , 2 ) + bit )%2
# add prob to corresponding number of errors
errorNum[bit][d-minSize][num] += combinedResultsCode[bit][d-minSize][string]
# the we make a graph for each, and print a title
Y0 = [y if y>0 else math.nan for y in errorNum[0][d-minSize]]
Y1 = [y if y>0 else math.nan for y in errorNum[1][d-minSize]]
print("\n\n***Probability of errors on code qubits for d = " + str(d) + "***")
MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of code qubit errors','Probability (log base 10)'],
labels=['Encoded 0','Encoded 1'],legendPos='upper right',log=True)
# actually, we make two graphs. This one plots the number of 1s rather than errors, and so the plot for encoded 1 is inverted
# Y0 in this graph is as before
Y1 = Y1[::-1] # but Y1 has its order inverted
print("\n\n***Probability for number of 1s in code qubit result for d = " + str(d) + "***")
MakeGraph(range(d+1),[Y0,Y1],[[0]*(d+1)]*2,['Number of 1s in code qubit result','Probability (log base 10)'],
labels=['Encoded 0','Encoded 1'],legendPos='center right',log=True)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sympy
from sympy import *
import itertools
from IPython.display import display
init_printing() #allows nice math displays
class QuantumMatrix():
def __init__(self, m, coeff = 1):
self.matrix = sympy.Matrix(m)
self.coefficient = coeff
self.canonize()
def canonize(self):
a = next((x for x in self.matrix if x != 0), None)
if a is not None: #zero vector
for i,j in itertools.product([0,1], [0,1]):
self.matrix[i,j] = sympy.simplify(self.matrix[i,j] / a)
self.coefficient = sympy.simplify(self.coefficient * a)
def __str__(self):
coeff_string = ""
if self.coefficient != 1:
coeff_string = "{} * ".format(self.coefficient)
return "{}[[{}, {}], [{}, {}]]".format(coeff_string,self.matrix[0], self.matrix[1], self.matrix[2], self.matrix[3])
def __mul__(self, rhs):
return QuantumMatrix(self.matrix * rhs.matrix, self.coefficient * rhs.coefficient)
def __add__(self, rhs):
temp_rhs_matrix = sympy.Matrix([[1,0],[0,1]])
for i,j in itertools.product([0,1], [0,1]):
temp_rhs_matrix[i,j] = sympy.simplify((rhs.matrix[i,j] * self.coefficient) / rhs.coefficient)
return QuantumMatrix(self.matrix + temp_rhs_matrix, self.coefficient * 1/sympy.sqrt(2))
def __sub__(self, rhs):
return self + QuantumMatrix(rhs.matrix, rhs.coefficient * -1)
def __eq__(self, rhs):
return (self.matrix == rhs.matrix and self.coefficient == rhs.coefficient)
def equiv(self, rhs):
return (self.matrix == rhs.matrix)
def __iter__(self):
for x in self.matrix:
yield x
X = QuantumMatrix( [[0,1], [1,0]])
Y = QuantumMatrix( [[0,-sympy.I], [sympy.I,0]])
Z = QuantumMatrix( [[1,0], [0,-1]])
I = QuantumMatrix( [[1,0], [0,1]])
print ("The Pauli matrices (when neglecting the global phase):")
print ("Identity: I=")
display(sympy.Matrix(I.matrix))
print ("X=")
display(sympy.Matrix(X.matrix))
print ("Y=")
display(sympy.Matrix(Y.matrix))
print ("Z=")
display(sympy.Matrix(Z.matrix))
print ("The Pauli gates X,Y,Z are of order 2:")
A=X*X
print ("X*X=")
display(sympy.Matrix(A.matrix))
A=Y*Y
print ("Y*Y=")
display(sympy.Matrix(A.matrix))
A=Z*Z
print ("Z*Z=")
display(sympy.Matrix(A.matrix))
print ("For example, one can verify that X*Y=Y*X=Z:")
A=X*Y
B=Y*X
print ("X*Y = Z =")
display(sympy.Matrix(A.matrix))
print ("Y*X = Z =")
display(sympy.Matrix(B.matrix))
print ("Similarly, X*Z=Z*X=Y, Y*Z=Z*Y=X")
H = QuantumMatrix( [[1,1], [1,-1]], 1/sympy.sqrt(2))
print ("Hadamard gate: H=")
display(sympy.Matrix(H.matrix))
print ("H is of order 2:")
A=H*H
print ("H*H =")
display(sympy.Matrix(A.matrix))
print ("H operates on the Pauli gates by conjugation as a reflection: X<-->Z:")
A=H*X*H
print("H*X*H = Z =")
display(sympy.Matrix(A.matrix))
A=H*Z*H
print("H*Z*H = X =")
display(sympy.Matrix(A.matrix))
A=H*Y*H
print("H*Y*H = Y =")
display(sympy.Matrix(A.matrix))
S = QuantumMatrix( [[1,0], [0,sympy.I]])
print ("Phase gate: S=")
display(sympy.Matrix(S.matrix))
print ("Z=S*S, thus S has order 4, and the inverse of S is S*Z:")
A=S*S
print ("S*S = Z =")
display(sympy.Matrix(A.matrix))
print ("The inverse of S: Sdg = S*Z =")
Sdg = S*Z
display(sympy.Matrix(Sdg.matrix))
print ("Indeed, S*Sdg =")
A = S*Sdg
display(sympy.Matrix(A.matrix))
print ("S operates on the Pauli gates by conjugation as a reflection: Y<-->Z:")
A = S*X*Sdg # =Y
print ("S*X*Sdg = Y =")
display(sympy.Matrix(A.matrix))
print ("S*Y*Sdg = X =")
A = S*Y*Sdg # =X
display(sympy.Matrix(A.matrix))
print ("S*Z*Sdg = Z =")
A = S*Z*Sdg # =Z
display(sympy.Matrix(A.matrix))
print ("We therefore get the commutator relations:")
print ("S*X = Y*S and Sdg*Y = X*Sdg")
print ("S*Y = X*S and Sdg*X = Y*Sdg")
print ("S*Z = Z*S = Sdg and Sdg*Z = Z*Sdg = S")
V = H*S*H*S
print ("Let: V = H*S*H*S =")
display(sympy.Matrix(V.matrix))
print ("V is of order 3:")
A=V*V*V
print ("V*V*V =")
display(sympy.Matrix(A.matrix))
print ("Hence, V = Sdg*H =")
A=Sdg*H
display(sympy.Matrix(A.matrix))
print ("The inverse of V is: W = S*Z*H*S*Z*H = H*S = ")
W=H*S
display(sympy.Matrix(W.matrix))
print ("Indeed, W = V*V =")
A=V*V
display(sympy.Matrix(A.matrix))
print ("V operates on the Pauli gates by conjugation as a rotation: Z-->X-->Y-->Z:")
A=W*X*V
print("W*X*V = Y =")
display(sympy.Matrix(A.matrix))
A=W*Y*V
print("W*Y*V = Z =")
display(sympy.Matrix(A.matrix))
A=W*Z*V
print("W*Z*V = X = ")
display(sympy.Matrix(A.matrix))
print ("I=")
display(sympy.Matrix(I.matrix))
print ("X=")
display(sympy.Matrix(X.matrix))
print ("Y=")
display(sympy.Matrix(Y.matrix))
print ("Z=")
display(sympy.Matrix(Z.matrix))
print ("V=")
display(sympy.Matrix(V.matrix))
A=V*X
print ("V*X=")
display(sympy.Matrix(A.matrix))
A=V*Y
print ("V*Y=")
display(sympy.Matrix(A.matrix))
A=V*Z
print ("V*Z=")
display(sympy.Matrix(A.matrix))
print ("W=")
display(sympy.Matrix(W.matrix))
A=W*X
print ("W*X=")
display(sympy.Matrix(A.matrix))
A=W*Y
print ("W*Y=")
display(sympy.Matrix(A.matrix))
A=W*Z
print ("W*Z=")
display(sympy.Matrix(A.matrix))
print ("H=")
display(sympy.Matrix(H.matrix))
A=H*X
print ("H*X=")
display(sympy.Matrix(A.matrix))
A=H*Y
print ("H*Y=")
display(sympy.Matrix(A.matrix))
A=H*Z
print ("H*Z=")
display(sympy.Matrix(A.matrix))
print ("H*V=")
A=H*V
display(sympy.Matrix(A.matrix))
A=H*V*X
print ("H*V*X=")
display(sympy.Matrix(A.matrix))
A=H*V*Y
print ("H*V*Y=")
display(sympy.Matrix(A.matrix))
A=H*V*Z
print ("H*V*Z=")
display(sympy.Matrix(A.matrix))
print ("H*W=")
A=H*W
display(sympy.Matrix(A.matrix))
A=H*W*X
print ("H*W*X=")
display(sympy.Matrix(A.matrix))
A=H*W*Y
print ("H*W*Y=")
display(sympy.Matrix(A.matrix))
A=H*W*Z
print ("H*W*Z=")
display(sympy.Matrix(A.matrix))
print ("H*V = H*H*S*H*S = S*H*S =")
A=S*H*S #H*V
display(sympy.Matrix(A.matrix))
A=Sdg*H*S #H*V*Y
print ("H*V*Y = H*H*S*H*S*Y = S*H*S*Y = S*H*X*S = S*Z*H*S = Sdg*H*S =")
display(sympy.Matrix(A.matrix))
A=S*H*Sdg #H*V*Z
print ("H*V*Z = H*H*S*H*S*Z = S*H*Sdg =")
display(sympy.Matrix(A.matrix))
print ("H*W = H*H*S = S =")
A=S #H*W
display(sympy.Matrix(A.matrix))
A= S*X #H*W*X
print ("H*W*X = S*X = ")
display(sympy.Matrix(A.matrix))
A=S*Y #H*W*Y
print ("H*W*Y = S*Y =")
display(sympy.Matrix(A.matrix))
A=Sdg #H*W*Z
print ("H*W*Z = Sdg =")
display(sympy.Matrix(A.matrix))
Class1Size = 2*2*3*3*4*4
print ("The size of Class 1 is: ", Class1Size)
Class2Size = 2*2*3*3*3*3*4*4
print ("The size of Class 2 is: ", Class2Size)
Class3Size = 2*2*3*3*3*3*4*4
print ("The size of Class 3 is: ", Class3Size)
Class4Size = 2*2*3*3*4*4
print ("The size of Class 4 is: ", Class4Size)
TotalSize = Class1Size + Class2Size + Class3Size + Class4Size
print ("The size of the 2-qubit Clifford group is: ", TotalSize)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import random
import math
from sympy.ntheory import isprime
# importing QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, IBMQ, execute
from qiskit.tools.monitor import job_monitor
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
IBMQ.load_accounts()
sim_backend = Aer.get_backend('qasm_simulator')
device_backend = least_busy(IBMQ.backends(operational=True, simulator=False))
#Function that takes in a prime number and a string of letters and returns a quantum circuit
def qfa_algorithm(string, prime):
if isprime(prime) == False:
raise ValueError("This number is not a prime") #Raises a ValueError if the input prime number is not prime
else:
n = math.ceil((math.log(prime))) #Rounds up to the next integer of the log(prime)
qr = QuantumRegister(n) #Creates a quantum register of length log(prime) for log(prime) qubits
cr = ClassicalRegister(n) #Creates a classical register for measurement
qfaCircuit = QuantumCircuit(qr, cr) #Defining the circuit to take in the values of qr and cr
for x in range(n): #For each qubit, we want to apply a series of unitary operations with a random int
random_value = random.randint(1,prime - 1) #Generates the random int for each qubit from {1, prime -1}
for letter in string: #For each letter in the string, we want to apply the same unitary operation to each qubit
qfaCircuit.ry((2*math.pi*random_value) / prime, qr[x]) #Applies the Y-Rotation to each qubit
qfaCircuit.measure(qr[x], cr[x]) #Measures each qubit
return qfaCircuit #Returns the created quantum circuit
#A function that returns a string saying if the string is accepted into the language or rejected
def accept(parameter):
states = list(result.get_counts(parameter))
for s in states:
for integer in s:
if integer == "1":
return "Reject: the string is not accepted into the language"
return "Accept: the string is accepted into the language"
range_lower = 0
range_higher = 36
prime_number = 11
for length in range(range_lower,range_higher):
params = qfa_algorithm("a"* length, prime_number)
job = execute(params, sim_backend, shots=1000)
result = job.result()
print(accept(params), "\n", "Length:",length," " ,result.get_counts(params))
qfa_algorithm("a"* 3, prime_number).draw(output='mpl')
#Function that takes in a prime number and a string of letters and returns a quantum circuit
def qfa_controlled_algorithm(string, prime):
if isprime(prime) == False:
raise ValueError("This number is not a prime") #Raises a ValueError if the input prime number is not prime
else:
n = math.ceil((math.log(math.log(prime,2),2))) #Represents log(log(p)) control qubits
states = 2 ** (n) #Number of states that the qubits can represent/Number of QFA's to be performed
qr = QuantumRegister(n+1) #Creates a quantum register of log(log(prime)) control qubits + 1 target qubit
cr = ClassicalRegister(1) #Creates a classical register of log(log(prime)) control qubits + 1 target qubit
control_qfaCircuit = QuantumCircuit(qr, cr) #Defining the circuit to take in the values of qr and cr
for q in range(n): #We want to take each control qubit and put them in a superposition by applying a Hadamard Gate
control_qfaCircuit.h(qr[q])
for letter in string: #For each letter in the string, we want to apply a series of Controlled Y-rotations
for q in range(n):
control_qfaCircuit.cu3(2*math.pi*(2**q)/prime, 0, 0, qr[q], qr[n]) #Controlled Y on Target qubit
control_qfaCircuit.measure(qr[n], cr[0]) #Measure the target qubit
return control_qfaCircuit #Returns the created quantum circuit
for length in range(range_lower,range_higher):
params = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(params, sim_backend, shots=1000)
result = job.result()
print(accept(params), "\n", "Length:",length," " ,result.get_counts(params))
qfa_controlled_algorithm("a"* 3, prime_number).draw(output='mpl')
prime_number = 3
length = 2 # set the length so that it is not divisible by the prime_number
print("The length of a is", length, " while the prime number is", prime_number)
qfa1 = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(qfa1, backend=device_backend, shots=100)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts())
qfa1.draw(output='mpl')
print_number = length = 3 # set the length so that it is divisible by the prime_number
print("The length of a is", length, " while the prime number is", prime_number)
qfa2 = qfa_controlled_algorithm("a"* length, prime_number)
job = execute(qfa2, backend=device_backend, shots=100)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts())
qfa2.draw(output='mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Imports
from itertools import product
import matplotlib.pyplot as plt
%matplotlib inline
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Result
from qiskit import available_backends, get_backend, execute, register, least_busy
from qiskit.tools.visualization import matplotlib_circuit_drawer, qx_color_scheme #require qiskit>0.5.5
%config InlineBackend.figure_format = 'svg'
style = qx_color_scheme()
style['compress'] = True
style['cregbundle'] = True
style['plotbarrier'] = True
circuit_drawer = lambda circuit: matplotlib_circuit_drawer(circuit, style=style)
# Creating registers
qa = QuantumRegister(1, 'alice')
qb = QuantumRegister(1, 'bob')
c = ClassicalRegister(2, 'c')
# Bell Measurement
bell_measurement = QuantumCircuit(qa, qb, c)
bell_measurement.cx(qa, qb)
bell_measurement.h(qa)
bell_measurement.measure(qa[0], c[0])
bell_measurement.measure(qb[0], c[1])
circuit_drawer(bell_measurement)
alice = {}
bob = {}
# eigenvalue
alice['+'] = QuantumCircuit(qa, qb, c) # do nothing
alice['-'] = QuantumCircuit(qa, qb, c)
alice['-'] .x(qa)
bob['+'] = QuantumCircuit(qa, qb, c) # do nothing
bob['-'] = QuantumCircuit(qa, qb, c)
bob['-'].x(qb)
# matrix
alice['Z'] = QuantumCircuit(qa, qb, c) # do nothing
alice['X'] = QuantumCircuit(qa, qb, c)
alice['X'].h(qa)
bob['W'] = QuantumCircuit(qa, qb, c)
bob['W'].h(qb)
bob['W'].t(qb)
bob['W'].h(qb)
bob['W'].s(qb)
bob['V'] = QuantumCircuit(qa, qb, c)
bob['V'].h(qb)
bob['V'].tdg(qb)
bob['V'].h(qb)
bob['V'].s(qb)
qc = alice['+'] + alice['Z'] + bob['+'] + bob['V']
circuit_drawer(qc)
qc = alice['-'] + alice['X'] + bob['+'] + bob['W']
circuit_drawer(qc)
backend = 'local_qasm_simulator'
shots = 1024
circuits = {}
for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']):
name = a_sign + a_basis + b_sign + b_basis
circuits[name] = QuantumCircuit(qa, qb, c)
circuits[name] += alice[a_sign]
circuits[name] += alice[a_basis]
circuits[name] += bob[b_sign]
circuits[name] += bob[b_basis]
circuits[name].barrier(qa)
circuits[name].barrier(qb)
circuits[name] += bell_measurement
# Example
print('A quantum circuit of -X+V.')
circuit_drawer(circuits['-X+V'])
job = execute(circuits.values(), backend=backend, shots=shots)
result = job.result()
completely_mixed = {'00': 0, '01': 0, '10': 0, '11': 0}
for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']):
name = a_sign + a_basis + b_sign + b_basis
completely_mixed['00'] += result.average_data(circuits[name], {'00': 1})/16
completely_mixed['01'] += result.average_data(circuits[name], {'01': 1})/16
completely_mixed['10'] += result.average_data(circuits[name], {'10': 1})/16
completely_mixed['11'] += result.average_data(circuits[name], {'11': 1})/16
plt.bar(completely_mixed.keys(), completely_mixed.values(), width=0.5)
plt.xlabel('Outcome', fontsize=15)
plt.ylabel('Probability for the completely mixed state', fontsize=10)
plt.axhline(y=0.25, color='red', linewidth=1)
def E(result: Result, observable: dict, a_basis: str, b_basis: str) -> float:
val = 0
str2int = lambda x: 1 if x == '+' else -1
for a_sign, b_sign in product(['+', '-'], ['+', '-']):
name = a_sign + a_basis + b_sign + b_basis
sign = str2int(a_sign) * str2int(b_sign)
val += sign * result.average_data(circuits[name], observable)
return val
def D(result: Result, outcome: str) -> float:
val = 0
for a_basis, b_basis in product(['Z', 'X'], ['V', 'W']):
if outcome[0] == outcome[1] and a_basis == 'X' and b_basis == 'V':
sign = -1
elif outcome[0] != outcome[1] and a_basis == 'X' and b_basis == 'W':
sign = -1
else:
sign = 1
val += sign * E(result, {outcome: 1}, a_basis=a_basis, b_basis=b_basis)
return val
for outcome in ['00', '01', '10', '11']:
if completely_mixed[outcome] <= 1/4: # check the condition
print('D is equal to {} for the outcome {}.'.format(D(result, outcome), outcome))
# Connecting to the IBM Quantum Experience
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
register(qx_config['APItoken'], qx_config['url'])
device_shots = 1024
device_name = least_busy(available_backends({'simulator': False, 'local': False}))
device = get_backend(device_name)
device_coupling = device.configuration['coupling_map']
print("the best backend is " + device_name + " with coupling " + str(device_coupling))
job = execute(circuits.values(), backend=device_name, shots=device_shots)
result = job.result()
completely_mixed = {'00': 0, '01': 0, '10': 0, '11': 0}
for a_sign, a_basis, b_sign, b_basis in product(['+', '-'], ['Z', 'X'], ['+', '-'], ['V', 'W']):
name = a_sign + a_basis + b_sign + b_basis
completely_mixed['00'] += result.average_data(circuits[name], {'00': 1})/16
completely_mixed['01'] += result.average_data(circuits[name], {'01': 1})/16
completely_mixed['10'] += result.average_data(circuits[name], {'10': 1})/16
completely_mixed['11'] += result.average_data(circuits[name], {'11': 1})/16
plt.bar(completely_mixed.keys(), completely_mixed.values(), width=0.5)
plt.xlabel('Outcome', fontsize=15)
plt.ylabel('Probability for the completely mixed state', fontsize=10)
plt.axhline(y=0.25, color='red', linewidth=1)
for outcome in ['00', '01', '10', '11']:
if completely_mixed[outcome] <= 1/4: # check the condition
print('D is equal to {} for the outcome {}.'.format(D(result, outcome), outcome))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Importing QISKit
import math, sys
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
# Import basic plotting tools
from qiskit.tools.visualization import plot_histogram
# Import methods to connect with remote backends
from qiskit import available_backends, execute, register, get_backend
# Import token to use remote backends
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
#to enable sleep
import time
#connect to remote API to be able to use remote simulators and real devices
register(qx_config['APItoken'], qx_config['url'])
print("Available backends:", available_backends())
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
q = QuantumRegister(3)
c = ClassicalRegister(3)
qft3 = QuantumCircuit(q, c)
input_state(qft3, q, 3)
qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
print(qft3.qasm())
simulate = execute(qft3, backend="local_qasm_simulator", shots=1024).result()
simulate.get_counts()
backend = "ibmqx4"
shots = 1024
if get_backend(backend).status["available"] is True:
job_exp = execute(qft3, backend=backend, shots=shots)
lapse = 0
interval = 10
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
results = job_exp.result()
plot_histogram(results.get_counts())
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Import packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import time
# import from qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, compile
from qiskit.converters import qobj_to_circuits
from qiskit import Aer, IBMQ
from qiskit.providers.aer import noise
# import tomography library
import qiskit.tools.qcvv.tomography as tomo
# useful additional packages
from qiskit.tools.visualization import plot_state, plot_histogram
from qiskit.tools.qi.qi import state_fidelity, outer
from qiskit.tools.qi.qi import outer
from qiskit.quantum_info import state_fidelity
from qiskit.tools.monitor import job_monitor, backend_overview
from qiskit.providers.ibmq import least_busy
Aer.backends() # No need for credentials for running the next cells
# Determine the job
n = int(input("type number of qubits + enter: "))
# create a n-qubit quantum register
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
my_state = QuantumCircuit(qr, cr, name='my_state')
# desired vector for a n-qubit W state
desired_vector = []
qr_vector = []
n_vector = 2**n
for i in range(n_vector):
desired_vector.append(0)
for j in range(n) :
desired_vector[2**j] = 1/np.sqrt(n)
# choice of the circuit building method (arbitrary or specific)
print("Do you want to use the specific method?")
W_state_circuit = input(" Answer by (y/n) + enter\n").upper()
if (W_state_circuit == "N") :
method = "arbitrary"
# Initialize a n-qubit W quantum state using the arbitrary method
for j in range(n) :
qr_vector.append(qr[j])
my_state.initialize(desired_vector, qr_vector)
else:
# Quantum circuit to make a n-qubit W state using the specific method
method = "specific"
my_state.x(qr[n-1]) #start is |10...0>
for i in range(1,n) :
theta = np.arccos(np.sqrt(1/(n-i+1)))
my_state.ry(-theta,qr[n-i-1])
my_state.cz(qr[n-i],qr[n-i-1])
my_state.ry(theta,qr[n-i-1])
for i in range(1,n) :
my_state.cx(qr[n-i-1],qr[n-i])
# Measurement circuit
measuring = QuantumCircuit(qr, cr, name='measuring')
for i in range(n) :
measuring.measure(qr[i] , cr[i])
test = my_state+measuring
# Test circuit "my_state" : Noise free model on simulator
backend_sim = Aer.get_backend('qasm_simulator')
shots = 1024
job_noisefree = execute(test, backend_sim, shots=shots, max_credits=5)
job_monitor(job_noisefree)
noisefree_count = job_noisefree.result().get_counts(test)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print(noisefree_count)
plot_histogram(noisefree_count, color=['purple'],
title=str(n) + '- qubit W state, noise free simulation, ' + method + " method")
# QASM from test
QASM_source = test.qasm()
print(QASM_source)
# Draw the circuit
test.draw(output='mpl')
# Execute state tomography using noise free quantum device simulation
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
backend_tomo = Aer.get_backend('qasm_simulator') # for simulation
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
mode = "noise free simulation"
my_state_job = execute(my_state_tomo_circuits, backend_tomo, shots=shots)
job_monitor(my_state_job)
my_state_tomo_result = my_state_job.result()
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
IBMQ.load_accounts()
backend_overview() # you may skip running this cell if you want
backend_real = least_busy(IBMQ.backends(operational=True, simulator=False))
print(backend_real)
# Prepare device noise simulation (DNS)
device = backend_real
print("device: ", device)
properties = device.properties()
coupling_map = device.configuration().coupling_map
prepared = False
if device.name() == 'ibmq_16_melbourne' :
gate_times = [
('u1', None, 0), ('u2', None, 100), ('u3', None, 200),
('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721),
('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800),
('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895),
('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800),
('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773),
('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800)
]
prepared = True
elif device.name() == 'ibmqx4' :
gate_times = [
('u1', None, 0), ('u2', None, 60), ('u3', None, 120),
('cx', [1, 0], 340), ('cx', [2, 0], 424), ('cx', [2, 1], 520),
('cx', [3, 2], 620), ('cx', [3, 4], 420), ('cx', [4, 2], 920)
]
prepared = True
else :
print("No gate times yet defined in this notebook for: ", device)
if prepared :
# Construct the noise model from backend properties and custom gate times
noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times)
# Get the basis gates for the noise model
basis_gates = noise_model.basis_gates
print("noise model prepared for", device)
# Execute test using device noise simulation (DNS)
backend_noise = Aer.get_backend('qasm_simulator') # for simulation (DNS)
shots = 1024
mode = "DNS"
job_noise = execute(test, backend_noise,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
job_monitor(job_noise)
print(job_noise.status)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
noisy_count = job_noise.result().get_counts(test)
print(noisy_count)
plot_histogram(noisy_count, color=['cyan'],
title= str(n) + '- qubit W state, ' + mode + ': {}, '.format(device.name()) + method + " method")
# Execute state tomography using device noise simulation (DNS)
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
backend_tomo = Aer.get_backend('qasm_simulator') # for simulation
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
mode = "DNS"
my_state_job = execute(my_state_tomo_circuits, backend_tomo,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
job_monitor(my_state_job)
my_state_tomo_result = my_state_job.result()
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode, "of", device)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.788,0.734,0.628,0.542], 'mo-', label="Specific Algorithm - DNS")
plt.plot([2,3,4,5], [0.773,0.682,0.386,0.148], 'cs-', label="Arbitrary Initialization - DNS")
plt.legend()
plt.show()
# Execute test using superconducting quantum computing device (SQC)
#Choose the backend
#backend_noise = Aer.get_backend('qasm_simulator') # for optional test before final experiment
backend_noise = device # for least busy SQC device
# Execute on SQC and get counts
shots = 1024
if backend_noise.name() == "qasm_simulator" : # optional test before final experiment
mode = "DNS"
job_noise = execute(test, backend_noise,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
else: # final experiment on real device
mode = "SQC"
job_noise = execute(test, backend_noise)
job_monitor(job_noise)
print(job_noise.status)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
noisy_count = job_noise.result().get_counts(test)
print(noisy_count)
plot_histogram(noisy_count, color=['orange'],
title= str(n) + '- qubit W state, ' + mode + ': {}, '.format(device.name()) + method + " method")
# Execute state tomography on superconducting quantum computing device (SQC)
# obtain the final state vector
backend_stvct = Aer.get_backend('statevector_simulator')
job = execute(my_state, backend_stvct)
my_state_psi = job.result().get_statevector(my_state)
# construct state tomography set for measurement of qubits [0, ..., n-1] in the Pauli basis
qubit_set = []
for i in range(0,n) :
qubit_set.append(i)
my_state_tomo_set = tomo.state_tomography_set(qubit_set) # default value for meas_basis ='Pauli'.
# add the state tomography measurement circuits to the Quantum Program
my_state_tomo_circuits = tomo.create_tomography_circuits(my_state, qr, cr, my_state_tomo_set)
#Choose the backend
#backend_tomo = Aer.get_backend('qasm_simulator') # optional test before final experiment
backend_tomo = device # for least busy SQC device
# take 1024 shots for each measurement basis
# note: reduce this number for larger number of qubits
shots = 1024
# loop: 27 circuits maximum per job to avoid exceeding the allowed limit for the real device.
n_circ = 3**n
i_max = min(27,n_circ)
my_jobs = []
index_job = -1
for i in range(0,n_circ,i_max) :
circs =[]
for j in range(i, i+i_max):
circs.append(my_state_tomo_circuits[j])
if backend_tomo.name() == "qasm_simulator" : # optional test before final experiment
mode = "DNS"
my_state_job = execute(circs, backend_tomo,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates)
else: # final experiment on real device
mode = "SQC"
my_state_job = execute(circs, backend_tomo, shots=shots)
my_jobs.append(my_state_job)
index_job = index_job + 1
job_monitor(my_jobs[index_job], monitor_async = True)
my_state_new_result = my_state_job.result()
if i == 0:
my_state_tomo_result = my_state_new_result
else:
my_state_tomo_result = my_state_tomo_result + my_state_new_result
# extract tomography data from results
my_state_tomo_data = tomo.tomography_data(my_state_tomo_result, my_state.name, my_state_tomo_set)
# Quantum fidelity
# reconstruct experimentally measured density matrix
rho_fit = tomo.fit_tomography_data(my_state_tomo_data)
# calculate fidelity of fitted state:
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print("Date (DMY):", time_exp)
print('Tomography',str(n)+'-qubit W state on', backend_tomo,
", shots:", shots, ", method:", method, ", mode:", mode, device)
F_fit = state_fidelity(rho_fit, my_state_psi)
print('Fidelity with theoretical ideal state')
print('F =', F_fit)
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.812,0.735,0.592,0.457], 'ro-', label="Specific Algorithm")
plt.plot([2,3,4,5], [0.838,0.539,0.144,0.060], 'bs-', label="Arbitrary Initialization")
plt.legend()
plt.show()
# DSN vs SQC, count histograms
# Shots = 1024
count_noisefree = {'010': 344, '001': 335, '100': 345}
count_DNS = {'110': 42, '010': 258, '111': 9, '011': 38, '000': 76, '001': 281, '100': 286, '101': 34}
count_real = {'001': 274, '000': 129, '010': 224, '011': 20, '100': 282, '111': 14, '101': 46, '110': 35}
plot_histogram([count_noisefree, count_DNS, count_real],
title= 'Determistic W state generation, specific algorithm, device: ibmqx4',
color=['purple','cyan', 'orange'], bar_labels=False,
legend = ['Noise free simulation', 'Device noise simulation','Real quantum device'])
plt.xlabel('Number of Entangled Qubits')
plt.ylabel('Quantum Fidelity')
plt.axis([1.4, 6, 0, 1])
plt.grid()
plt.plot([2,3,4,5], [0.812,0.735,0.592,0.457], 'ro-', label="Specific Algorithm - SQC")
plt.plot([2,3,4,5], [0.838,0.539,0.144,0.060], 'bs-', label="Arbitrary Initialization - SQC")
plt.plot([2,3,4,5], [0.788,0.734,0.628,0.542], 'mo-', label="Specific Algorithm - DNS")
plt.plot([2,3,4,5], [0.773,0.682,0.386,0.148], 'cs-', label="Arbitrary Initialization - DNS")
plt.legend()
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# useful math functions
from math import pi, cos, acos, sqrt
import random
# importing the QISKit
from qiskit import QuantumProgram
import Qconfig
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
Q_program = QuantumProgram()
Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
N = 4
# Creating registers
qr = Q_program.create_quantum_register("qr", N)
# for recording the measurement on qr
cr = Q_program.create_classical_register("cr", N)
circuitName = "sharedEntangled"
sharedEntangled = Q_program.create_circuit(circuitName, [qr], [cr])
#Create uniform superposition of all strings of length 2
for i in range(2):
sharedEntangled.h(qr[i])
#The amplitude is minus if there are odd number of 1s
for i in range(2):
sharedEntangled.z(qr[i])
#Copy the content of the fist two qubits to the last two qubits
for i in range(2):
sharedEntangled.cx(qr[i], qr[i+2])
#Flip the last two qubits
for i in range(2,4):
sharedEntangled.x(qr[i])
#we first define controlled-u gates required to assign phases
from math import pi
def ch(qProg, a, b):
""" Controlled-Hadamard gate """
qProg.h(b)
qProg.sdg(b)
qProg.cx(a, b)
qProg.h(b)
qProg.t(b)
qProg.cx(a, b)
qProg.t(b)
qProg.h(b)
qProg.s(b)
qProg.x(b)
qProg.s(a)
return qProg
def cu1pi2(qProg, c, t):
""" Controlled-u1(phi/2) gate """
qProg.u1(pi/4.0, c)
qProg.cx(c, t)
qProg.u1(-pi/4.0, t)
qProg.cx(c, t)
qProg.u1(pi/4.0, t)
return qProg
def cu3pi2(qProg, c, t):
""" Controlled-u3(pi/2, -pi/2, pi/2) gate """
qProg.u1(pi/2.0, t)
qProg.cx(c, t)
qProg.u3(-pi/4.0, 0, 0, t)
qProg.cx(c, t)
qProg.u3(pi/4.0, -pi/2.0, 0, t)
return qProg
# dictionary for Alice's operations/circuits
aliceCircuits = {}
# Quantum circuits for Alice when receiving idx in 1, 2, 3
for idx in range(1, 4):
circuitName = "Alice"+str(idx)
aliceCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr])
theCircuit = aliceCircuits[circuitName]
if idx == 1:
#the circuit of A_1
theCircuit.x(qr[1])
theCircuit.cx(qr[1], qr[0])
theCircuit = cu1pi2(theCircuit, qr[1], qr[0])
theCircuit.x(qr[0])
theCircuit.x(qr[1])
theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
theCircuit = cu3pi2(theCircuit, qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit = ch(theCircuit, qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit.x(qr[1])
theCircuit.cx(qr[1], qr[0])
theCircuit.x(qr[1])
elif idx == 2:
theCircuit.x(qr[0])
theCircuit.x(qr[1])
theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit.x(qr[1])
theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit.h(qr[0])
theCircuit.h(qr[1])
elif idx == 3:
theCircuit.cz(qr[0], qr[1])
theCircuit.swap(qr[0], qr[1])
theCircuit.h(qr[0])
theCircuit.h(qr[1])
theCircuit.x(qr[0])
theCircuit.x(qr[1])
theCircuit.cz(qr[0], qr[1])
theCircuit.x(qr[0])
theCircuit.x(qr[1])
#measure the first two qubits in the computational basis
theCircuit.measure(qr[0], cr[0])
theCircuit.measure(qr[1], cr[1])
# dictionary for Bob's operations/circuits
bobCircuits = {}
# Quantum circuits for Bob when receiving idx in 1, 2, 3
for idx in range(1,4):
circuitName = "Bob"+str(idx)
bobCircuits[circuitName] = Q_program.create_circuit(circuitName, [qr], [cr])
theCircuit = bobCircuits[circuitName]
if idx == 1:
theCircuit.x(qr[2])
theCircuit.x(qr[3])
theCircuit.cz(qr[2], qr[3])
theCircuit.x(qr[3])
theCircuit.u1(pi/2.0, qr[2])
theCircuit.x(qr[2])
theCircuit.z(qr[2])
theCircuit.cx(qr[2], qr[3])
theCircuit.cx(qr[3], qr[2])
theCircuit.h(qr[2])
theCircuit.h(qr[3])
theCircuit.x(qr[3])
theCircuit = cu1pi2(theCircuit, qr[2], qr[3])
theCircuit.x(qr[2])
theCircuit.cz(qr[2], qr[3])
theCircuit.x(qr[2])
theCircuit.x(qr[3])
elif idx == 2:
theCircuit.x(qr[2])
theCircuit.x(qr[3])
theCircuit.cz(qr[2], qr[3])
theCircuit.x(qr[3])
theCircuit.u1(pi/2.0, qr[3])
theCircuit.cx(qr[2], qr[3])
theCircuit.h(qr[2])
theCircuit.h(qr[3])
elif idx == 3:
theCircuit.cx(qr[3], qr[2])
theCircuit.x(qr[3])
theCircuit.h(qr[3])
#measure the third and fourth qubits in the computational basis
theCircuit.measure(qr[2], cr[2])
theCircuit.measure(qr[3], cr[3])
a, b = random.randint(1,3), random.randint(1,3) #generate random integers
print("The values of a and b are, resp.,", a,b)
aliceCircuit = aliceCircuits["Alice"+str(a)]
bobCircuit = bobCircuits["Bob"+str(b)]
circuitName = "Alice"+str(a)+"Bob"+str(b)
Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit)
backend = "local_qasm_simulator"
##backend = "ibmqx2"
shots = 1 # We perform a one-shot experiment
results = Q_program.execute([circuitName], backend=backend, shots=shots)
answer = results.get_counts(circuitName)
print(answer)
for key in answer.keys():
aliceAnswer = [int(key[-1]), int(key[-2])]
bobAnswer = [int(key[-3]), int(key[-4])]
if sum(aliceAnswer) % 2 == 0:#the sume of Alice answer must be even
aliceAnswer.append(0)
else:
aliceAnswer.append(1)
if sum(bobAnswer) % 2 == 1:#the sum of Bob answer must be odd
bobAnswer.append(0)
else:
bobAnswer.append(1)
break
print("Alice answer for a = ", a, "is", aliceAnswer)
print("Bob answer for b = ", b, "is", bobAnswer)
if(aliceAnswer[b-1] != bobAnswer[a-1]): #check if the intersection of their answers is the same
print("Alice and Bob lost")
else:
print("Alice and Bob won")
backend = "local_qasm_simulator"
#backend = "ibmqx2"
shots = 10 # We perform 10 shots of experiments for each round
nWins = 0
nLost = 0
for a in range(1,4):
for b in range(1,4):
print("Asking Alice and Bob with a and b are, resp.,", a,b)
rWins = 0
rLost = 0
aliceCircuit = aliceCircuits["Alice"+str(a)]
bobCircuit = bobCircuits["Bob"+str(b)]
circuitName = "Alice"+str(a)+"Bob"+str(b)
Q_program.add_circuit(circuitName, sharedEntangled+aliceCircuit+bobCircuit)
if backend == "ibmqx2":
ibmqx2_backend = Q_program.get_backend_configuration('ibmqx2')
ibmqx2_coupling = ibmqx2_backend['coupling_map']
results = Q_program.execute([circuitName], backend=backend, shots=shots, coupling_map=ibmqx2_coupling, max_credits=3, wait=10, timeout=240)
else:
results = Q_program.execute([circuitName], backend=backend, shots=shots)
answer = results.get_counts(circuitName)
for key in answer.keys():
kfreq = answer[key] #frequencies of keys obtained from measurements
aliceAnswer = [int(key[-1]), int(key[-2])]
bobAnswer = [int(key[-3]), int(key[-4])]
if sum(aliceAnswer) % 2 == 0:
aliceAnswer.append(0)
else:
aliceAnswer.append(1)
if sum(bobAnswer) % 2 == 1:
bobAnswer.append(0)
else:
bobAnswer.append(1)
#print("Alice answer for a = ", a, "is", aliceAnswer)
#print("Bob answer for b = ", b, "is", bobAnswer)
if(aliceAnswer[b-1] != bobAnswer[a-1]):
#print(a, b, "Alice and Bob lost")
nLost += kfreq
rLost += kfreq
else:
#print(a, b, "Alice and Bob won")
nWins += kfreq
rWins += kfreq
print("\t#wins = ", rWins, "out of ", shots, "shots")
print("Number of Games = ", nWins+nLost)
print("Number of Wins = ", nWins)
print("Winning probabilities = ", (nWins*100.0)/(nWins+nLost))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import random
for n in range(5):
print('Flip '+str(n+1))
if random.random()<0.5:
print('HEADS\n')
else:
print('TAILS\n')
import time
for n in range(5):
t = str(time.time())
print('Flip '+str(n+1)+' (system time = ' + t + ')')
if int(t[-1])%2==0:
print('HEADS\n')
else:
print('TAILS\n')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
circ = QuantumCircuit(q, c)
circ.h(q)
circ.measure(q, c)
from qiskit import BasicAer, execute
backend = BasicAer.get_backend('qasm_simulator')
job = execute(circ, backend, shots=5, memory=True)
data = job.result().get_memory()
print(data)
for output in data:
print('Flip with output bit value ' +output)
if output=='0':
print('HEADS\n')
else:
print('TAILS\n')
from qiskit import IBMQ
IBMQ.load_accounts()
backend = IBMQ.get_backend('ibmq_5_tenerife')
job = execute(circ, backend, shots=5, memory=True)
for output in job.result().get_memory():
print('Flip with output bit value ' +output)
if output=='0':
print('HEADS\n')
else:
print('TAILS\n')
job.result().get_memory()
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q, c)
for j in range(n):
circ.h(q[j])
circ.measure(q,c)
job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=8192)
# get the histogram of bit string results, convert it to one of integers and plot it
bit_counts = job.result().get_counts()
int_counts = {}
for bitstring in bit_counts:
int_counts[ int(bitstring,2) ] = bit_counts[bitstring]
from qiskit.tools.visualization import plot_histogram
plot_histogram(int_counts)
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q, c)
for j in range(n):
circ.rx(3.14159/(2.5+j),q[j])
circ.measure(q,c)
job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=8192)
bit_counts = job.result().get_counts()
int_counts = {}
for bitstring in bit_counts:
int_counts[ int(bitstring,2) ] = bit_counts[bitstring]
plot_histogram(int_counts)
job = execute(circ, BasicAer.get_backend('qasm_simulator'), shots=10, memory=True)
data = job.result().get_memory()
print(data)
int_data = []
for bitstring in data:
int_data.append( int(bitstring,2) )
print(int_data)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
import sys
# importing the QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, get_backend
# importing API token to access remote backends
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
backend = 'local_qasm_simulator' # the device to run on
shots = 1024 # the number of shots in the experiment
#to record the rotation number for encoding 00, 10, 11, 01
rotationNumbers = {"00":1, "10":3, "11":5, "01":7}
# Creating registers
# qubit for encoding 2 bits of information
qr = QuantumRegister(1)
# bit for recording the measurement of the qubit
cr = ClassicalRegister(1)
# dictionary for encoding circuits
encodingCircuits = {}
# Quantum circuits for encoding 00, 10, 11, 01
for bits in ("00", "01", "10", "11"):
circuitName = "Encode"+bits
encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
encodingCircuits[circuitName].u3(rotationNumbers[bits]*pi/4.0, 0, 0, qr[0])
encodingCircuits[circuitName].barrier()
# dictionary for decoding circuits
decodingCircuits = {}
# Quantum circuits for decoding the first and second bit
for pos in ("First", "Second"):
circuitName = "Decode"+pos
decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
if pos == "Second": #if pos == "First" we can directly measure
decodingCircuits[circuitName].h(qr[0])
decodingCircuits[circuitName].measure(qr[0], cr[0])
#combine encoding and decoding of QRACs to get a list of complete circuits
circuitNames = []
circuits = []
for k1 in encodingCircuits.keys():
for k2 in decodingCircuits.keys():
circuitNames.append(k1+k2)
circuits.append(encodingCircuits[k1]+decodingCircuits[k2])
print("List of circuit names:", circuitNames) #list of circuit names
job = execute(circuits, backend=backend, shots=shots)
results = job.result()
print("Experimental Result of Encode01DecodeFirst")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85
print("Experimental Result of Encode01DecodeSecond")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85
print("Experimental Result of Encode11DecodeFirst")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeFirst")])) #We should measure "1" with probability 0.85
print("Experimental Result of Encode11DecodeSecond")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode11DecodeSecond")])) #We should measure "1" with probability 0.85
#to enable sleep
import time
backend = "ibmqx4"
#connect to remote API to be able to use remote simulators and real devices
register(qx_config['APItoken'], qx_config['url'])
print("Available backends:", available_backends())
if get_backend(backend).status["available"] is True:
job_exp = execute(circuits, backend=backend, shots=shots)
lapse = 0
interval = 50
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
results = job_exp.result()
print("Experimental Result of Encode01DecodeFirst")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeFirst")])) #We should measure "0" with probability 0.85
print("Experimental Result of Encode01DecodeSecond")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode01DecodeSecond")])) #We should measure "1" with probability 0.85
backend = 'local_qasm_simulator' # the device to run on
shots = 1024 # the number of shots in the experiment
from math import sqrt, cos, acos
#compute the value of theta
theta = acos(sqrt(0.5 + sqrt(3.0)/6.0))
#to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111
rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4),
"100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4),
"001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4),
"101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)}
# Creating registers
# qubit for encoding 3 bits of information
qr = QuantumRegister(1)
# bit for recording the measurement of the qubit
cr = ClassicalRegister(1)
# dictionary for encoding circuits
encodingCircuits = {}
# Quantum circuits for encoding 000, ..., 111
for bits in rotationParams.keys():
circuitName = "Encode"+bits
encodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
encodingCircuits[circuitName].u3(*rotationParams[bits], qr[0])
encodingCircuits[circuitName].barrier()
# dictionary for decoding circuits
decodingCircuits = {}
# Quantum circuits for decoding the first, second and third bit
for pos in ("First", "Second", "Third"):
circuitName = "Decode"+pos
decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
if pos == "Second": #if pos == "First" we can directly measure
decodingCircuits[circuitName].h(qr[0])
elif pos == "Third":
decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[0])
decodingCircuits[circuitName].measure(qr[0], cr[0])
#combine encoding and decoding of QRACs to get a list of complete circuits
circuitNames = []
circuits = []
for k1 in encodingCircuits.keys():
for k2 in decodingCircuits.keys():
circuitNames.append(k1+k2)
circuits.append(encodingCircuits[k1]+decodingCircuits[k2])
print("List of circuit names:", circuitNames) #list of circuit names
job = execute(circuits, backend=backend, shots=shots)
results = job.result()
print("Experimental Result of Encode010DecodeFirst")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78
print("Experimental Result of Encode010DecodeSecond")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78
print("Experimental Result of Encode010DecodeThird")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78
backend = "ibmqx4"
#backend = "local_qasm_simulator"
print("Available backends:", available_backends())
if get_backend(backend).status["available"] is True:
job_exp = execute(circuits, backend=backend, shots=shots)
lapse = 0
interval = 50
while not job_exp.done:
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status)
time.sleep(interval)
lapse += 1
print(job_exp.status)
results = job_exp.result()
print("Experimental Result of Encode010DecodeFirst")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeFirst")])) #We should measure "0" with probability 0.78
print("Experimental Result of Encode010DecodeSecond")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeSecond")])) #We should measure "1" with probability 0.78
print("Experimental Result of Encode010DecodeThird")
plot_histogram(results.get_counts(circuits[circuitNames.index("Encode010DecodeThird")])) #We should measure "0" with probability 0.78
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#initialization
import sys
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing the QISKit
from qiskit import QuantumProgram
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
#set api
from IBMQuantumExperience import IBMQuantumExperience
api = IBMQuantumExperience(token=qx_config['APItoken'], config={'url': qx_config['url']})
#prepare backends
from qiskit.backends import discover_local_backends, discover_remote_backends, get_backend_instance
remote_backends = discover_remote_backends(api) #we have to call this to connect to remote backends
local_backends = discover_local_backends()
# Quantum program setup
Q_program = QuantumProgram()
#for plot with 16qubit
import numpy as np
from functools import reduce
from scipy import linalg as la
from collections import Counter
import matplotlib.pyplot as plt
def plot_histogram5(data, number_to_keep=False):
"""Plot a histogram of data.
data is a dictionary of {'000': 5, '010': 113, ...}
number_to_keep is the number of terms to plot and rest is made into a
single bar called other values
"""
if number_to_keep is not False:
data_temp = dict(Counter(data).most_common(number_to_keep))
data_temp["rest"] = sum(data.values()) - sum(data_temp.values())
data = data_temp
labels = sorted(data)
values = np.array([data[key] for key in labels], dtype=float)
pvalues = values / sum(values)
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects = ax.bar(ind, pvalues, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Probabilities', fontsize=12)
ax.set_xticks(ind)
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])])
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
'%f' % float(height),
ha='center', va='bottom', fontsize=8)
plt.show()
q1_2 = Q_program.create_quantum_register("q1_2", 3)
c1_2 = Q_program.create_classical_register("c1_2", 3)
qw1_2 = Q_program.create_circuit("qw1_2", [q1_2], [c1_2])
t=8 #time
qw1_2.x(q1_2[2])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.measure(q1_2[0], c1_2[0])
qw1_2.measure(q1_2[1], c1_2[2])
qw1_2.measure(q1_2[2], c1_2[1])
print(qw1_2.qasm())
result = Q_program.execute(["qw1_2"], backend='local_qiskit_simulator', shots=1000)
plot_histogram5(result.get_counts("qw1_2"))
result = Q_program.execute(["qw1_2"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=1024)
plot_histogram5(result.get_counts("qw1_2"))
q1 = Q_program.create_quantum_register("q1", 3)
c1 = Q_program.create_classical_register("c1", 3)
qw1 = Q_program.create_circuit("qw1", [q1], [c1])
t=8 #time
qw1.x(q1[1])
qw1.cx(q1[2], q1[1])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.cx(q1[2], q1[1])
qw1.u3(2*t, 0, 0, q1[2])
qw1.measure(q1[0], c1[0])
qw1.measure(q1[1], c1[1])
qw1.measure(q1[2], c1[2])
print(qw1.qasm())
result = Q_program.execute(["qw1"], backend='local_qiskit_simulator')
plot_histogram5(result.get_counts("qw1"))
result = Q_program.execute(["qw1"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=600)
plot_histogram5(result.get_counts("qw1"))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# useful math functions
from math import pi, cos, acos, sqrt
import sys
# importing the QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, get_backend
# importing API token to access remote backends
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def ch(qProg, a, b):
""" Controlled-Hadamard gate """
qProg.h(b)
qProg.sdg(b)
qProg.cx(a, b)
qProg.h(b)
qProg.t(b)
qProg.cx(a, b)
qProg.t(b)
qProg.h(b)
qProg.s(b)
qProg.x(b)
qProg.s(a)
return qProg
def cu3(qProg, theta, phi, lambd, c, t):
""" Controlled-u3 gate """
qProg.u1((lambd-phi)/2, t)
qProg.cx(c, t)
qProg.u3(-theta/2, 0, -(phi+lambd)/2, t)
qProg.cx(c, t)
qProg.u3(theta/2, phi, 0, t)
return qProg
#CHANGE THIS 7BIT 0-1 STRING TO PERFORM EXPERIMENT ON ENCODING 0000000, ..., 1111111
x1234567 = "0101010"
if len(x1234567) != 7 or not("1" in x1234567 or "0" in x1234567):
raise Exception("x1234567 is a 7-bit 0-1 pattern. Please set it to the correct pattern")
#compute the value of rotation angle theta of (3,1)-QRAC
theta = acos(sqrt(0.5 + sqrt(3.0)/6.0))
#to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111
rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4),
"100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4),
"001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4),
"101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)}
# Creating registers
# qubits for encoding 7 bits of information with qr[0] kept by the sender
qr = QuantumRegister(3)
# bits for recording the measurement of the qubits qr[1] and qr[2]
cr = ClassicalRegister(2)
encodingName = "Encode"+x1234567
encodingCircuit = QuantumCircuit(qr, cr, name=encodingName)
#Prepare superposition of mixing QRACs of x1...x6 and x7
encodingCircuit.u3(1.187, 0, 0, qr[0])
#Encoding the seventh bit
seventhBit = x1234567[6]
if seventhBit == "1": #copy qr[0] into qr[1] and qr[2]
encodingCircuit.cx(qr[0], qr[1])
encodingCircuit.cx(qr[0], qr[2])
#perform controlled-Hadamard qr[0], qr[1], and toffoli qr[0], qr[1] , qr[2]
encodingCircuit = ch(encodingCircuit, qr[0], qr[1])
encodingCircuit.ccx(qr[0], qr[1], qr[2])
#End of encoding the seventh bit
#encode x1...x6 with two (3,1)-QRACS. To do that, we must flip q[0] so that the controlled encoding is executed
encodingCircuit.x(qr[0])
#Encoding the first 3 bits 000, ..., 111 into the second qubit, i.e., (3,1)-QRAC on the second qubit
firstThreeBits = x1234567[0:3]
#encodingCircuit.cu3(*rotationParams[firstThreeBits], qr[0], qr[1])
encodingCircuit = cu3(encodingCircuit, *rotationParams[firstThreeBits], qr[0], qr[1])
#Encoding the second 3 bits 000, ..., 111 into the third qubit, i.e., (3,1)-QRAC on the third qubit
secondThreeBits = x1234567[3:6]
#encodingCircuit.cu3(*rotationParams[secondTreeBits], qr[0], qr[2])
encodingCircuit = cu3(encodingCircuit, *rotationParams[secondThreeBits], qr[0], qr[2])
#end of encoding
encodingCircuit.barrier()
# dictionary for decoding circuits
decodingCircuits = {}
# Quantum circuits for decoding the 1st to 6th bits
for i, pos in enumerate(["First", "Second", "Third", "Fourth", "Fifth", "Sixth"]):
circuitName = "Decode"+pos
decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
if i < 3: #measure 1st, 2nd, 3rd bit
if pos == "Second": #if pos == "First" we can directly measure
decodingCircuits[circuitName].h(qr[1])
elif pos == "Third":
decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[1])
decodingCircuits[circuitName].measure(qr[1], cr[1])
else: #measure 4th, 5th, 6th bit
if pos == "Fifth": #if pos == "Fourth" we can directly measure
decodingCircuits[circuitName].h(qr[2])
elif pos == "Sixth":
decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[2])
decodingCircuits[circuitName].measure(qr[2], cr[1])
#Quantum circuits for decoding the 7th bit
decodingCircuits["DecodeSeventh"] = QuantumCircuit(qr, cr, name="DecodeSeventh")
decodingCircuits["DecodeSeventh"].measure(qr[1], cr[0])
decodingCircuits["DecodeSeventh"].measure(qr[2], cr[1])
#combine encoding and decoding of (7,2)-QRACs to get a list of complete circuits
circuitNames = []
circuits = []
k1 = encodingName
for k2 in decodingCircuits.keys():
circuitNames.append(k1+k2)
circuits.append(encodingCircuit+decodingCircuits[k2])
print("List of circuit names:", circuitNames) #list of circuit names
#Q_program.get_qasms(circuitNames) #list qasms codes
backend = "local_qasm_simulator"
#backend = "ibmqx2"
shots = 1000
job = execute(circuits, backend=backend, shots=shots)
results = job.result()
for k in ["DecodeFirst", "DecodeSecond", "DecodeThird", "DecodeFourth", "DecodeFifth", "DecodeSixth"]:
print("Experimental Result of ", encodingName+k)
plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+k)]))
print("Experimental result of ", encodingName+"DecodeSeventh")
plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+"DecodeSeventh")]))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from collections import Counter #Use this to convert results from list to dict for histogram
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
import Qconfig
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
device = 'ibmqx2' # the device to run on
#device = 'local_qasm_simulator' # uncomment to run on the simulator
N = 50 # Number of bombs
steps = 20 # Number of steps for the algorithm, limited by maximum circuit depth
eps = np.pi / steps # Algorithm parameter, small
QPS_SPECS = {
"name": "IFM",
"circuits": [{
"name": "IFM_gen", # Prototype circuit for bomb generation
"quantum_registers": [{
"name":"q_gen",
"size":1
}],
"classical_registers": [{
"name":"c_gen",
"size":1
}]},
{"name": "IFM_meas", # Prototype circuit for bomb measurement
"quantum_registers": [{
"name":"q",
"size":2
}],
"classical_registers": [{
"name":"c",
"size":steps+1
}]}]
}
Q_program = QuantumProgram(specs=QPS_SPECS)
Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"])
# Quantum circuits to generate bombs
circuits = ["IFM_gen"+str(i) for i in range(N)]
# NB: Can't have more than one measurement per circuit
for circuit in circuits:
q_gen = Q_program.get_quantum_register("q_gen")
c_gen = Q_program.get_classical_register('c_gen')
IFM = Q_program.create_circuit(circuit, [q_gen], [c_gen])
IFM.h(q_gen[0]) #Turn the qubit into |0> + |1>
IFM.measure(q_gen[0], c_gen[0])
_ = Q_program.get_qasms(circuits) # Suppress the output
result = Q_program.execute(circuits, device, shots=1, max_credits=5, wait=10, timeout=240) # Note that we only want one shot
bombs = []
for circuit in circuits:
for key in result.get_counts(circuit): # Hack, there should only be one key, since there was only one shot
bombs.append(int(key))
#print(', '.join(('Live' if bomb else 'Dud' for bomb in bombs))) # Uncomment to print out "truth" of bombs
plot_histogram(Counter(('Live' if bomb else 'Dud' for bomb in bombs))) #Plotting bomb generation results
device = 'local_qasm_simulator' #Running on the simulator
circuits = ["IFM_meas"+str(i) for i in range(N)]
#Creating one measurement circuit for each bomb
for i in range(N):
bomb = bombs[i]
q = Q_program.get_quantum_register("q")
c = Q_program.get_classical_register('c')
IFM = Q_program.create_circuit(circuits[i], [q], [c])
for step in range(steps):
IFM.ry(eps, q[0]) #First we rotate the control qubit by epsilon
if bomb: #If the bomb is live, the gate is a controlled X gate
IFM.cx(q[0],q[1])
#If the bomb is a dud, the gate is a controlled identity gate, which does nothing
IFM.measure(q[1], c[step]) #Now we measure to collapse the combined state
IFM.measure(q[0], c[steps])
Q_program.get_qasms(circuits)
result = Q_program.execute(circuits, device, shots=1, max_credits=5, wait=10, timeout=240)
def get_status(counts):
# Return whether a bomb was a dud, was live but detonated, or was live and undetonated
# Note that registers are returned in reversed order
for key in counts:
if '1' in key[1:]:
#If we ever measure a '1' from the measurement qubit (q1), the bomb was measured and will detonate
return '!!BOOM!!'
elif key[0] == '1':
#If the control qubit (q0) was rotated to '1', the state never entangled because the bomb was a dud
return 'Dud'
else:
#If we only measured '0' for both the control and measurement qubit, the bomb was live but never set off
return 'Live'
results = {'Live': 0, 'Dud': 0, "!!BOOM!!": 0}
for circuit in circuits:
status = get_status(result.get_counts(circuit))
results[status] += 1
plot_histogram(results)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
import Qconfig
# import tomography library
import qiskit.tools.qcvv.tomography as tomo
#visualization packages
from qiskit.tools.visualization import plot_wigner_function, plot_wigner_data
density_matrix = np.matrix([[0.5, 0, 0, 0.5],[0, 0, 0, 0],[0, 0, 0, 0],[0.5, 0, 0, 0.5]])
print(density_matrix)
plot_wigner_function(density_matrix, res=200)
import sympy as sym
from sympy.physics.quantum import TensorProduct
num = int(np.log2(len(density_matrix)))
harr = sym.sqrt(3)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(density_matrix*Delta)
print(sym.latex(W))
Q_program = QuantumProgram()
number_of_qubits = 2
backend = 'local_qasm_simulator'
shots = 1024
bell_qubits = [0, 1]
qr = Q_program.create_quantum_register('qr',2)
cr = Q_program.create_classical_register('cr',2)
bell = Q_program.create_circuit('bell', [qr], [cr])
bell.h(qr[0])
bell.cx(qr[0],qr[1])
bell_tomo_set = tomo.state_tomography_set([0, 1])
bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set)
bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots)
bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set)
rho_fit_sim = tomo.fit_tomography_data(bell_tomo_data)
plot_wigner_function(np.matrix(rho_fit_sim),res=200)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(np.matrix(rho_fit_sim)*Delta)
print(sym.latex(W))
Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])
backend = 'ibmqx2'
max_credits = 8
shots = 1024
bell_qubits = [0, 1]
bell_tomo_set = tomo.state_tomography_set(bell_qubits)
bell_tomo_circuits = tomo.create_tomography_circuits(Q_program, 'bell', qr, cr, bell_tomo_set)
bell_tomo_result = Q_program.execute(bell_tomo_circuits, backend=backend, shots=shots,
max_credits=max_credits, timeout=300)
bell_tomo_data = tomo.tomography_data(bell_tomo_result, 'bell', bell_tomo_set)
rho_fit_ibmqx = tomo.fit_tomography_data(bell_tomo_data)
plot_wigner_function(np.matrix(rho_fit_ibmqx), res=100)
print(rho_fit_ibmqx)
Delta_su2 = sym.zeros(2)
Delta = sym.ones(1)
for qubit in range(num):
phi = sym.Indexed('phi', qubit)
theta = sym.Indexed('theta', qubit)
costheta = harr*sym.cos(2*theta)
sintheta = harr*sym.sin(2*theta)
Delta_su2[0,0] = (1+costheta)/2
Delta_su2[0,1] = -(sym.exp(2j*phi)*sintheta)/2
Delta_su2[1,0] = -(sym.exp(-2j*phi)*sintheta)/2
Delta_su2[1,1] = (1-costheta)/2
Delta = TensorProduct(Delta,Delta_su2)
W = sym.trace(np.matrix(rho_fit_ibmqx)*Delta)
print(sym.latex(W))
theta1_points = 8
theta2_points = 8
number_of_points = theta1_points*theta2_points
the1 = [0]*number_of_points
the2 = [0]*number_of_points #initialize theta values
phis = [[0]*number_of_points]*number_of_qubits #set phi values to 0
point = 0
for i in range(theta1_points):
for k in range(theta2_points):
the1[point] = 2*i*np.pi/theta1_points
the2[point] = 2*k*np.pi/theta2_points #create the values of theta for all points on plot
point += 1
thetas = np.vstack((the1,the2))
bell_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas,
bell_qubits, qr, cr)
backend = 'local_qasm_simulator'
shots = 1024
bell_result = Q_program.execute(bell_circuits, backend=backend, shots=shots)
print(bell_result)
wdata = tomo.wigner_data(bell_result, bell_qubits,
bell_circuits, shots=shots)
wdata = np.matrix(wdata)
wdata = wdata.reshape(theta1_points,theta2_points)
plot_wigner_data(wdata, method='plaquette')
equator_points = 64
theta = [np.pi/2]*equator_points
phi = [0]*equator_points
point = 0
for i in range(equator_points):
phi[i] = 2*i*np.pi/equator_points
thetas = np.vstack((theta,theta))
phis = np.vstack((phi,phi))
bell_eq_circuits = tomo.build_wigner_circuits(Q_program, 'bell', phis, thetas,
bell_qubits, qr, cr)
bell_eq_result = Q_program.execute(bell_eq_circuits, backend=backend, shots=shots)
wdata_eq = tomo.wigner_data(bell_eq_result, bell_qubits,
bell_eq_circuits, shots=shots)
plot_wigner_data(wdata_eq, method='curve')
Q_program = QuantumProgram()
number_of_qubits = 5
backend = 'local_qasm_simulator'
shots = 1024
ghz_qubits = [0, 1, 2, 3, 4]
qr = Q_program.create_quantum_register('qr',5)
cr = Q_program.create_classical_register('cr',5)
ghz = Q_program.create_circuit('ghz', [qr], [cr])
ghz.h(qr[0])
ghz.h(qr[1])
ghz.x(qr[2])
ghz.h(qr[3])
ghz.h(qr[4])
ghz.cx(qr[0],qr[2])
ghz.cx(qr[1],qr[2])
ghz.cx(qr[3],qr[2])
ghz.cx(qr[4],qr[2])
ghz.h(qr[0])
ghz.h(qr[1])
ghz.h(qr[2])
ghz.h(qr[3])
ghz.h(qr[4])
equator_points = 64
thetas = [[np.pi/2]*equator_points]*number_of_qubits
phi = [0]*equator_points
point = 0
for i in range(equator_points):
phi[i] = 2*i*np.pi/equator_points
phis = np.vstack((phi,phi,phi,phi,phi))
ghz_eq_circuits = tomo.build_wigner_circuits(Q_program, 'ghz', phis, thetas,
ghz_qubits, qr, cr)
ghz_eq_result = Q_program.execute(ghz_eq_circuits, backend=backend, shots=shots, timeout = 300)
wghzdata_eq = tomo.wigner_data(ghz_eq_result, ghz_qubits,
ghz_eq_circuits, shots=shots)
plot_wigner_data(wghzdata_eq, method='curve')
import matplotlib.pyplot as plt
plt.plot(phi, wghzdata_eq, 'o')
plt.axis([0, 2*np.pi, -0.6, 0.6])
plt.show()
density_matrix = np.zeros((32,32))
density_matrix[0][0] = 0.5
density_matrix[0][31] = -0.5
density_matrix[31][0] = -0.5
density_matrix[31][31] = 0.5
plot_wigner_function(density_matrix, res=200)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer, IBMQ
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuits = []
# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
qc_phase_gate.h(qr)
qc_phase_gate.u1(phase, qr)
qc_phase_gate.h(qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(qc_phase_gate)
# Visualising one of the circuits as an example
circuits[25].draw(output='mpl')
# To run using qasm simulator
backend = BasicAer.get_backend('qasm_simulator')
# the number of shots in the experiment
shots = 1024
result = execute(circuits, backend=backend, shots=shots).result()
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.25,1/np.sqrt(2),'ro',0.5,0,'ko',1,-1,'go',-0.25,1/np.sqrt(2),'rx',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of X')
plt.show()
# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuits = []
# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
phase_shift = phase_index-50
phase = 2*np.pi*phase_shift/50
circuit_name = "phase_gate_%d"%phase_index
qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
qc_phase_gate.u3(phase,0,np.pi, qr)
qc_phase_gate.measure(qr[0], cr[0])
circuits.append(qc_phase_gate)
# Visualising one of the circuits as an example
circuits[75].draw(output='mpl')
# To run of qasm simulator
backend = BasicAer.get_backend('qasm_simulator')
# the number of shots in the experiment
shots = 1024
result = execute(circuits, backend=backend, shots=shots).result()
probz = []
phase_value = []
for phase_index in phase_vector:
phase_shift = phase_index - 50
phase_value.append(2*phase_shift/50)
if '0' in result.get_counts(circuits[phase_index]):
probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
else:
probz.append(-1)
plt.plot(phase_value, probz, 'b',0.5,0,'ko',1,-1,'go',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of Z')
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, IBMQ, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
backend = BasicAer.get_backend('qasm_simulator') # run on local simulator by default
# Uncomment the following lines to run on a real device
# IBMQ.load_accounts()
# from qiskit.backends.ibmq import least_busy
# backend = least_busy(IBMQ.backends(operational=True, simulator=False))
# print("the best backend is " + backend.name())
# Creating registers
q2 = QuantumRegister(2)
c1 = ClassicalRegister(1)
c2 = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
# quantum circuit to measure q0 in the standard basis
measureIZ = QuantumCircuit(q2, c1)
measureIZ.measure(q2[0], c1[0])
bellIZ = bell+measureIZ
# quantum circuit to measure q0 in the superposition basis
measureIX = QuantumCircuit(q2, c1)
measureIX.h(q2[0])
measureIX.measure(q2[0], c1[0])
bellIX = bell+measureIX
# quantum circuit to measure q1 in the standard basis
measureZI = QuantumCircuit(q2, c1)
measureZI.measure(q2[1], c1[0])
bellZI = bell+measureZI
# quantum circuit to measure q1 in the superposition basis
measureXI = QuantumCircuit(q2, c1)
measureXI.h(q2[1])
measureXI.measure(q2[1], c1[0])
bellXI = bell+measureXI
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2[0])
measureXX.h(q2[1])
measureXX.measure(q2[0], c2[0])
measureXX.measure(q2[1], c2[1])
bellXX = bell+measureXX
bellIZ.draw(output='mpl')
bellIX.draw(output='mpl')
bellZI.draw(output='mpl')
bellXI.draw(output='mpl')
bellZZ.draw(output='mpl')
bellXX.draw(output='mpl')
circuits = [bellIZ,bellIX,bellZI,bellXI,bellZZ,bellXX]
job = execute(circuits, backend)
result = job.result()
plot_histogram(result.get_counts(bellIZ))
result.get_counts(bellIZ)
plot_histogram(result.get_counts(bellIX))
plot_histogram(result.get_counts(bellZI))
plot_histogram(result.get_counts(bellXI))
plot_histogram(result.get_counts(bellZZ))
plot_histogram(result.get_counts(bellXX))
# quantum circuit to make a mixed state
mixed1 = QuantumCircuit(q2, c2)
mixed2 = QuantumCircuit(q2, c2)
mixed2.x(q2)
mixed1.measure(q2[0], c2[0])
mixed1.measure(q2[1], c2[1])
mixed2.measure(q2[0], c2[0])
mixed2.measure(q2[1], c2[1])
mixed1.draw(output='mpl')
mixed2.draw(output='mpl')
mixed_state = [mixed1,mixed2]
job = execute(mixed_state, backend)
result = job.result()
counts1 = result.get_counts(mixed_state[0])
counts2 = result.get_counts(mixed_state[1])
from collections import Counter
ground = Counter(counts1)
excited = Counter(counts2)
plot_histogram(ground+excited)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Imports
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info.analyzation.average import average_data
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
IBMQ.load_accounts()
# use simulator to learn more about entangled quantum states where possible
sim_backend = BasicAer.get_backend('qasm_simulator')
sim_shots = 8192
# use device to test entanglement
device_shots = 1024
device_backend = least_busy(IBMQ.backends(operational=True, simulator=False))
print("the best backend is " + device_backend.name())
# Creating registers
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make an entangled bell state
bell = QuantumCircuit(q, c)
bell.h(q[0])
bell.cx(q[0], q[1])
# quantum circuit to measure q in the standard basis
measureZZ = QuantumCircuit(q, c)
measureZZ.measure(q[0], c[0])
measureZZ.measure(q[1], c[1])
bellZZ = bell+measureZZ
# quantum circuit to measure q in the superposition basis
measureXX = QuantumCircuit(q, c)
measureXX.h(q[0])
measureXX.h(q[1])
measureXX.measure(q[0], c[0])
measureXX.measure(q[1], c[1])
bellXX = bell+measureXX
# quantum circuit to measure ZX
measureZX = QuantumCircuit(q, c)
measureZX.h(q[0])
measureZX.measure(q[0], c[0])
measureZX.measure(q[1], c[1])
bellZX = bell+measureZX
# quantum circuit to measure XZ
measureXZ = QuantumCircuit(q, c)
measureXZ.h(q[1])
measureXZ.measure(q[0], c[0])
measureXZ.measure(q[1], c[1])
bellXZ = bell+measureXZ
circuits = [bellZZ,bellXX,bellZX,bellXZ]
bellZZ.draw(output='mpl')
bellXX.draw(output='mpl')
bellZX.draw(output='mpl')
bellXZ.draw(output='mpl')
job = execute(circuits, backend=device_backend, shots=device_shots)
job_monitor(job)
result = job.result()
observable_first ={'00': 1, '01': -1, '10': 1, '11': -1}
observable_second ={'00': 1, '01': 1, '10': -1, '11': -1}
observable_correlated ={'00': 1, '01': -1, '10': -1, '11': 1}
print('IZ = ' + str(average_data(result.get_counts(bellZZ),observable_first)))
print('ZI = ' + str(average_data(result.get_counts(bellZZ),observable_second)))
print('ZZ = ' + str(average_data(result.get_counts(bellZZ),observable_correlated)))
print('IX = ' + str(average_data(result.get_counts(bellXX),observable_first)))
print('XI = ' + str(average_data(result.get_counts(bellXX),observable_second)))
print('XX = ' + str(average_data(result.get_counts(bellXX),observable_correlated)))
print('ZX = ' + str(average_data(result.get_counts(bellZX),observable_correlated)))
print('XZ = ' + str(average_data(result.get_counts(bellXZ),observable_correlated)))
CHSH = lambda x : x[0]+x[1]+x[2]-x[3]
measure = [measureZZ, measureZX, measureXX, measureXZ]
# Theory
sim_chsh_circuits = []
sim_x = []
sim_steps = 30
for step in range(sim_steps):
theta = 2.0*np.pi*step/30
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
sim_chsh_circuits.append(bell+bell_middle+m)
sim_x.append(theta)
job = execute(sim_chsh_circuits, backend=sim_backend, shots=sim_shots)
result = job.result()
sim_chsh = []
circ = 0
for x in range(len(sim_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(average_data(result.get_counts(sim_chsh_circuits[circ].name),observable_correlated))
circ += 1
sim_chsh.append(CHSH(temp_chsh))
# Experiment
real_chsh_circuits = []
real_x = []
real_steps = 10
for step in range(real_steps):
theta = 2.0*np.pi*step/10
bell_middle = QuantumCircuit(q,c)
bell_middle.ry(theta,q[0])
for m in measure:
real_chsh_circuits.append(bell+bell_middle+m)
real_x.append(theta)
job = execute(real_chsh_circuits, backend=device_backend, shots=device_shots)
job_monitor(job)
result = job.result()
real_chsh = []
circ = 0
for x in range(len(real_x)):
temp_chsh = []
for m in range(len(measure)):
temp_chsh.append(average_data(result.get_counts(real_chsh_circuits[circ].name),observable_correlated))
circ += 1
real_chsh.append(CHSH(temp_chsh))
plt.plot(sim_x, sim_chsh, 'r-', real_x, real_chsh, 'bo')
plt.plot([0, 2*np.pi], [2, 2], 'b-')
plt.plot([0, 2*np.pi], [-2, -2], 'b-')
plt.grid()
plt.ylabel('CHSH', fontsize=20)
plt.xlabel(r'$Y(\theta)$', fontsize=20)
plt.show()
print(real_chsh)
# 2 - qubits
# quantum circuit to make GHZ state
q2 = QuantumRegister(2)
c2 = ClassicalRegister(2)
ghz = QuantumCircuit(q2, c2)
ghz.h(q2[0])
ghz.cx(q2[0],q2[1])
# quantum circuit to measure q in standard basis
measureZZ = QuantumCircuit(q2, c2)
measureZZ.measure(q2[0], c2[0])
measureZZ.measure(q2[1], c2[1])
ghzZZ = ghz+measureZZ
measureXX = QuantumCircuit(q2, c2)
measureXX.h(q2[0])
measureXX.h(q2[1])
measureXX.measure(q2[0], c2[0])
measureXX.measure(q2[1], c2[1])
ghzXX = ghz+measureXX
circuits2 = [ghzZZ, ghzXX]
ghzZZ.draw(output='mpl')
ghzXX.draw(output='mpl')
job2 = execute(circuits2, backend=sim_backend, shots=sim_shots)
result2 = job2.result()
plot_histogram(result2.get_counts(ghzZZ))
plot_histogram(result2.get_counts(ghzXX))
# 3 - qubits
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[1],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
circuits3 = [ghzZZZ, ghzXXX]
ghzZZZ.draw(output='mpl')
ghzXXX.draw(output='mpl')
job3 = execute(circuits3, backend=sim_backend, shots=sim_shots)
result3 = job3.result()
plot_histogram(result3.get_counts(ghzZZZ))
plot_histogram(result3.get_counts(ghzXXX))
# 4 - qubits
# quantum circuit to make GHZ state
q4 = QuantumRegister(4)
c4 = ClassicalRegister(4)
ghz4 = QuantumCircuit(q4, c4)
ghz4.h(q4[0])
ghz4.cx(q4[0],q4[1])
ghz4.cx(q4[1],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
ghz4.cx(q4[3],q4[2])
ghz4.h(q4[3])
ghz4.h(q4[2])
# quantum circuit to measure q in standard basis
measureZZZZ = QuantumCircuit(q4, c4)
measureZZZZ.measure(q4[0], c4[0])
measureZZZZ.measure(q4[1], c4[1])
measureZZZZ.measure(q4[2], c4[2])
measureZZZZ.measure(q4[3], c4[3])
ghzZZZZ = ghz4+measureZZZZ
measureXXXX = QuantumCircuit(q4, c4)
measureXXXX.h(q4[0])
measureXXXX.h(q4[1])
measureXXXX.h(q4[2])
measureXXXX.h(q4[3])
measureXXXX.measure(q4[0], c4[0])
measureXXXX.measure(q4[1], c4[1])
measureXXXX.measure(q4[2], c4[2])
measureXXXX.measure(q4[3], c4[3])
ghzXXXX = ghz4+measureXXXX
circuits4 = [ghzZZZZ, ghzXXXX]
ghzZZZZ.draw(output='mpl')
ghzXXXX.draw(output='mpl')
job4 = execute(circuits4, backend=sim_backend, shots=sim_shots)
result4 = job4.result()
plot_histogram(result4.get_counts(ghzZZZZ))
plot_histogram(result4.get_counts(ghzXXXX))
# quantum circuit to make GHZ state
q3 = QuantumRegister(3)
c3 = ClassicalRegister(3)
ghz3 = QuantumCircuit(q3, c3)
ghz3.h(q3[0])
ghz3.cx(q3[0],q3[1])
ghz3.cx(q3[0],q3[2])
# quantum circuit to measure q in standard basis
measureZZZ = QuantumCircuit(q3, c3)
measureZZZ.measure(q3[0], c3[0])
measureZZZ.measure(q3[1], c3[1])
measureZZZ.measure(q3[2], c3[2])
ghzZZZ = ghz3+measureZZZ
circuits5 = [ghzZZZ]
ghzZZZ.draw(output='mpl')
job5 = execute(circuits5, backend=sim_backend, shots=sim_shots)
result5 = job5.result()
plot_histogram(result5.get_counts(ghzZZZ))
MerminM = lambda x : x[0]*x[1]*x[2]*x[3]
observable ={'000': 1, '001': -1, '010': -1, '011': 1, '100': -1, '101': 1, '110': 1, '111': -1}
# quantum circuit to measure q XXX
measureXXX = QuantumCircuit(q3, c3)
measureXXX.h(q3[0])
measureXXX.h(q3[1])
measureXXX.h(q3[2])
measureXXX.measure(q3[0], c3[0])
measureXXX.measure(q3[1], c3[1])
measureXXX.measure(q3[2], c3[2])
ghzXXX = ghz3+measureXXX
# quantum circuit to measure q XYY
measureXYY = QuantumCircuit(q3, c3)
measureXYY.s(q3[1]).inverse()
measureXYY.s(q3[2]).inverse()
measureXYY.h(q3[0])
measureXYY.h(q3[1])
measureXYY.h(q3[2])
measureXYY.measure(q3[0], c3[0])
measureXYY.measure(q3[1], c3[1])
measureXYY.measure(q3[2], c3[2])
ghzXYY = ghz3+measureXYY
# quantum circuit to measure q YXY
measureYXY = QuantumCircuit(q3, c3)
measureYXY.s(q3[0]).inverse()
measureYXY.s(q3[2]).inverse()
measureYXY.h(q3[0])
measureYXY.h(q3[1])
measureYXY.h(q3[2])
measureYXY.measure(q3[0], c3[0])
measureYXY.measure(q3[1], c3[1])
measureYXY.measure(q3[2], c3[2])
ghzYXY = ghz3+measureYXY
# quantum circuit to measure q YYX
measureYYX = QuantumCircuit(q3, c3)
measureYYX.s(q3[0]).inverse()
measureYYX.s(q3[1]).inverse()
measureYYX.h(q3[0])
measureYYX.h(q3[1])
measureYYX.h(q3[2])
measureYYX.measure(q3[0], c3[0])
measureYYX.measure(q3[1], c3[1])
measureYYX.measure(q3[2], c3[2])
ghzYYX = ghz3+measureYYX
circuits6 = [ghzXXX, ghzYYX, ghzYXY, ghzXYY]
ghzXXX.draw(output='mpl')
ghzYYX.draw(output='mpl')
ghzYXY.draw(output='mpl')
ghzXYY.draw(output='mpl')
job6 = execute(circuits6, backend=device_backend, shots=device_shots)
job_monitor(job6)
result6 = job6.result()
temp=[]
temp.append(average_data(result6.get_counts(ghzXXX),observable))
temp.append(average_data(result6.get_counts(ghzYYX),observable))
temp.append(average_data(result6.get_counts(ghzYXY),observable))
temp.append(average_data(result6.get_counts(ghzXYY),observable))
print(MerminM(temp))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from pprint import pprint
# importing QISKit
from qiskit import QuantumProgram, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import available_backends, execute, register, least_busy
# import basic plot tools
from qiskit.tools.visualization import plot_histogram, circuit_drawer
backend = 'local_qasm_simulator' # run on local simulator by default
# Uncomment the following lines to run on a real device
# register(qx_config['APItoken'], qx_config['url'])
# backend = least_busy(available_backends({'simulator': False, 'local': False}))
# print("the best backend is " + backend)
# Creating registers
tq = QuantumRegister(3)
tc0 = ClassicalRegister(1)
tc1 = ClassicalRegister(1)
tc2 = ClassicalRegister(1)
# Quantum circuit to make the shared entangled state
teleport = QuantumCircuit(tq, tc0,tc1,tc2)
teleport.h(tq[1])
teleport.cx(tq[1], tq[2])
teleport.ry(np.pi/4,tq[0])
teleport.cx(tq[0], tq[1])
teleport.h(tq[0])
teleport.barrier()
teleport.measure(tq[0], tc0[0])
teleport.measure(tq[1], tc1[0])
teleport.z(tq[2]).c_if(tc0, 1)
teleport.x(tq[2]).c_if(tc1, 1)
teleport.measure(tq[2], tc2[0])
circuit_drawer(teleport)
teleport_job = execute(teleport, 'local_qasm_simulator') # note that this circuit doesn't run on a real device
teleport_result = teleport_job.result()
data = teleport_result.get_counts(teleport)
alice = {}
alice['00'] = data['0 0 0'] + data['1 0 0']
alice['10'] = data['0 1 0'] + data['1 1 0']
alice['01'] = data['0 0 1'] + data['1 0 1']
alice['11'] = data['0 1 1'] + data['1 1 1']
plot_histogram(alice)
bob = {}
bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
plot_histogram(bob)
# Creating registers
sdq = QuantumRegister(2)
sdc = ClassicalRegister(2)
# Quantum circuit to make the shared entangled state
superdense = QuantumCircuit(sdq, sdc)
superdense.h(sdq[0])
superdense.cx(sdq[0], sdq[1])
# For 00, do nothing
# For 01, apply $X$
#shared.x(q[0])
# For 01, apply $Z$
#shared.z(q[0])
# For 11, apply $XZ$
superdense.z(sdq[0])
superdense.x(sdq[0])
superdense.barrier()
superdense.cx(sdq[0], sdq[1])
superdense.h(sdq[0])
superdense.measure(sdq[0], sdc[0])
superdense.measure(sdq[1], sdc[1])
circuit_drawer(superdense)
superdense_job = execute(superdense, backend)
superdense_result = superdense_job.result()
plot_histogram(superdense_result.get_counts(superdense))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
from qiskit.circuit import QuantumCircuit, Parameter
import warnings
warnings.filterwarnings('ignore')
theta = Parameter("θ")
phi = Parameter("φ")
lamb = Parameter("λ")
def sampleCircuitA(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
circuit.barrier()
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
return circuit
circuitA = sampleCircuitA(qubits=4)
circuitA.draw(output='mpl')
def sampleCircuitB1(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u1(theta, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u1(theta, j)
return circuit
def sampleCircuitB2(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u2(phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u2(phi, lamb, j)
return circuit
def sampleCircuitB3(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u3(theta, phi, lamb, j)
return circuit
circuitB1 = sampleCircuitB1(qubits=4)
circuitB1.draw(output='mpl')
circuitB2 = sampleCircuitB2(qubits=4)
circuitB2.draw(output='mpl')
circuitB3 = sampleCircuitB3(qubits=4)
circuitB3.draw(output='mpl')
def sampleCircuitC(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
circuit.barrier()
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, 3, 2)
circuit.crx(theta, 0, 3)
circuit.crx(theta, 1, 0)
circuit.crx(theta, 2, 1)
return circuit
circuitC = sampleCircuitC(qubits=4)
circuitC.draw(output='mpl')
def sampleCircuitD(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(qubits - 1, -1, -1):
for k in range(qubits - 1, -1, -1):
if j != k:
circuit.crx(theta, j, k)
circuit.barrier()
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
return circuit
circuitD = sampleCircuitD(qubits=4)
circuitD.draw(output='mpl')
def sampleCircuitE(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(1, qubits, 2):
circuit.crx(theta, j, j - 1)
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(2, qubits, 2):
circuit.crx(theta, j, j - 1)
return circuit
circuitE = sampleCircuitE(qubits=4)
circuitE.draw(output='mpl')
def sampleCircuitF(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
return circuit
circuitF = sampleCircuitF(qubits=4)
circuitF.draw(output='mpl')
def sampleEncoding(qubits):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.h(i)
circuit.ry(theta, i)
return circuit
circuit = sampleEncoding(4)
circuit.draw(output='mpl')
# demo:
circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5))
circuit.draw(output='mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
IBMQ.load_accounts()
backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None)
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
def DJ_N3(qc):
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[2])
qc.z(q[0])
qc.cx(q[1], q[2])
qc.h(q[2])
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.measure(q,c)
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3,'c')
# Create a Quantum Circuit acting on the q register
qc = QuantumCircuit(q,c)
DJ_N3(qc)
qc.draw()
job_hpc = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
result_hpc = job_hpc.result()
counts_hpc = result_hpc.get_counts(qc)
plot_histogram(counts_hpc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qiskit.__qiskit_version__
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.visualization import plot_histogram
q = QuantumRegister(6)
qc = QuantumCircuit(q)
qc.x(q[2])
qc.cx(q[1], q[5])
qc.cx(q[2], q[5])
qc.cx(q[3], q[5])
qc.ccx(q[1], q[2], q[4])
qc.ccx(q[3], q[4], q[5])
qc.ccx(q[1], q[2], q[4])
qc.x(q[2])
qc.draw(output='mpl')
def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula):
"""Circuit that computes the black-box function from f_in to f_out.
Create a circuit that verifies whether a given exactly-1 3-SAT
formula is satisfied by the input. The exactly-1 version
requires exactly one literal out of every clause to be satisfied.
"""
num_clauses = len(exactly_1_3_sat_formula)
for (k, clause) in enumerate(exactly_1_3_sat_formula):
# This loop ensures aux[k] is 1 if an odd number of literals
# are true
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
# Flip aux[k] if all literals are true, using auxiliary qubit
# (ancilla) aux[num_clauses]
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
# Flip back to reverse state of negative literals and ancilla
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# The formula is satisfied if and only if all auxiliary qubits
# except aux[num_clauses] are 1
if (num_clauses == 1):
circuit.cx(aux[0], f_out[0])
elif (num_clauses == 2):
circuit.ccx(aux[0], aux[1], f_out[0])
elif (num_clauses == 3):
circuit.ccx(aux[0], aux[1], aux[num_clauses])
circuit.ccx(aux[2], aux[num_clauses], f_out[0])
circuit.ccx(aux[0], aux[1], aux[num_clauses])
else:
raise ValueError('We only allow at most 3 clauses')
# Flip back any auxiliary qubits to make sure state is consistent
# for future executions of this routine; same loop as above.
for (k, clause) in enumerate(exactly_1_3_sat_formula):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# -- end function
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 ' +
'controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
# -- end function
def inversion_about_average(circuit, f_in, n):
"""Apply inversion about the average step of Grover's algorithm."""
# Hadamards everywhere
for j in range(n):
circuit.h(f_in[j])
# D matrix: flips the sign of the state |000> only
for j in range(n):
circuit.x(f_in[j])
n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1])
for j in range(n):
circuit.x(f_in[j])
# Hadamards everywhere again
for j in range(n):
circuit.h(f_in[j])
# -- end function
qr = QuantumRegister(3)
qInvAvg = QuantumCircuit(qr)
inversion_about_average(qInvAvg, qr, 3)
qInvAvg.draw(output='mpl')
"""
Grover search implemented in Qiskit.
This module contains the code necessary to run Grover search on 3
qubits, both with a simulator and with a real quantum computing
device. This code is the companion for the paper
"An introduction to quantum computing, without the physics",
Giacomo Nannicini, https://arxiv.org/abs/1708.03684.
"""
def input_state(circuit, f_in, f_out, n):
"""(n+1)-qubit input state for Grover search."""
for j in range(n):
circuit.h(f_in[j])
circuit.x(f_out)
circuit.h(f_out)
# -- end function
# Make a quantum program for the n-bit Grover search.
n = 3
# Exactly-1 3-SAT formula to be satisfied, in conjunctive
# normal form. We represent literals with integers, positive or
# negative, to indicate a Boolean variable or its negation.
exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]]
# Define three quantum registers: 'f_in' is the search space (input
# to the function f), 'f_out' is bit used for the output of function
# f, aux are the auxiliary bits used by f to perform its
# computation.
f_in = QuantumRegister(n)
f_out = QuantumRegister(1)
aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1)
# Define classical register for algorithm result
ans = ClassicalRegister(n)
# Define quantum circuit with above registers
grover = QuantumCircuit()
grover.add_register(f_in)
grover.add_register(f_out)
grover.add_register(aux)
grover.add_register(ans)
input_state(grover, f_in, f_out, n)
T = 2
for t in range(T):
# Apply T full iterations
black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula)
inversion_about_average(grover, f_in, n)
# Measure the output register in the computational basis
for j in range(n):
grover.measure(f_in[j], ans[j])
# Execute circuit
backend = BasicAer.get_backend('qasm_simulator')
job = execute([grover], backend=backend, shots=1000)
result = job.result()
# Get counts and plot histogram
counts = result.get_counts(grover)
plot_histogram(counts)
IBMQ.load_account()
# get ibmq_16_melbourne configuration and coupling map
backend = IBMQ.get_backend('ibmq_16_melbourne')
# compile the circuit for ibmq_16_rueschlikon
grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
grover.draw(output='mpl', scale=0.5)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.tools.visualization import plot_histogram, plot_state_city
# List Aer backends
Aer.backends()
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
# Construct quantum circuit
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Construct quantum circuit
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get memory
result = execute(circ, simulator, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Construct an empty quantum circuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.measure(qr, cr)
# Set the initial state
opts = {"initial_statevector": np.array([1, 0, 0, 1] / np.sqrt(2))}
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
counts = result.get_counts(circ)
plot_histogram(counts, title="Bell initial statevector")
# Construct quantum circuit without measure
qr = QuantumRegister(2, 'qr')
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit with measure
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state post-measurement')
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.iden(qr)
# Set the initial state
opts = {"initial_statevector": np.array([1, 0, 0, 1] / np.sqrt(2))}
# Select the StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title="Bell initial statevector")
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", unitary)
# Construct an empty quantum circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.iden(qr)
# Set the initial unitary
opts = {"initial_unitary": np.array([[ 1, 1, 0, 0],
[ 0, 0, 1, -1],
[ 0, 0, 1, 1],
[ 1, -1, 0, 0]] / np.sqrt(2))}
# Select the UnitarySimulator from the Aer provider
simulator = Aer.get_backend('unitary_simulator')
# Execute and get counts
result = execute(circ, simulator, backend_options=opts).result()
unitary = result.get_unitary(circ)
unitary = result.get_unitary(circ)
print("Initial Unitary:\n", unitary)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#量子エラー研究.平均誤差率
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend =FakeVigo()
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0,1,2],[0,1,2])
sim_ideal = AerSimulator()
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts =result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
#ibmq-vigo のsimulator
sim_vigo = AerSimulator.from_backend(device_backend)
tcirc = transpile(circ,sim_vigo)
result_noise =sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise, title="Counts for 3-qubit GHZ device noise model")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qsvm_datasets import *
from qiskit import Aer
from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
from qiskit_aqua.input import SVMInput
from qiskit_aqua import run_algorithm, QuantumInstance
from qiskit_aqua.algorithms import QSVMKernel
from qiskit_aqua.components.feature_maps import SecondOrderExpansion
# setup aqua logging
import logging
from qiskit_aqua import set_aqua_logging
# set_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
from qiskit import IBMQ
IBMQ.load_accounts()
feature_dim=2 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20,
test_size=10,
n=feature_dim,
gap=0.3,
PLOT_DATA=True)
extra_test_data = sample_ad_hoc_data(sample_Total, 10, n=feature_dim)
datapoints, class_to_label = split_dataset_to_data_and_labels(extra_test_data)
print(class_to_label)
seed = 10598
feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2, entanglement='linear')
qsvm = QSVMKernel(feature_map, training_input, test_input, datapoints[0])
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_mapper=seed)
result = qsvm.run(quantum_instance)
"""declarative approach
params = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM.Kernel'
},
'backend': {'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
algo_input = SVMInput(training_input, test_input, datapoints[0])
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: {}".format(result['testing_accuracy']))
print("preduction of datapoints:")
print("ground truth: {}".format(map_label_to_class_name(datapoints[1], qsvm.label_to_class)))
print("prediction: {}".format(result['predicted_classes']))
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20,
test_size=10,
n=2,
PLOT_DATA=True)
seed = 10598
feature_map = SecondOrderExpansion(num_qubits=feature_dim, depth=2, entanglement='linear')
qsvm = QSVMKernel(feature_map, training_input, test_input)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed=seed, seed_mapper=seed)
result = qsvm.run(quantum_instance)
"""declarative approach, re-use the params above
algo_input = SVMInput(training_input, test_input)
result = run_algorithm(params, algo_input)
"""
print("testing success ratio: ", result['testing_accuracy'])
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit_chemistry import QiskitChemistry
from qiskit import Aer
# from qiskit import IBMQ
# IBMQ.load_accounts()
# backend = IBMQ.get_backend('ibmq_16_melbourne')
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
# Input dictionary to configure Qiskit AQUA Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/0.7_sto-3g.hdf5'},
'operator': {'name': 'hamiltonian'},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'COBYLA'},
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'}
}
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
print('Ground state energy: {}'.format(result['energy']))
for line in result['printable']:
print(line)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import Aer
from qiskit_chemistry import QiskitChemistry
import warnings
warnings.filterwarnings('ignore')
# setup qiskit_chemistry logging
import logging
from qiskit_chemistry import set_qiskit_chemistry_logging
set_qiskit_chemistry_logging(logging.ERROR) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET
# from qiskit import IBMQ
# IBMQ.load_accounts()
# First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/H2_equilibrium_0.735_sto-3g.hdf5'},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
print('Ground state energy (classical): {:.12f}'.format(result['energy']))
# Second, we use variational quantum eigensolver (VQE)
qiskit_chemistry_dict['algorithm']['name'] = 'VQE'
qiskit_chemistry_dict['optimizer'] = {'name': 'SPSA', 'max_trials': 350}
qiskit_chemistry_dict['variational_form'] = {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
print('Ground state energy (quantum) : {:.12f}'.format(result['energy']))
print("====================================================")
# You can also print out other info in the field 'printable'
for line in result['printable']:
print(line)
# select H2 or LiH to experiment with
molecule='H2'
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': ''},
'optimizer': {'name': 'SPSA', 'max_trials': 350},
'variational_form': {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
}
# choose which backend want to use
# backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
backend_cfg = {'shots': 1024}
algos = ['ExactEigensolver', 'VQE']
if molecule == 'LiH':
mol_distances = np.arange(0.6, 5.1, 0.1)
qiskit_chemistry_dict['operator']['freeze_core'] = True
qiskit_chemistry_dict['operator']['orbital_reduction'] = [-3, -2]
qiskit_chemistry_dict['optimizer']['max_trials'] = 2500
qiskit_chemistry_dict['variational_form']['depth'] = 5
else:
mol_distances = np.arange(0.2, 4.1, 0.1)
energy = np.zeros((len(algos), len(mol_distances)))
for j, algo in enumerate(algos):
qiskit_chemistry_dict['algorithm']['name'] = algo
if algo == 'ExactEigensolver':
qiskit_chemistry_dict.pop('backend', None)
elif algo == 'VQE':
qiskit_chemistry_dict['backend'] = backend_cfg
print("Using {}".format(algo))
for i, dis in enumerate(mol_distances):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
qiskit_chemistry_dict['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(qiskit_chemistry_dict, backend=backend if algo == 'VQE' else None)
energy[j][i] = result['energy']
print("\n")
for i, algo in enumerate(algos):
plt.plot(mol_distances, energy[i], label=algo)
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import common packages
import numpy as np
from qiskit import Aer
# lib from Qiskit Aqua
from qiskit_aqua import Operator, QuantumInstance
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit_aqua.components.optimizers import COBYLA
# lib from Qiskit Aqua Chemistry
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.drivers import PySCFDriver, UnitsType
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
# using driver to get fermionic Hamiltonian
# PySCF example
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
# please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
map_type = 'parity'
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
# prepare full idx of freeze_list and remove_list
# convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
print(qubitOp.print_operators())
print(qubitOp)
# Using exact eigensolver to get the smallest eigenvalue
exact_eigensolver = ExactEigensolver(qubitOp, k=1)
ret = exact_eigensolver.run()
print('The computed energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total ground state energy is: {:.12f}'.format(ret['eigvals'][0].real + energy_shift + nuclear_repulsion_energy))
# from qiskit import IBMQ
# IBMQ.load_accounts()
backend = Aer.get_backend('statevector_simulator')
# setup COBYLA optimizer
max_eval = 200
cobyla = COBYLA(maxiter=max_eval)
# setup HartreeFock state
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type,
qubit_reduction)
# setup UCCSD variational form
var_form = UCCSD(qubitOp.num_qubits, depth=1,
num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=[0], active_unoccupied=[0, 1],
initial_state=HF_state, qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction, num_time_slices=1)
# setup VQE
vqe = VQE(qubitOp, var_form, cobyla, 'matrix')
quantum_instance = QuantumInstance(backend=backend)
results = vqe.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0]))
print('The total ground state energy is: {:.12f}'.format(results['eigvals'][0] + energy_shift + nuclear_repulsion_energy))
print("Parameters: {}".format(results['opt_params']))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import BasicAer
from qiskit_aqua.algorithms import AmplitudeEstimation
from qiskit_aqua.components.uncertainty_problems import EuropeanCallExpectedValue, EuropeanCallDelta
from qiskit_aqua.components.random_distributions import LogNormalDistribution
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 3
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev
# construct circuit factory for uncertainty model
uncertainty_model = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma, low=low, high=high)
# plot probability distribution
x = uncertainty_model.values
y = uncertainty_model.probabilities
plt.bar(x, y, width=0.2)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# construct circuit factory for payoff function
european_call = EuropeanCallExpectedValue(
uncertainty_model,
strike_price=strike_price,
c_approx=c_approx
)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = uncertainty_model.values
y = np.maximum(0, x - strike_price)
plt.plot(x, y, 'ro-')
plt.grid()
plt.title('Payoff Function', size=15)
plt.xlabel('Spot Price', size=15)
plt.ylabel('Payoff', size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(uncertainty_model.probabilities, y)
exact_delta = sum(uncertainty_model.probabilities[x >= strike_price])
print('exact (normalized) expected value:\t%.4f' % exact_value)
print('exact (normalized) delta value: \t%.4f' % exact_delta)
# set number of evaluation qubits (samples)
m = 5
# construct amplitude estimation
ae = AmplitudeEstimation(m, european_call)
# result = ae.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100)
result = ae.run(quantum_instance=BasicAer.get_backend('statevector_simulator'))
print('Exact value: \t%.4f' % exact_value)
print('Estimated value:\t%.4f' % result['estimation'])
print('Probability: \t%.4f' % result['max_probability'])
# plot estimated values for "a"
plt.bar(result['values'], result['probabilities'], width=0.5/len(result['probabilities']))
plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('"a" Value', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
# plot estimated values for option price (after re-scaling and reversing the c_approx-transformation)
plt.bar(result['mapped_values'], result['probabilities'], width=1/len(result['probabilities']))
plt.plot([exact_value, exact_value], [0,1], 'r--', linewidth=2)
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('Estimated Option Price', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
european_call_delta = EuropeanCallDelta(
uncertainty_model,
strike_price
)
# set number of evaluation qubits (=log(samples)
m = 5
# construct amplitude estimation
ae_delta = AmplitudeEstimation(m, european_call_delta)
# result_delta = ae_delta.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100)
result_delta = ae_delta.run(quantum_instance=BasicAer.get_backend('statevector_simulator'))
print('Exact delta: \t%.4f' % exact_delta)
print('Esimated value:\t%.4f' % result_delta['estimation'])
print('Probability: \t%.4f' % result_delta['max_probability'])
# plot estimated values for delta
plt.bar(result_delta['values'], result_delta['probabilities'], width=0.5/len(result_delta['probabilities']))
plt.plot([exact_delta, exact_delta], [0,1], 'r--', linewidth=2)
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('Estimated Option Delta', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import BasicAer
from qiskit_aqua.algorithms import AmplitudeEstimation
from qiskit_aqua.components.random_distributions import MultivariateNormalDistribution
from qiskit_aqua.components.uncertainty_problems import FixedIncomeExpectedValue
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01*np.eye(2)
# construct corresponding distribution
u = MultivariateNormalDistribution(num_qubits, low, high, mu, sigma)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2**num_qubits[0])
y = np.linspace(low[1], high[1], 2**num_qubits[1])
z = u.probabilities.reshape(2**num_qubits[0], 2**num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel('$r_1$ (%)', size=15)
plt.ylabel('$r_2$ (%)', size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf)+1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel('periods', size=15)
plt.ylabel('cashflow ($)', size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (cf[t]/pow(1 + b[t], t+1) - (t+1)*cf[t]*np.dot(A[:, t], np.asarray([x1, x2]))/pow(1 + b[t], t+2))
cnt += 1
print('Exact value: \t%.4f' % exact_value)
# specify approximation factor
c_approx = 0.125
# get fixed income circuit appfactory
fixed_income = FixedIncomeExpectedValue(u, A, b, cf, c_approx)
# set number of evaluation qubits (samples)
m = 5
# construct amplitude estimation
ae = AmplitudeEstimation(m, fixed_income)
# result = ae.run(quantum_instance=BasicAer.get_backend('qasm_simulator'), shots=100)
result = ae.run(quantum_instance=BasicAer.get_backend('statevector_simulator'))
print('Exact value: \t%.4f' % exact_value)
print('Estimated value:\t%.4f' % result['estimation'])
print('Probability: \t%.4f' % result['max_probability'])
# plot estimated values for "a" (direct result of amplitude estimation, not rescaled yet)
plt.bar(result['values'], result['probabilities'], width=0.5/len(result['probabilities']))
plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('"a" Value', size=15)
plt.ylabel('Probability', size=15)
plt.xlim((0,1))
plt.ylim((0,1))
plt.grid()
plt.show()
# plot estimated values for fixed-income asset (after re-scaling and reversing the c_approx-transformation)
plt.bar(result['mapped_values'], result['probabilities'], width=3/len(result['probabilities']))
plt.plot([exact_value, exact_value], [0,1], 'r--', linewidth=2)
plt.xticks(size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('Estimated Option Price', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import BasicAer
from qiskit_aqua import QuantumInstance
from qiskit_aqua import Operator, run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import portfolio
from qiskit_aqua.algorithms import VQE, QAOA, ExactEigensolver
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua.components.variational_forms import RY
import numpy as np
from qiskit import IBMQ
IBMQ.load_accounts()
# set number of assets (= number of qubits)
num_assets = 4
# get random expected return vector (mu) and covariance matrix (sigma)
mu, sigma = portfolio.random_model(num_assets, seed=42)
q = 0.5 # set risk factor
budget = int(num_assets / 2) # set budget
penalty = num_assets # set parameter to scale the budget penalty term
qubitOp, offset = portfolio.get_portfolio_qubitops(mu, sigma, q, budget, penalty)
algo_input = EnergyInput(qubitOp)
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def print_result(result):
selection = portfolio.sample_most_likely(result['eigvecs'][0])
value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty)
print('Optimal: selection {}, value {:.4f}'.format(selection, value))
probabilities = np.abs(result['eigvecs'][0])**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = portfolio.portfolio_value(x, mu, sigma, q, budget, penalty)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
exact_eigensolver = ExactEigensolver(qubitOp, k=1)
result = exact_eigensolver.run()
""" the equivalent if using declarative approach
algorithm_cfg = {
'name': 'ExactEigensolver'
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params, algo_input)
"""
print_result(result)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = RY(qubitOp.num_qubits, depth=3, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla, 'matrix')
vqe.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""declarative approach
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA',
'maxiter': 250
}
var_form_cfg = {
'name': 'RY',
'depth': 3,
'entanglement': 'full'
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg
}
result = run_algorithm(params, algo_input, backend=backend)
"""
print_result(result)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa = QAOA(qubitOp, cobyla, 3, 'matrix')
qaoa.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = qaoa.run(quantum_instance)
"""declarative approach
algorithm_cfg = {
'name': 'QAOA.Variational',
'p': 3,
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA',
'maxiter': 250
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg
}
result = run_algorithm(params, algo_input, backend=backend)
"""
print_result(result)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit_aqua import register_pluggable
from evolutionfidelity.evolutionfidelity import EvolutionFidelity
try:
register_pluggable(EvolutionFidelity)
except Exception as e:
print(e)
from qiskit import Aer
import numpy as np
from qiskit_aqua.operator import Operator
from evolutionfidelity.evolutionfidelity import EvolutionFidelity
from qiskit_aqua.components.initial_states import Zero
from qiskit_aqua import QuantumInstance
num_qubits = 2
temp = np.random.random((2 ** num_qubits, 2 ** num_qubits))
qubit_op = Operator(matrix=temp + temp.T)
initial_state = Zero(qubit_op.num_qubits)
algo = EvolutionFidelity(qubit_op, initial_state, expansion_order=1)
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend)
result = algo.run(quantum_instance)
print(result['score'])
from qiskit_aqua.input import EnergyInput
from qiskit_aqua import run_algorithm
params = {
'problem': {
'name': 'eoh'
},
'algorithm': {
'name': 'EvolutionFidelity',
'expansion_order': 1
},
'initial_state': {
'name': 'ZERO'
}
}
algo_input = EnergyInput(qubit_op)
result = run_algorithm(params, algo_input, backend=backend)
print(result['score'])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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.
# =============================================================================
"""
The Fidelity of Quantum Evolution.
This is a simple tutorial example to show how to build an algorithm to extend
Qiskit Aqua library. Algorithms are designed to be dynamically discovered within
Qiskit Aqua. For this the entire parent directory 'evolutionfidelity' should
be moved under the 'qiskit_aqua' directory. The current demonstration notebook
shows how to explicitly register the algorithm and works without re-locating this
code. The former automatic discovery does however allow the algorithm to be found
and seen in the UI browser, and selected from the GUI when choosing an algorithm.
"""
import logging
import numpy as np
from qiskit import QuantumRegister
from qiskit.quantum_info import state_fidelity
from qiskit_aqua.algorithms import QuantumAlgorithm
from qiskit_aqua import AquaError, PluggableType, get_pluggable_class
logger = logging.getLogger(__name__)
class EvolutionFidelity(QuantumAlgorithm):
"""The Tutorial Sample EvolutionFidelity algorithm."""
PROP_EXPANSION_ORDER = 'expansion_order'
"""
A configuration dictionary defines the algorithm to QISKIt Aqua. It can contain
the following though this sample does not have them all.
name: Is the registered name and will be used as the case-sensitive key to load an instance
description: As it implies a brief description of algorithm
classical: True if purely a classical algorithm that does not need a quantum backend
input_schema: A json schema detailing the configuration variables of this entity.
Each variable as a type, and can be given default, minimum etc. This conforms
to JSON Schema which can be consulted for for detail. The existing algorithms
and other pluggable entities may also be helpful to refer to.
problems: A list of problems the algorithm can solve
depends: A list of dependent object types
defaults: A list of configurations for the dependent objects. May just list names if the
dependent's defaults are acceptable
"""
CONFIGURATION = {
'name': 'EvolutionFidelity',
'description': 'Sample Demo EvolutionFidelity Algorithm for Quantum Systems',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'evolution_fidelity_schema',
'type': 'object',
'properties': {
PROP_EXPANSION_ORDER: {
'type': 'integer',
'default': 1,
'minimum': 1
},
},
'additionalProperties': False
},
'problems': ['eoh'],
'depends': ['initial_state'],
'defaults': {
'initial_state': {
'name': 'ZERO'
}
}
}
"""
If directly use these objects programmatically then the constructor is more convenient to call
than init_params. init_params itself uses this to do the actual object initialization.
"""
def __init__(self, operator, initial_state, expansion_order=1):
self.validate(locals())
super().__init__()
self._operator = operator
self._initial_state = initial_state
self._expansion_order = expansion_order
self._ret = {}
"""
init_params is called via run_algorithm. The params contain all the configuration settings
of the objects. algo_input contains data computed from above for the algorithm. A simple
algorithm may have all its data in configuration params such that algo_input is None
"""
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params: parameters dictionary
algo_input: EnergyInput instance
"""
if algo_input is None:
raise AquaError("EnergyInput instance is required.")
operator = algo_input.qubit_op
evolution_fidelity_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM)
expansion_order = evolution_fidelity_params.get(EvolutionFidelity.PROP_EXPANSION_ORDER)
# Set up initial state, we need to add computed num qubits to params
initial_state_params = params.get(QuantumAlgorithm.SECTION_KEY_INITIAL_STATE)
initial_state_params['num_qubits'] = operator.num_qubits
initial_state = get_pluggable_class(PluggableType.INITIAL_STATE,
initial_state_params['name']).init_params(initial_state_params)
return cls(operator, initial_state, expansion_order)
"""
Once the algorithm has been initialized then run is called to carry out the computation
and the result is returned as a dictionary.
E.g., the `_run` method is required to be implemented for an algorithm.
"""
def _run(self):
evo_time = 1
# get the groundtruth via simple matrix * vector
state_out_exact = self._operator.evolve(self._initial_state.construct_circuit('vector'), evo_time, 'matrix', 0)
qr = QuantumRegister(self._operator.num_qubits, name='q')
circuit = self._initial_state.construct_circuit('circuit', qr)
circuit += self._operator.evolve(
None, evo_time, 'circuit', 1,
quantum_registers=qr,
expansion_mode='suzuki',
expansion_order=self._expansion_order
)
result = self._quantum_instance.execute(circuit)
state_out_dynamics = np.asarray(result.get_statevector(circuit))
self._ret['score'] = state_fidelity(state_out_exact, state_out_dynamics)
return self._ret
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import Operator, run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import maxcut, tsp
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit_aqua.components.optimizers import SPSA
from qiskit_aqua.components.variational_forms import RY
from qiskit_aqua import QuantumInstance
# setup aqua logging
import logging
from qiskit_aqua import set_aqua_logging
# set_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
from qiskit import IBMQ
IBMQ.load_accounts()
# Generating a graph of 4 nodes
n=4 # Number of nodes in graph
G=nx.Graph()
G.add_nodes_from(np.arange(0,n,1))
elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
# Computing the weight matrix from the random graph
w = np.zeros([n,n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i,j,default=0)
if temp != 0:
w[i,j] = temp['weight']
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i,j]*x[i]*(1-x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print('case = ' + str(x)+ ' cost = ' + str(cost))
colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute))
qubitOp, offset = maxcut.get_maxcut_qubitops(w)
algo_input = EnergyInput(qubitOp)
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
"""
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
"""
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, 'matrix')
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""declarative apporach
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'SPSA',
'max_trials': 300
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'statevector_simulator'}
}
result = run_algorithm(params, algo_input)
"""
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
# run quantum algorithm with shots
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""declarative approach, update the param from the previous cell.
params['algorithm']['operator_mode'] = 'grouped_paulis'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params, algo_input)
"""
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
plot_histogram(result['eigvecs'][0])
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n ** 2
ins = tsp.random_tsp(n)
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
colors = ['r' for node in G.nodes()]
pos = {k: v for k, v in enumerate(ins.coord)}
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
print('distance\n', ins.w)
from itertools import permutations
def brute_force_tsp(w, N):
a=list(permutations(range(1,N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j,pre_j]
pre_j = j
distance = distance + w[pre_j,0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print('order = ' + str(order) + ' Distance = ' + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(ins.w, ins.dim)
print('Best order from brute force = ' + str(best_order) + ' with total distance = ' + str(best_distance))
def draw_tsp_solution(G, order, colors, pos):
G2 = G.copy()
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G2, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
draw_tsp_solution(G, best_order, colors, pos)
qubitOp, offset = tsp.get_tsp_qubitops(ins)
algo_input = EnergyInput(qubitOp)
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
"""
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
"""
print('energy:', result['energy'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
draw_tsp_solution(G, z, colors, pos)
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, 'matrix')
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'SPSA',
'max_trials': 300
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': seed},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'statevector_simulator'}
}
result = run_algorithm(parahms,algo_input)
"""
print('energy:', result['energy'])
print('time:', result['eval_time'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
draw_tsp_solution(G, z, colors, pos)
# run quantum algorithm with shots
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis', batch_mode=True)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed, seed_mapper=seed)
result = vqe.run(quantum_instance)
"""update params in the previous cell
params['algorithm']['operator_mode'] = 'grouped_paulis'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params,algo_input)
"""
print('energy:', result['energy'])
print('time:', result['eval_time'])
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
plot_histogram(result['eigvecs'][0])
draw_tsp_solution(G, z, colors, pos)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(3, 'q')
# Create a Quantum Circuit acting on the q register
circ = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[2])
circ.draw()
# Import Aer
from qiskit import BasicAer
# Run the quantum circuit on a statevector simulator backend
backend = BasicAer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.tools.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = BasicAer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Classical Register with 3 bits.
c = ClassicalRegister(3, 'c')
# Create a Quantum Circuit
meas = QuantumCircuit(q, c)
meas.barrier(q)
# map the quantum measurement to the classical bits
meas.measure(q,c)
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
IBMQ.load_accounts()
print("Available backends:")
IBMQ.backends()
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits > 4 and
not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())
from qiskit.tools.monitor import job_monitor
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts])
backend = IBMQ.get_backend('ibmq_qasm_simulator', hub=None)
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_hpc = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
result_hpc = job_hpc.result()
counts_hpc = result_hpc.get_counts(qc)
plot_histogram(counts_hpc)
jobID = job_exp.job_id()
print('JOB ID: {}'.format(jobID))
job_get=backend.retrieve_job(jobID)
job_get.result().get_counts(qc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit.tools.visualization import plot_histogram
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
q = QuantumRegister(2)
c = ClassicalRegister(2)
# quantum circuit to make a Bell state
bell = QuantumCircuit(q,c)
bell.h(q[0])
bell.cx(q[0],q[1])
meas = QuantumCircuit(q,c)
meas.measure(q, c)
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell+meas
result = execute(circ, backend, shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
# Execute 2 qubit Bell state again
second_result = execute(circ, backend, shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False)
from qiskit.tools.visualization import iplot_histogram
# Run in interactive mode
iplot_histogram(counts)
from qiskit.tools.visualization import plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = execute(bell, backend).result()
psi = result.get_statevector(bell)
plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
plot_state_city(psi, title="My City", color=['black', 'orange'])
plot_state_hinton(psi, title="My Hinton")
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
plot_bloch_multivector(psi, title="My Bloch Spheres")
from qiskit.tools.visualization import iplot_state_paulivec
# Generate an interactive pauli vector plot
iplot_state_paulivec(psi)
from qiskit.tools.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0])
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import IBMQ
IBMQ.backends()
IBMQ.delete_accounts()
IBMQ.stored_accounts()
import Qconfig_IBMQ_experience
import Qconfig_IBMQ_network
IBMQ.enable_account(Qconfig_IBMQ_experience.APItoken)
# uncomment to print to screen (it will show your token and url)
# IBMQ.active_accounts()
IBMQ.backends()
IBMQ.disable_accounts(token=Qconfig_IBMQ_experience.APItoken)
IBMQ.backends()
IBMQ.save_account(Qconfig_IBMQ_experience.APItoken, overwrite=True)
IBMQ.save_account(Qconfig_IBMQ_network.APItoken, Qconfig_IBMQ_network.url, overwrite=True)
# uncomment to print to screen (it will show your token and url)
# IBMQ.stored_accounts()
IBMQ.active_accounts()
IBMQ.backends()
IBMQ.load_accounts()
IBMQ.backends()
IBMQ.backends(hub='ibm-q-internal')
IBMQ.disable_accounts(hub='ibm-q-internal')
# uncomment to print to screen (it will show your token and url)
# IBMQ.active_accounts()
IBMQ.backends()
IBMQ.disable_accounts()
IBMQ.load_accounts(hub=None)
IBMQ.backends()
IBMQ.backends(operational=True, simulator=False)
IBMQ.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True)
from qiskit.providers.ibmq import least_busy
small_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits == 5 and
not x.configuration().simulator)
least_busy(small_devices)
IBMQ.get_backend('ibmq_16_melbourne')
backend = least_busy(small_devices)
backend.provider
backend.name()
backend.status()
backend.configuration()
backend.properties()
backend.hub
backend.group
backend.project
for ran_job in backend.jobs(limit=5):
print(str(ran_job.job_id()) + " " + str(ran_job.status()))
job = backend.retrieve_job(ran_job.job_id())
job.status()
backend_temp = job.backend()
backend_temp
job.job_id()
result = job.result()
counts = result.get_counts()
print(counts)
job.creation_date()
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import compile
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.x(qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
qobj = compile(circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status()
import time
#time.sleep(10)
job.cancel()
job.status()
job = backend.run(qobj)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
counts = result.get_counts()
print(counts)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
from qiskit.providers.aer.noise.errors.standard_errors import coherent_unitary_error
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.characterization.hamiltonian import ZZFitter, zz_circuits
from qiskit.ignis.characterization.gates import (AmpCalFitter, ampcal_1Q_circuits,
AngleCalFitter, anglecal_1Q_circuits,
AmpCalCXFitter, ampcal_cx_circuits,
AngleCalCXFitter, anglecal_cx_circuits)
# ZZ rates are typically ~ 100kHz so we want Ramsey oscillations around 1MHz
# 12 numbers ranging from 10 to 1000, logarithmically spaced
# extra point at 1500
num_of_gates = np.arange(0,150,5)
gate_time = 0.1
# Select the qubits whose ZZ will be measured
qubits = [0]
spectators = [1]
# Generate experiments
circs, xdata, osc_freq = zz_circuits(num_of_gates, gate_time, qubits, spectators, nosc=2)
# Set the simulator with ZZ
zz_unitary = np.eye(4,dtype=complex)
zz_unitary[3,3] = np.exp(1j*2*np.pi*0.02*gate_time)
error = coherent_unitary_error(zz_unitary)
noise_model = NoiseModel()
noise_model.add_nonlocal_quantum_error(error, 'id', [0], [0,1])
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 500
# For demonstration purposes split the execution into two jobs
print("Running the first 20 circuits")
backend_result1 = qiskit.execute(circs[0:20], backend,
shots=shots, noise_model=noise_model).result()
print("Running the rest of the circuits")
backend_result2 = qiskit.execute(circs[20:], backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an oscillation
plt.figure(figsize=(10, 6))
initial_a = 1
initial_c = 0
initial_f = osc_freq
initial_phi = -np.pi/20
# Instantiate the fitter
# pass the 2 results in as a list of results
fit = ZZFitter([backend_result1, backend_result2], xdata, qubits, spectators,
fit_p0=[initial_a, initial_f, initial_phi, initial_c],
fit_bounds=([-0.5, 0, -np.pi, -0.5],
[1.5, 2*osc_freq, np.pi, 1.5]))
fit.plot_ZZ(0, ax=plt.gca())
print("ZZ Rate: %f kHz"%(fit.ZZ_rate()[0]*1e3))
plt.show()
qubits = [4,2]
circs, xdata = ampcal_1Q_circuits(10, qubits)
print(circs[2])
# Set the simulator
# Add a rotation error
err_unitary = np.zeros([2,2],dtype=complex)
angle_err = 0.1
for i in range(2):
err_unitary[i,i] = np.cos(angle_err)
err_unitary[i,(i+1) % 2] = np.sin(angle_err)
err_unitary[0,1] *= -1.0
error = coherent_unitary_error(err_unitary)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'u2')
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 500
backend_result1 = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an oscillation
plt.figure(figsize=(10, 6))
initial_theta = 0.02
initial_c = 0.5
initial_phi = 0.1
fit = AmpCalFitter(backend_result1, xdata, qubits,
fit_p0=[initial_theta, initial_c],
fit_bounds=([-np.pi, -1],
[np.pi, 1]))
# plot the result for the number 1 indexed qubit.
# In this case that refers to Q2 since we passed in as [4, 2])
fit.plot(1, ax=plt.gca())
print("Rotation Error on U2: %f rads"%(fit.angle_err()[0]))
plt.show()
qubits = [0,1]
circs, xdata = anglecal_1Q_circuits(10, qubits, angleerr=0.1)
#The U1 gates are added errors to test the procedure
print(circs[2])
# Set the simulator
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 1000
backend_result1 = qiskit.execute(circs, backend,
shots=shots).result()
%matplotlib inline
# Fit the data to an oscillation
plt.figure(figsize=(10, 6))
initial_theta = 0.02
initial_c = 0.5
initial_phi = 0.01
fit = AngleCalFitter(backend_result1, xdata, qubits,
fit_p0=[initial_theta, initial_c],
fit_bounds=([-np.pi, -1],
[np.pi, 1]))
fit.plot(0, ax=plt.gca())
print("Angle error between X and Y: %f rads"%(fit.angle_err()[0]))
plt.show()
# We can specify more than one CX gate to calibrate in parallel
# but these lists must be the same length and not contain
# any duplicate elements
qubits = [0,2]
controls = [1,3]
circs, xdata = ampcal_cx_circuits(15, qubits, controls)
print(circs[2])
# Set the simulator
# Add a rotation error on CX
# only if the control is in the excited state
err_unitary = np.eye(4,dtype=complex)
angle_err = 0.15
for i in range(2):
err_unitary[2+i,2+i] = np.cos(angle_err)
err_unitary[2+i,2+(i+1) % 2] = -1j*np.sin(angle_err)
error = coherent_unitary_error(err_unitary)
noise_model = NoiseModel()
noise_model.add_nonlocal_quantum_error(error, 'cx', [1,0], [0,1])
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 1500
backend_result1 = qiskit.execute(circs, backend,
shots=shots, noise_model=noise_model).result()
%matplotlib inline
# Fit the data to an oscillation
plt.figure(figsize=(10, 6))
initial_theta = 0.02
initial_c = 0.5
initial_phi = 0.01
fit = AmpCalCXFitter(backend_result1, xdata, qubits,
fit_p0=[initial_theta, initial_c],
fit_bounds=([-np.pi, -1],
[np.pi, 1]))
fit.plot(0, ax=plt.gca())
print("Rotation Error on CX: %f rads"%(fit.angle_err()[0]))
plt.show()
qubits = [0,2]
controls = [1,3]
circs, xdata = anglecal_cx_circuits(15, qubits, controls, angleerr=0.1)
print(circs[2])
# Set the simulator
# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 1000
backend_result1 = qiskit.execute(circs, backend,
shots=shots).result()
%matplotlib inline
# Fit the data to an oscillation
plt.figure(figsize=(10, 6))
initial_theta = 0.02
initial_c = 0.5
initial_phi = 0.01
fit = AngleCalCXFitter(backend_result1, xdata, qubits,
fit_p0=[initial_theta, initial_c],
fit_bounds=([-np.pi, -1],
[np.pi, 1]))
fit.plot(0, ax=plt.gca())
print("Rotation Error on CX: %f rads"%(fit.angle_err()[0]))
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
CompleteMeasFitter, MeasurementFilter)
# Generate the calibration circuits
qr = qiskit.QuantumRegister(5)
meas_calibs, state_labels = complete_meas_cal(qubit_list=[2,3,4], qr=qr, circlabel='mcal')
state_labels
# Execute the calibration circuits without noise
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
# The calibration matrix without noise is the identity matrix
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Generate a noise model for the 5 qubits
noise_model = noise.NoiseModel()
for qi in range(5):
read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]])
noise_model.add_readout_error(read_err, [qi])
# Execute the calibration circuits
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
# Calculate the calibration matrix with the noise model
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Plot the calibration matrix
meas_fitter.plot_calibration()
# What is the measurement fidelity?
print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity())
# What is the measurement fidelity of Q0?
print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity(
label_list = [['000','001','010','011'],['100','101','110','111']]))
# Make a 3Q GHZ state
cr = ClassicalRegister(3)
ghz = QuantumCircuit(qr, cr)
ghz.h(qr[2])
ghz.cx(qr[2], qr[3])
ghz.cx(qr[3], qr[4])
ghz.measure(qr[2],cr[0])
ghz.measure(qr[3],cr[1])
ghz.measure(qr[4],cr[2])
job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model)
results = job.result()
# Results without mitigation
raw_counts = results.get_counts()
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Needed for functions
import numpy as np
import time
# Import QISKit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, Aer
from qiskit.quantum_info import state_fidelity
from qiskit.tools.qi.qi import outer
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
# Process tomography of a Hadamard gate
q = QuantumRegister(1)
circ = QuantumCircuit(q)
circ.h(q[0])
# Run circuit on unitary simulator to find ideal unitary
job = qiskit.execute(circ, Aer.get_backend('unitary_simulator'))
ideal_unitary = job.result().get_unitary(circ)
# convert to Choi-matrix in column-major convention
choi_ideal = outer(ideal_unitary.ravel(order='F'))
# Generate process tomography circuits and run on qasm simulator
qpt_circs = process_tomography_circuits(circ, q)
job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=4000)
# Extract tomography data so that counts are indexed by measurement configuration
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs)
qpt_tomo.data
# MLE Least-Squares tomographic reconstruction
t = time.time()
choi_lstsq = qpt_tomo.fit(method='lstsq')
print('Least-Sq Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2))
# CVXOPT Semidefinite-Program tomographic reconstruction
t = time.time()
choi_cvx = qpt_tomo.fit(method='cvx')
print('\nCVXOPT Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2))
# Process tomography of a Hadamard gate
q = QuantumRegister(2)
circ = QuantumCircuit(q)
circ.swap(q[0], q[1])
# Ideal channel is a unitary
ideal_unitary = np.eye(2)
choi_ideal = outer(ideal_unitary.ravel(order='F'))
# Generate process tomography circuits and run on qasm simulator
# We use the optional prepared_qubits kwarg to specify that the prepared qubit was different to measured qubit
qpt_circs = process_tomography_circuits(circ, q[1], prepared_qubits=q[0])
job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000)
# Extract tomography data so that counts are indexed by measurement configuration
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs)
qpt_tomo.data
# Least-Squares tomographic reconstruction
t = time.time()
choi_lstsq = qpt_tomo.fit(method='lstsq')
print('Least-Sq Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2))
# CVXOPT Semidefinite-Program tomographic reconstruction
t = time.time()
choi_cvx = qpt_tomo.fit(method='cvx')
print('\nCVXOPT Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2))
# Bell-state entangling circuit
q = QuantumRegister(2)
circ = QuantumCircuit(q)
circ.h(q[0])
circ.cx(q[0], q[1])
# Run circuit on unitary simulator to find ideal unitary
job = qiskit.execute(circ, Aer.get_backend('unitary_simulator'))
ideal_unitary = job.result().get_unitary(circ)
# convert to Choi-matrix in column-major convention
choi_ideal = outer(ideal_unitary.ravel(order='F'))
# Generate process tomography circuits and run on qasm simulator
qpt_circs = process_tomography_circuits(circ, q)
job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000)
# Extract tomography data so that counts are indexed by measurement configuration
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs)
t = time.time()
choi_lstsq = qpt_tomo.fit(method='lstsq')
print('Least-Sq Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 4, choi_lstsq / 4))
t = time.time()
choi_cvx = qpt_tomo.fit(method='cvx')
print('\nCVXOPT Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 4, choi_cvx / 4))
# Process tomography of a Hadamard gate
q = QuantumRegister(1)
circ = QuantumCircuit(q)
circ.h(q[0])
# Run circuit on unitary simulator to find ideal unitary
job = qiskit.execute(circ, Aer.get_backend('unitary_simulator'))
ideal_unitary = job.result().get_unitary(circ)
# convert to Choi-matrix in column-major convention
choi_ideal = outer(ideal_unitary.ravel(order='F'))
# Generate process tomography circuits and run on qasm simulator
qpt_circs = process_tomography_circuits(circ, q, prep_labels='SIC', prep_basis='SIC')
job = qiskit.execute(qpt_circs, Aer.get_backend('qasm_simulator'), shots=2000)
# Extract tomography data so that counts are indexed by measurement configuration
qpt_tomo = ProcessTomographyFitter(job.result(), qpt_circs, prep_basis='SIC')
qpt_tomo.data
# MLE Least-Squares tomographic reconstruction
t = time.time()
choi_lstsq = qpt_tomo.fit(method='lstsq')
print('Least-Sq Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_lstsq / 2))
# CVXOPT Semidefinite-Program tomographic reconstruction
t = time.time()
choi_cvx = qpt_tomo.fit(method='cvx')
print('\nCVXOPT Fitter')
print('fit time:', time.time() - t)
print('fit fidelity:', state_fidelity(choi_ideal / 2, choi_cvx / 2))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Import general libraries (needed for functions)
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
#Import Qiskit classes classes
import qiskit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
#Import the RB Functions
import qiskit.ignis.verification.randomized_benchmarking as rb
#Number of qubits
nQ = 3
#There are 3 qubits: Q0,Q1,Q2.
#Number of seeds (random sequences)
nseeds = 5
#Number of Cliffords in the sequence (start, stop, steps)
nCliffs = np.arange(1,200,20)
#2Q RB on Q0,Q2 and 1Q RB on Q1
rb_pattern = [[0,2],[1]]
#Do three times as many 1Q Cliffords
length_multiplier = [1,3]
rb_opts = {}
rb_opts['length_vector'] = nCliffs
rb_opts['nseeds'] = nseeds
rb_opts['rb_pattern'] = rb_pattern
rb_opts['length_multiplier'] = length_multiplier
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
print(rb_circs[0][0])
#Create a new circuit without the measurement
qc = qiskit.QuantumCircuit(*rb_circs[0][-1].qregs,*rb_circs[0][-1].cregs)
for i in rb_circs[0][-1][0:-nQ]:
qc._attach(i)
#The Unitary is an identity (with a global phase)
backend = qiskit.Aer.get_backend('unitary_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
basis_gates_str = ','.join(basis_gates)
job = qiskit.execute(qc, backend=backend, basis_gates=basis_gates_str)
print(np.around(job.result().get_unitary(),3))
noise_model = NoiseModel()
p1Q = 0.002
p2Q = 0.01
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2')
noise_model.add_all_qubit_quantum_error(depolarizing_error(2*p1Q, 1), 'u3')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx')
#noise_model = None
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
basis_gates_str = ','.join(basis_gates)
shots = 200
result_list = []
qobj_list = []
import time
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots)
print('Simulating seed %d'%rb_seed)
job = backend.run(qobj, noise_model=noise_model, backend_options={'max_parallel_experiments': 0})
result_list.append(job.result())
qobj_list.append(qobj)
print("Finished Simulating")
#Create an RBFitter object with 1 seed of data
rbfit = rb.fitters.RBFitter(result_list[0], xdata, rb_opts['rb_pattern'])
plt.figure(figsize=(15, 6))
for i in range(2):
ax = plt.subplot(1, 2, i+1)
pattern_ind = i
# Plot the essence by calling plot_rb_data
rbfit.plot_rb_data(pattern_ind, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(len(rb_opts['rb_pattern'][i])), fontsize=18)
plt.show()
rbfit = rb.fitters.RBFitter(result_list[0], xdata, rb_opts['rb_pattern'])
for seed_num, data in enumerate(result_list):#range(1,len(result_list)):
plt.figure(figsize=(15, 6))
axis = [plt.subplot(1, 2, 1), plt.subplot(1, 2, 2)]
# Add another seed to the data
rbfit.add_data([data])
for i in range(2):
pattern_ind = i
# Plot the essence by calling plot_rb_data
rbfit.plot_rb_data(pattern_ind, ax=axis[i], add_label=True, show_plt=False)
# Add title and label
axis[i].set_title('%d Qubit RB - after seed %d'%(len(rb_opts['rb_pattern'][i]), seed_num), fontsize=18)
# Display
display.display(plt.gcf())
# Clear display after each seed and close
display.clear_output(wait=True)
time.sleep(1.0)
plt.close()
shots = 200
result_list = []
qobj_list = []
for rb_seed,rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots)
print('Simulating seed %d'%rb_seed)
job = backend.run(qobj, noise_model=noise_model, backend_options={'max_parallel_experiments': 0})
result_list.append(job.result())
qobj_list.append(qobj)
print("Finished Simulating")
#Add this data to the previous fit
rbfit.add_data(result_list)
#Replot
plt.figure(figsize=(15, 6))
for i in range(2):
ax = plt.subplot(1, 2, i+1)
pattern_ind = i
# Plot the essence by calling plot_rb_data
rbfit.plot_rb_data(pattern_ind, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(len(rb_opts['rb_pattern'][i])), fontsize=18)
plt.show()
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list,xdata[0],basis_gates,rb_opts['rb_pattern'][0])
for i in range(len(basis_gates)):
print("Number of %s gates per Clifford: %f"%(basis_gates[i],
np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]])))
#Prepare lists of the number of qubits and the errors
ngates = np.zeros(7)
ngates[0:3] = gates_per_cliff[0][0:3]
ngates[3:6] = gates_per_cliff[1][0:3]
ngates[6] = gates_per_cliff[0][3]
gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int)
gate_errs = np.zeros(len(gate_qubits))
gate_errs[[1,4]] = p1Q/2 #convert from depolarizing error to epg (1Q)
gate_errs[[2,5]] = 2*p1Q/2 #convert from depolarizing error to epg (1Q)
gate_errs[6] = p2Q*3/4 #convert from depolarizing error to epg (2Q)
#Calculate the predicted epc
pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs)
print("Predicted 2Q Error per Clifford: %e"%pred_epc)
rb_opts2 = rb_opts.copy()
rb_opts2['rb_pattern'] = [[0,1]]
rb_opts2['length_multiplier'] = 1
rb_circs2, xdata2 = rb.randomized_benchmarking_seq(**rb_opts2)
noise_model2 = NoiseModel()
#Add T1/T2 noise to the simulation
t1 = 100.
t2 = 80.
gate1Q = 0.1
gate2Q = 0.5
noise_model2.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,gate1Q), 'u2')
noise_model2.add_all_qubit_quantum_error(thermal_relaxation_error(t1,t2,2*gate1Q), 'u3')
noise_model2.add_all_qubit_quantum_error(
thermal_relaxation_error(t1,t2,gate2Q).kron(thermal_relaxation_error(t1,t2,gate2Q)), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx'] # use U,CX for now
basis_gates_str = ','.join(basis_gates)
shots = 500
result_list2 = []
qobj_list2 = []
for rb_seed,rb_circ_seed in enumerate(rb_circs2):
print('Compiling seed %d'%rb_seed)
qobj = qiskit.compile(rb_circ_seed, backend=backend, basis_gates=basis_gates_str, shots=shots)
print('Simulating seed %d'%rb_seed)
job = backend.run(qobj, noise_model=noise_model2, backend_options={'max_parallel_experiments': 0})
result_list2.append(job.result())
qobj_list2.append(qobj)
print("Finished Simulating")
#Create an RBFitter object
rbfit = rb.RBFitter(result_list2, xdata2, rb_opts2['rb_pattern'])
plt.figure(figsize=(10, 6))
ax = plt.gca()
# Plot the essence by calling plot_rb_data
rbfit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('2 Qubit RB with T1/T2 noise', fontsize=18)
plt.show()
#Count the number of single and 2Q gates in the 2Q Cliffords
gates_per_cliff = rb.rb_utils.gates_per_clifford(qobj_list2,xdata2[0],basis_gates,rb_opts2['rb_pattern'][0])
for i in range(len(basis_gates)):
print("Number of %s gates per Clifford: %f"%(basis_gates[i],
np.mean([gates_per_cliff[0][i],gates_per_cliff[0][i]])))
#Prepare lists of the number of qubits and the errors
ngates = np.zeros(7)
ngates[0:3] = gates_per_cliff[0][0:3]
ngates[3:6] = gates_per_cliff[1][0:3]
ngates[6] = gates_per_cliff[0][3]
gate_qubits = np.array([0,0,0,1,1,1,-1], dtype=int)
gate_errs = np.zeros(len(gate_qubits))
#Here are the predicted primitive gate errors from the coherence limit
gate_errs[[1,4]] = rb.rb_utils.coherence_limit(1,[t1],[t2],gate1Q)
gate_errs[[2,5]] = rb.rb_utils.coherence_limit(1,[t1],[t2],2*gate1Q)
gate_errs[6] = rb.rb_utils.coherence_limit(2,[t1,t1],[t2,t2],gate2Q)
#Calculate the predicted epc
pred_epc = rb.rb_utils.twoQ_clifford_error(ngates,gate_qubits,gate_errs)
print("Predicted 2Q Error per Clifford: %e"%pred_epc)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
import qiskit as qk
import numpy as np
from scipy.optimize import curve_fit
from qiskit.tools.qcvv.fitters import exp_fit_fun, osc_fit_fun, plot_coherence
# function for padding with QId gates
def pad_QId(circuit,N,qr):
# circuit to add to, N = number of QId gates to add, qr = qubit reg
for ii in range(N):
circuit.barrier(qr)
circuit.iden(qr)
return circuit
qk.register(qx_config['APItoken'], qx_config['url'])
# backend and token settings
backend = qk.get_backend('ibmqx4') # the device to run on
shots = 1024 # the number of shots in the experiment
# Select qubit whose T1 is to be measured
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
# the delay times are all set in terms of single-qubit gates
# so we need to calculate the time from these parameters
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=10
gates_per_step=120
max_gates=(steps-1)*gates_per_step+1
tot_length=buffer_length+pulse_length
time_per_step=gates_per_step*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t1_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t1 = t1_job.result()
keys_0_1=list(result_t1.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps in microseconds
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t1.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
# fit the data to an exponential
fitT1, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,2,0], [1., 500, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT1, exp_fit_fun, punit, 'T$_1$ ', qubit)
print("a: " + str(round(fitT1[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T1: " + str(round(fitT1[1],2))+ " µs" + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT1[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
str(params['T1']['value']) +' ' + params['T1']['unit']
# Select qubit on which to measure T2*
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=35
gates_per_step=20
max_gates=(steps-1)*gates_per_step+2
num_osc=5
tot_length=buffer_length+pulse_length
time_per_step=gates_per_step*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].u1(2*np.pi*num_osc*ii/(steps-1),qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2star_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2star = t2star_job.result()
keys_0_1=list(result_t2star.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2star.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2s, fcov = curve_fit(osc_fit_fun, xvals, data, p0=[0.5, 100, 1/10, np.pi, 0], bounds=([0.3,0,0,0,0], [0.5, 200, 1/2,2*np.pi,1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2s, osc_fit_fun, punit, '$T_2^*$ ', qubit)
print("a: " + str(round(fitT2s[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2*: " + str(round(fitT2s[1],2))+ " µs"+ u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("f: " + str(round(10**3*fitT2s[2],3)) + 'kHz' + u" \u00B1 " + str(round(10**6*ferr[2],3)) + 'kHz')
print("phi: " + str(round(fitT2s[3],2)) + u" \u00B1 " + str(round(ferr[3],2)))
print("c: " + str(round(fitT2s[4],2)) + u" \u00B1 " + str(round(ferr[4],2)))
# Select qubit to measure T2 echo on
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=18
gates_per_step=28
tot_length=buffer_length+pulse_length
max_gates=(steps-1)*2*gates_per_step+3
time_per_step=(2*gates_per_step)*tot_length
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num],gates_per_step*ii,qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2echo_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2echo = t2echo_job.result()
keys_0_1=list(result_t2echo.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2echo.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2e, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2e, exp_fit_fun, punit, '$T_{2echo}$ ', qubit)
print("a: " + str(round(fitT2e[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2: " + str(round(fitT2e[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT2e[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
str(params['T2']['value']) +' ' + params['T2']['unit']
# Select qubit for CPMG measurement of T2
qubit=1
# Creating registers
qr = qk.QuantumRegister(5)
cr = qk.ClassicalRegister(5)
params = backend.parameters['qubits'][qubit]
pulse_length=params['gateTime']['value'] # single-qubit gate time
buffer_length=params['buffer']['value'] # spacing between pulses
unit = params['gateTime']['unit']
steps=10
gates_per_step=18
num_echo=5 # has to be odd number to end up in excited state at the end
tot_length=buffer_length+pulse_length
time_per_step=((num_echo+1)*gates_per_step+num_echo)*tot_length
max_gates=num_echo*(steps-1)*gates_per_step+num_echo+2
qc_dict={}
for ii in range(steps):
step_num='step_%s'%(str(ii))
qc_dict.update({step_num:qk.QuantumCircuit(qr, cr)})
qc_dict[step_num].h(qr[qubit])
for iii in range(num_echo):
qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit])
qc_dict[step_num].x(qr[qubit])
qc_dict[step_num]=pad_QId(qc_dict[step_num], gates_per_step*ii, qr[qubit])
qc_dict[step_num].h(qr[qubit])
qc_dict[step_num].barrier(qr[qubit])
qc_dict[step_num].measure(qr[qubit], cr[qubit])
circuits=list(qc_dict.values())
# run the program
status = backend.status
if status['operational'] == False or status['pending_jobs'] > 10:
print('Warning: the selected backend appears to be busy or unavailable at present; consider choosing a different one if possible')
t2cpmg_job=qk.execute(circuits, backend, shots=shots)
# arrange the data from the run
result_t2cpmg = t2cpmg_job.result()
keys_0_1=list(result_t2cpmg.get_counts(qc_dict['step_0']).keys())# get the key of the excited state '00001'
# change unit from ns to microseconds
plot_factor=1
if unit.find('ns')>-1:
plot_factor=1000
punit='$\mu$s'
xvals=time_per_step*np.linspace(0,len(qc_dict.keys()),len(qc_dict.keys()))/plot_factor # calculate the time steps
data=np.zeros(len(qc_dict.keys())) # numpy array for data
sigma_data = np.zeros(len(qc_dict.keys()))
for ii,key in enumerate(qc_dict.keys()):
# get the data in terms of counts for the excited state normalized to the total number of counts
data[ii]=float(result_t2cpmg.get_counts(qc_dict[key])[keys_0_1[1]])/shots
sigma_data[ii] = np.sqrt(data[ii]*(1-data[ii]))/np.sqrt(shots)
fitT2cpmg, fcov = curve_fit(exp_fit_fun, xvals, data, bounds=([-1,10,0], [1, 150, 1]))
ferr = np.sqrt(np.diag(fcov))
plot_coherence(xvals, data, sigma_data, fitT2cpmg, exp_fit_fun, punit, '$T_{2cpmg}$ ', qubit)
print("a: " + str(round(fitT2cpmg[0],2)) + u" \u00B1 " + str(round(ferr[0],2)))
print("T2: " + str(round(fitT2cpmg[1],2))+ ' µs' + u" \u00B1 " + str(round(ferr[1],2)) + ' µs')
print("c: " + str(round(fitT2cpmg[2],2)) + u" \u00B1 " + str(round(ferr[2],2)))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Needed for functions
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.quantum_info import state_fidelity
from qiskit.providers.aer import noise
# Tomography functions
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
import qiskit.ignis.mitigation.measurement as mc
# Create the expected density matrix
q2 = QuantumRegister(2)
bell = QuantumCircuit(q2)
bell.h(q2[0])
bell.cx(q2[0], q2[1])
print(bell)
job = qiskit.execute(bell, Aer.get_backend('statevector_simulator'))
psi_bell = job.result().get_statevector(bell)
print(psi_bell)
# Create the actual circuit
q2 = QuantumRegister(6)
bell = QuantumCircuit(q2)
bell.h(q2[3])
bell.cx(q2[3], q2[5])
print(bell)
# Generate circuits and run on simulator
t = time.time()
# Generate the state tomography circuits. Only pass in the
# registers we want to measure (in this case 3 and 5)
qst_bell = state_tomography_circuits(bell, [q2[3],q2[5]])
job = qiskit.execute(qst_bell, Aer.get_backend('qasm_simulator'), shots=5000)
print('Time taken:', time.time() - t)
# Generate the state tomography circuits using the default settings for
# basis
tomo_bell = StateTomographyFitter(job.result(), qst_bell)
# Perform the tomography fit
# which outputs a density matrix
rho_bell = tomo_bell.fit()
F_bell = state_fidelity(psi_bell, rho_bell)
print('Fit Fidelity =', F_bell)
#Add measurement noise
noise_model = noise.NoiseModel()
for qi in range(6):
read_err = noise.errors.readout_error.ReadoutError([[0.75, 0.25],[0.1,0.9]])
noise_model.add_readout_error(read_err,[qi])
#generate the calibration circuits
meas_calibs, state_labels = mc.complete_meas_cal(qubit_list=[3,5])
backend = Aer.get_backend('qasm_simulator')
qobj_cal = qiskit.compile(meas_calibs, backend=backend, shots=15000)
qobj_tomo = qiskit.compile(qst_bell, backend=backend, shots=15000)
job_cal = backend.run(qobj_cal, noise_model=noise_model)
job_tomo = backend.run(qobj_tomo, noise_model=noise_model)
meas_fitter = mc.CompleteMeasFitter(job_cal.result(),state_labels)
tomo_bell = StateTomographyFitter(job_tomo.result(), qst_bell)
#no correction
rho_bell = tomo_bell.fit()
F_bell = state_fidelity(psi_bell, rho_bell)
print('Fit Fidelity (no correction) =', F_bell)
#correct data
correct_tomo_results = meas_fitter.filter.apply(job_tomo.result(), method='least_squares')
tomo_bell = StateTomographyFitter(correct_tomo_results, qst_bell)
rho_bell = tomo_bell.fit()
F_bell = state_fidelity(psi_bell, rho_bell)
print('Fit Fidelity (w/ correction) =', F_bell)
def random_u3_tomo(nq, shots):
def rand_angles():
return tuple(2 * np.pi * np.random.random(3) - np.pi)
q = QuantumRegister(nq)
circ = QuantumCircuit(q)
for j in range(nq):
circ.u3(*rand_angles(), q[j])
job = qiskit.execute(circ, Aer.get_backend('statevector_simulator'))
psi_rand = job.result().get_statevector(circ)
qst_circs = state_tomography_circuits(circ, q)
job = qiskit.execute(qst_circs, Aer.get_backend('qasm_simulator'),
shots=shots)
tomo_data = StateTomographyFitter(job.result(), qst_circs)
rho_cvx = tomo_data.fit(method='cvx')
rho_lstsq = tomo_data.fit(method='lstsq')
print('F fit (CVX) =', state_fidelity(psi_rand, rho_cvx))
print('F fit (LSTSQ) =', state_fidelity(psi_rand, rho_lstsq))
for j in range(5):
print('Random single-qubit unitaries: set {}'.format(j))
random_u3_tomo(3, 5000)
# Create a state preparation circuit
q5 = QuantumRegister(5)
bell5 = QuantumCircuit(q5)
bell5.h(q5[0])
for j in range(4):
bell5.cx(q5[j], q5[j + 1])
# Get ideal output state
job = qiskit.execute(bell5, Aer.get_backend('statevector_simulator'))
psi_bell5 = job.result().get_statevector(bell5)
# Generate circuits and run on simulator
t = time.time()
qst_bell5 = state_tomography_circuits(bell5, q5)
job = qiskit.execute(qst_bell5, Aer.get_backend('qasm_simulator'), shots=5000)
# Extract tomography data so that counts are indexed by measurement configuration
tomo_bell5 = StateTomographyFitter(job.result(), qst_bell5)
print('Time taken:', time.time() - t)
t = time.time()
rho_lstsq_bell5 = tomo_bell5.fit(method='lstsq')
print('Least-Sq Reconstruction')
print('Time taken:', time.time() - t)
print('Fit Fidelity:', state_fidelity(psi_bell5, rho_lstsq_bell5))
t = time.time()
rho_cvx_bell5 = tomo_bell5.fit(method='cvx')
print('CVX Reconstruction')
print('Time taken:', time.time() - t)
print('Fidelity:', state_fidelity(psi_bell5, rho_cvx_bell5))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import *
IBMQ.load_accounts(hub=None)
from qiskit.tools.jupyter import *
from qiskit.tools.monitor import job_monitor
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c);
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
backend.name()
job = execute(qc, backend)
job_monitor(job, monitor_async=True)
%%qiskit_job_status
job2 = execute(qc, backend)
num_jobs = 5
my_jobs = []
for j in range(num_jobs):
my_jobs.append(execute(qc, backend))
job_monitor(my_jobs[j], monitor_async=True)
%%qiskit_job_status
my_jobs2 = []
for j in range(num_jobs):
my_jobs2.append(execute(qc, backend))
%%qiskit_job_status
import numpy as np
my_jobs3 = np.empty(num_jobs, dtype=object)
for j in range(num_jobs):
my_jobs3[j] = execute(qc, backend)
%%qiskit_job_status -i 5
job4 = execute(qc, backend)
%%qiskit_job_status --interval 5
job5 = execute(qc, backend)
%qiskit_backend_monitor backend
%qiskit_backend_overview
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import *
IBMQ.load_accounts(hub=None)
from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c);
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(filters=lambda x: not x.configuration().simulator))
backend.name()
job1 = execute(qc, backend)
job_monitor(job1)
job2 = execute(qc, backend)
job_monitor(job2, interval=5)
backend_monitor(backend)
backend_overview()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
def run_hadamard_simulator(number_of_qubits, list_of_qubits, shots):
'''
Run our amazing Hadamard simulator!
Note: this function is not designed to be efficient
Args:
number_of_qubits (integer): number of qubits in the qunatum circuit
list_of_qubits (list of integers): a list of qubits on whom Hadamard gates are applied
shots (integer): number of shots
Returns:
list of integers:
each entry in the list contains the number of shots
where the measurement result is the correspnding basis state;
basis states are ordered lexicographically
'''
# For each qubit, store whether it is manipulated by an odd number of Hadamard gates
# Example: for run_hadamard_simulator(5, [3, 1, 3, 4], 100)
# we obtain hadamard_list:
# [0, 1, 0, 0, 1]
# because qubits 1 and 4 have an odd number of Hadamard gates.
hadamard_list = [0]*number_of_qubits
for qubit in list_of_qubits:
hadamard_list[qubit] = (1 + hadamard_list[qubit])%2
# Calculate the result for each basis state
result = [0]*(2**number_of_qubits)
for i in range(2**number_of_qubits):
# Example: when i is 2,
# the basis_state is 01000
basis_state = '{0:b}'.format(i).zfill(number_of_qubits)[::-1]
for qubit in range(number_of_qubits):
if hadamard_list[qubit] == 0 and basis_state[qubit] == '1':
result[i] = 0
break
if hadamard_list[qubit] == 1:
result[i] += int(shots/(2**(1 + hadamard_list.count(1))))
return result
run_hadamard_simulator(4, [3, 1, 3, 2], 1024)
from qiskit.providers import BaseJob
class HadamardJob(BaseJob):
def __init__(self, backend):
super().__init__(backend, 1)
def result(self):
return self._result
def cancel(self):
pass
def status(self):
pass
def submit(self):
pass
from qiskit.providers import BaseBackend
from qiskit.providers.models import BackendConfiguration
from qiskit import qobj as qiskit_qobj
from qiskit.result import Result
class HadamardSimulator(BaseBackend):
'''
A wrapper backend for the Hadamard simulator
'''
def __init__(self, provider=None):
configuration = {
'backend_name': 'hadamard_simulator',
'backend_version': '0.1.0',
'url': 'http://www.i_love_hadamard.com',
'simulator': True,
'local': True,
'description': 'Simulates only Hadamard gates',
'basis_gates': ['h', 'x'], # basis_gates must contain at least two gates
'memory': True,
'n_qubits': 30,
'conditional': False,
'max_shots': 100000,
'open_pulse': False,
'gates': [
{
'name': 'TODO',
'parameters': [],
'qasm_def': 'TODO'
}
]
}
# We will explain about the provider in the next section
super().__init__(configuration=BackendConfiguration.from_dict(configuration),
provider=provider)
def run(self, qobj):
"""Run qobj
Args:
qobj (QObj): circuit description
Returns:
HadamardJob: derived from BaseJob
"""
hadamard_job = HadamardJob(None)
experiment_results = []
for circuit_index, circuit in enumerate(qobj.experiments):
number_of_qubits = circuit.config.n_qubits
shots = qobj.config.shots
list_of_qubits = []
for operation in circuit.instructions:
if getattr(operation, 'conditional', None):
raise QiskitError('conditional operations are not supported '
'by the Hadamard simulator')
if operation.name != 'h':
if operation.name == 'measure':
continue
else:
raise QiskitError('The Hadamrd simulator allows only Hadamard gates')
list_of_qubits.append(operation.qubits[0])
# Need to verify that
# all the qubits are measured, and to different classical registers.
# Raise an error otherwise.
# We skip this part here.
counts = run_hadamard_simulator(number_of_qubits, list_of_qubits, shots)
formatted_counts = {}
for i in range(2**number_of_qubits):
if counts[i] != 0:
formatted_counts[hex(i)] = counts[i]
experiment_results.append({
'name': circuit.header.name,
'success': True,
'shots': shots,
'data': {'counts': formatted_counts},
'header': circuit.header.as_dict()
})
hadamard_job._result = Result.from_dict({
'results': experiment_results,
'backend_name': 'hadamard_simulator',
'backend_version': '0.1.0',
'qobj_id': '0',
'job_id': '0',
'success': True
})
return hadamard_job
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.transpiler import PassManager
qreg = QuantumRegister(4)
creg = ClassicalRegister(4)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[3])
qc.h(qreg[1])
qc.h(qreg[3])
qc.h(qreg[2])
qc.measure(qreg, creg)
hadamard_job = execute(qc, backend=HadamardSimulator(), pass_manager=PassManager(), shots=1024)
result = hadamard_job.result()
print(result.get_counts(qc))
from qiskit.providers import BaseProvider
from qiskit.providers.providerutils import filter_backends
class HadamardProvider(BaseProvider):
"""Provider for the Hadamard backend"""
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
# Populate the list of Hadamard backends
self._backends = [HadamardSimulator(provider=self)]
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
backends = self._backends
if name:
backends = [backend for backend in backends if backend.name() == name]
return filter_backends(backends, filters=filters, **kwargs)
from qiskit import execute, Aer
from qiskit.transpiler import PassManager
hadamard_provider = HadamardProvider()
new_hadamard_job = execute(qc, hadamard_provider.get_backend('hadamard_simulator'),
pass_manager=PassManager(), shots=1024)
new_hadamard_result = new_hadamard_job.result()
aer_job = execute(qc, Aer.get_backend('qasm_simulator'),
pass_manager=PassManager(), shots=1024)
aer_result = aer_job.result()
print('Hadamard simulator:')
print(new_hadamard_result.get_counts(qc))
print('Aer simulator:')
print(aer_result.get_counts(qc))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.compiler import transpile
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.measure_all()
qc1.draw(output='mpl')
job1 = execute(qc1, backend=QasmSimulator(), shots=1024)
plot_histogram(job1.result().get_counts())
qc2 = QuantumCircuit(2)
# State Preparation
qc2.x(0)
qc2.barrier()
# Perform q_0 XOR 0
qc2.cx(0,1)
qc2.measure_all()
qc2.draw(output='mpl')
job2 = execute(qc2.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job2.result().get_counts())
qc3 = QuantumCircuit(3)
# State Preparation
qc3.x(0)
qc3.x(1)
qc3.barrier()
# Perform q_0 XOR 0
qc3.ccx(0,1,2)
qc3.measure_all()
qc3.draw(output='mpl')
job3 = execute(qc3.reverse_bits(), backend=QasmSimulator(), shots=1024)
plot_histogram(job3.result().get_counts())
qc4 = QuantumCircuit(3)
# State Preparation
qc4.h(range(3))
qc4.measure_all()
qc4.draw(output='mpl')
job4 = execute(qc4.reverse_bits(), backend=QasmSimulator(), shots=8192)
plot_histogram(job4.result().get_counts())
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeMelbourne
device_backend = FakeMelbourne()
coupling_map = device_backend.configuration().coupling_map
noise_model = NoiseModel.from_backend(device_backend)
basis_gates = noise_model.basis_gates
result_noise = execute(qc4, QasmSimulator(),
shots=8192,
noise_model=noise_model,
coupling_map=coupling_map,
basis_gates=basis_gates).result()
plot_histogram(result_noise.get_counts())
qc3_t = transpile(qc3, basis_gates=basis_gates)
qc3_t.draw(output='mpl')
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
provider.backends()
ibmq_backend = provider.get_backend('ibmq_16_melbourne')
result_device = execute(qc4, backend=ibmq_backend, shots=8192).result()
plot_histogram(result_device.get_counts())
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u2(pi/2,pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u1(pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u0(pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.iden(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu1(pi/2,q[0], q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu3(pi/2, pi/2, pi/2, q[0], q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = execute(qc, backend, shots=1024)
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw(output='latex')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import *
from qiskit.tools.parallel import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.tools.jupyter import * # Needed to load the Jupyter HTMLProgressBar
num_circuits = 1000
width = 4
depth = 4
import copy
import math
import numpy as np
from qiskit.tools.qi.qi import random_unitary_matrix
from qiskit.mapper import two_qubit_kak
def build_qv_circuit(idx, seeds, width, depth):
"""Builds a single Quantum Volume circuit. Two circuits,
one with measurements, and one widthout, are returned.
The model circuits consist of layers of Haar random
elements of SU(4) applied between corresponding pairs
of qubits in a random bipartition.
See: https://arxiv.org/abs/1811.12926
"""
np.random.seed(seeds[idx])
q = QuantumRegister(width, "q")
c = ClassicalRegister(width, "c")
# Create measurement subcircuit
qc = QuantumCircuit(q,c)
# For each layer
for j in range(depth):
# Generate uniformly random permutation Pj of [0...n-1]
perm = np.random.permutation(width)
# For each pair p in Pj, generate Haar random SU(4)
# Decompose each SU(4) into CNOT + SU(2) and add to Ci
for k in range(math.floor(width/2)):
qubits = [int(perm[2*k]), int(perm[2*k+1])]
U = random_unitary_matrix(4)
for gate in two_qubit_kak(U):
i0 = qubits[gate["args"][0]]
if gate["name"] == "cx":
i1 = qubits[gate["args"][1]]
qc.cx(q[i0], q[i1])
elif gate["name"] == "u1":
qc.u1(gate["params"][2], q[i0])
elif gate["name"] == "u2":
qc.u2(gate["params"][1], gate["params"][2],
q[i0])
elif gate["name"] == "u3":
qc.u3(gate["params"][0], gate["params"][1],
gate["params"][2], q[i0])
elif gate["name"] == "id":
pass # do nothing
qc_no_meas = copy.deepcopy(qc)
# Create circuit with final measurement
qc.measure(q,c)
return qc, qc_no_meas
num_circuits = 1000
seeds = np.random.randint(np.iinfo(np.int32).max, size=num_circuits)
TextProgressBar()
parallel_map(build_qv_circuit, np.arange(num_circuits), task_args=(seeds, width, depth));
seeds = np.random.randint(np.iinfo(np.int32).max, size=num_circuits)
HTMLProgressBar()
parallel_map(build_qv_circuit, np.arange(num_circuits), task_args=(seeds, width, depth));
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
n = 3 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
circuit = QuantumCircuit(q, c)
circuit.x(q[1])
circuit.h(q)
circuit.cx(q[0], q[1])
circuit.measure(q, c);
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Latex Drawing
circuit.draw(output='latex')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='latex')
# Draw the circuit with reversed bit order
circuit.draw(output='latex', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='latex', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='latex', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text', line_length=80)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
# Scale the latex output to 1/2 the normal size
circuit.draw(output='latex', scale=0.5)
# Print the latex source for the visualization
print(circuit.draw(output='latex_source'))
# Save the latex source to a file
circuit.draw(output='latex_source', filename='/tmp/circuit.tex');
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import *
Aer.backends()
IBMQ.load_accounts()
IBMQ.backends()
from pprint import pprint
backend_name = 'ibmqx4'
backend = IBMQ.get_backend(backend_name)
backend.status()
backend.configuration()
backend.properties()
from qiskit.backends.ibmq import least_busy
devices = IBMQ.backends(simulator=False)
least_busy_device = least_busy(devices)
least_busy_device.status()
last_10_jobs = least_busy_device.jobs(limit=10)
for j in last_10_jobs:
print(j.job_id())
from qiskit.tools.visualization import circuit_drawer
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.tdg(qr[2])
circ.cx(qr[2], qr[1])
circ.x(qr[2])
circ.cx(qr[0], qr[2])
circ.cx(qr[1], qr[3])
circ.measure(qr, cr)
circuit_drawer(circ, scale=0.5)
%matplotlib inline
qiskit.tools.visualization.matplotlib_circuit_drawer(circ)
simulator_backend = IBMQ.get_backend(simulator=True, hub=None)
job = execute(circ, simulator_backend)
import time
from qiskit.backends import JobStatus
print(job.status())
while job.status() != JobStatus.DONE:
time.sleep(1)
print(job.status())
qobj = compile(circ, simulator_backend)
compiled_circ = qobj_to_circuits(qobj)[0]
circuit_drawer(compiled_circ, scale=0.5)
qobj.as_dict()
job = simulator_backend.run(qobj)
result = job.result()
import qiskit.wrapper.jupyter
%%qiskit_job_status
job = execute(circ, backend)
%%qiskit_progress_bar
qobj = compile(circ, backend)
from qiskit import *
from qiskit.tools.visualization.interactive import *
q = QuantumRegister(5)
circ1 = QuantumCircuit(q)
circ1.h(q)
circ1.ry(1.3, q[0])
circ1.cx(q[0], q[1])
statevector_simulator = Aer.get_backend('statevector_simulator')
result = execute(circ1, statevector_simulator).result()
psi = result.get_statevector()
iplot_state(psi, method='qsphere') # method could be city, paulivec, qsphere, bloch, wigner
# Not displayable in github
c = ClassicalRegister(5)
circ2 = QuantumCircuit(q, c)
circ2.h(q)
circ2.measure(q, c)
circ3 = QuantumCircuit(q, c)
circ3.h(q[0])
circ3.y(q[1])
circ3.cx(q[1], q[0])
circ3.measure(q, c)
qasm_simulator = Aer.get_backend('qasm_simulator')
result = execute([circ2, circ3], qasm_simulator).result()
counts_list = [result.get_counts(circ) for circ in [circ2, circ3]]
# Needs to be run in Jupyter, will not render on github
iplot_histogram(counts_list, legend=['first circuit', 'second circuit'])
# Not displayable in github
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.qi.qi import qft
import numpy as np
import copy
# Setting up a Hadamard QPE circuit for demonstrations below.
def h_qpe(circ, q, n):
for i in range(n-1):
circ.h(q[i])
for j in range(0, n-1, 2): # Only place a CH^n on every other qubit, because CX^n = I for n even
circ.ch(q[j], q[n-1])
circ.barrier()
qft(circ, q, n-1)
n = 5
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
circuit = QuantumCircuit(qr, cr)
circuit.rx(np.pi/4, qr[n-1])
circuit.barrier()
h_qpe(circuit, qr, n)
unt_circ = copy.deepcopy(circuit)
circuit.barrier()
circuit.measure(qr, cr)
%%capture --no-display
from qiskit import BasicAer, LegacySimulators, Aer
qasm_backend = BasicAer.get_backend('qasm_simulator')
sv_backend = BasicAer.get_backend('statevector_simulator')
unt_backend = BasicAer.get_backend('unitary_simulator')
# Setup
from qiskit import execute
qasm_job = execute(circuit, qasm_backend)
sv_job = execute(unt_circ, sv_backend)
unt_job = execute(unt_circ, unt_backend)
qasm_result = qasm_job.result()
sv_result = sv_job.result()
unt_result = unt_job.result()
qasm_result.data()
sv_result.data()
unt_result.data()
# Not displayed because results are too large for github.
qasm_result.get_counts()
sv_result.get_statevector()
unt_result.get_unitary()
len(sv_result.get_statevector())
from qiskit import LegacySimulators
from qiskit.extensions.simulator.snapshot import snapshot
snap_backend = LegacySimulators.get_backend('statevector_simulator')
snap_unt_circ = copy.deepcopy(unt_circ)
snap_unt_circ.snapshot(10)
sv_job = execute(snap_unt_circ, snap_backend)
sv_result = sv_job.result()
sv_result.data()['snapshots']
from qiskit.quantum_info.analyzation.average import average_data
counts = qasm_result.get_counts()
iden = np.eye(len(counts))
oper = {}
for i, key in enumerate(counts.keys()):
oper[key] = iden[i]
average_data(counts, oper)
#!pip install qiskit-terra[visualization]
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.visualization.dag_visualization import dag_drawer
lin_len = 98
# Change to wider in Jupyter, this is only to render nicely in github
circuit.draw(line_length=lin_len)
style = {'cregbundle': True, 'usepiformat': True, 'subfontsize': 12, 'fold': 100, 'showindex': True,
'backgroundcolor': '#fffaff',
"displaycolor": { # Taken from qx_color_scheme() in _circuit_visualization.py
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"}}
circuit.draw(output='mpl', style=style)
circuit.draw(output='latex_source', plot_barriers=False)
circuit.draw(output='latex', plot_barriers=False)
from qiskit import transpiler
draw_circ = transpiler.transpile(circuit, qasm_backend, basis_gates='U,CX')
draw_circ.draw(line_length=2000)
# Not shown in github for rendering reasons, load in Jupyter
from qiskit.tools.qi.qi import outer
from qiskit.tools.visualization import plot_histogram, plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere
from qiskit.tools.visualization import iplot_histogram, iplot_state_city, iplot_bloch_multivector, iplot_state_paulivec, iplot_state_hinton, iplot_state_qsphere
counts = qasm_result.get_counts()
phi = sv_result.get_statevector()
rho = outer(phi)
plot_histogram(counts)
plot_state_city(rho)
plot_state_hinton(rho)
hist_fig = plot_histogram(counts)
state_fig = plot_state_city(rho)
hist_fig.savefig('histogram.png')
state_fig.savefig('state_plot.png')
iplot_bloch_multivector(rho)
# Not displayed in github, download and run loacally.
from qiskit.converters.circuit_to_dag import circuit_to_dag
my_dag = circuit_to_dag(circuit)
dag_drawer(my_dag)
job = execute(circuit, qasm_backend, shots=50, memory=True)
result = job.result()
result.get_memory(circuit)
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, CXCancellation, LookaheadSwap, StochasticSwap
from qiskit.transpiler import transpile
from qiskit.mapper import CouplingMap
qr = QuantumRegister(7, 'q')
qr = QuantumRegister(7, 'q')
tpl_circuit = QuantumCircuit(qr)
tpl_circuit.h(qr[3])
tpl_circuit.cx(qr[0], qr[6])
tpl_circuit.cx(qr[6], qr[0])
tpl_circuit.cx(qr[0], qr[1])
tpl_circuit.cx(qr[3], qr[1])
tpl_circuit.cx(qr[3], qr[0])
tpl_circuit.draw()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
simulator = BasicAer.get_backend('qasm_simulator')
coupling_map = CouplingMap(couplinglist=coupling)
pass_manager = PassManager()
pass_manager.append([BasicSwap(coupling_map=coupling_map)])
basic_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
basic_circ.draw()
pass_manager = PassManager()
pass_manager.append([LookaheadSwap(coupling_map=coupling_map)])
lookahead_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
lookahead_circ.draw()
pass_manager = PassManager()
pass_manager.append([StochasticSwap(coupling_map=coupling_map)])
stoch_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
stoch_circ.draw()
qasm_job = execute(circuit, qasm_backend, pass_manager=PassManager())
from qiskit.converters.dag_to_circuit import dag_to_circuit
new_circ_from_dag = dag_to_circuit(my_dag)
new_circ_from_dag.draw(line_length = lin_len)
from qiskit import QuantumCircuit
qasm_str = circuit.qasm()
new_circ = QuantumCircuit.from_qasm_str(qasm_str)
new_circ.draw(line_length = lin_len)
filepath = 'my_qasm_file.txt'
qasm_file = open(filepath, "w")
qasm_file.write(unt_circ.qasm())
qasm_file.close()
new_unt_circ = QuantumCircuit.from_qasm_file(filepath)
new_unt_circ.draw(line_length = lin_len)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from math import pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer, qx_color_scheme
# We recommend the following options for Jupter notebook
%matplotlib inline
# Create a Quantum Register called "q" with 3 qubits
qr = QuantumRegister(3, 'q')
# Create a Classical Register called "c" with 3 bits
cr = ClassicalRegister(3, 'c')
# Create a Quantum Circuit called involving "qr" and "cr"
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0]).c_if(cr, 3)
circuit.z(qr[0])
circuit.u2(pi/2, 2*pi/3, qr[1])
circuit.cu1(pi, qr[0], qr[1])
# Barrier to seperator the input from the circuit
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])
# Toffoli gate from qubit 0,1 to qubit 2
circuit.ccx(qr[0], qr[1], qr[2])
# CNOT (Controlled-NOT) gate from qubit 0 to qubit 1
circuit.cx(qr[0], qr[1])
circuit.swap(qr[0], qr[2])
# measure gate from qr to cr
circuit.measure(qr, cr)
QASM_source = circuit.qasm()
print(QASM_source)
drawer(circuit)
drawer(circuit, basis='u1,u2,u3,id,cx', scale=1.0)
my_style = {'plotbarrier': True}
drawer(circuit, style=my_style)
my_style = {'cregbundle': True}
drawer(circuit, style=my_style)
my_style = {'showindex': True}
drawer(circuit, style=my_style)
my_style = {'compress': True}
drawer(circuit, style=my_style)
my_style = {'fold': 6}
drawer(circuit, style=my_style)
my_style = {'usepiformat': True}
drawer(circuit, style=my_style)
qr = QuantumRegister(1, 'q')
circuit_xyz = QuantumCircuit(qr)
circuit_xyz.x(qr[0])
circuit_xyz.y(qr[0])
circuit_xyz.z(qr[0])
drawer(circuit_xyz)
my_style = {'displaytext': {'x': '😺', 'y': '\Sigma', 'z': '✈'}}
drawer(circuit_xyz, style=my_style)
qr = QuantumRegister(2, 'q')
circuit_cucz = QuantumCircuit(qr)
circuit_cucz.cz(qr[0], qr[1])
circuit_cucz.cu1(pi, qr[0], qr[1])
drawer(circuit_cucz)
my_style = {'latexdrawerstyle': False}
drawer(circuit_cucz, style=my_style)
qr = QuantumRegister(3, 'q')
cr = ClassicalRegister(3, 'c')
circuit_all = QuantumCircuit(qr, cr)
circuit_all.x(qr[0])
circuit_all.y(qr[0])
circuit_all.z(qr[0])
circuit_all.barrier(qr[0])
circuit_all.barrier(qr[1])
circuit_all.barrier(qr[2])
circuit_all.h(qr[0])
circuit_all.s(qr[0])
circuit_all.sdg(qr[0])
circuit_all.t(qr[0])
circuit_all.tdg(qr[0])
circuit_all.iden(qr[0])
circuit_all.reset(qr[0])
circuit_all.rx(pi, qr[0])
circuit_all.ry(pi, qr[0])
circuit_all.rz(pi, qr[0])
circuit_all.u0(pi, qr[0])
circuit_all.u1(pi, qr[0])
circuit_all.u2(pi, pi, qr[0])
circuit_all.u3(pi, pi, pi, qr[0])
circuit_all.swap(qr[0], qr[1])
circuit_all.cx(qr[0], qr[1])
circuit_all.cy(qr[0], qr[1])
circuit_all.cz(qr[0], qr[1])
circuit_all.ch(qr[0], qr[1])
circuit_all.cu1(pi, qr[0], qr[1])
circuit_all.cu3(pi, pi, pi, qr[0], qr[1])
circuit_all.crz(pi, qr[0], qr[1])
circuit_all.ccx(qr[0], qr[1], qr[2])
circuit_all.cswap(qr[0], qr[1], qr[2])
circuit_all.measure(qr, cr)
drawer(circuit_all)
cmp_style = qx_color_scheme()
cmp_style
drawer(circuit_all, style=cmp_style)
cmp_style.update({
'usepiformat': True,
'showindex': True,
'cregbundle': True,
'compress': True,
'fold': 17
})
drawer(circuit_all, filename='circuit.pdf', style=cmp_style)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import the QuantumProgram and our configuration
import math
from pprint import pprint
from qiskit import QuantumProgram
import Qconfig
qp = QuantumProgram()
# quantum register for the first circuit
q1 = qp.create_quantum_register('q1', 4)
c1 = qp.create_classical_register('c1', 4)
# quantum register for the second circuit
q2 = qp.create_quantum_register('q2', 2)
c2 = qp.create_classical_register('c2', 2)
# making the first circuits
qc1 = qp.create_circuit('GHZ', [q1], [c1])
qc2 = qp.create_circuit('superposition', [q2], [c2])
qc1.h(q1[0])
qc1.cx(q1[0], q1[1])
qc1.cx(q1[1], q1[2])
qc1.cx(q1[2], q1[3])
for i in range(4):
qc1.measure(q1[i], c1[i])
# making the second circuits
qc2.h(q2)
for i in range(2):
qc2.measure(q2[i], c2[i])
# printing the circuits
print(qp.get_qasm('GHZ'))
print(qp.get_qasm('superposition'))
qobj = qp.compile(['GHZ','superposition'], backend='local_qasm_simulator')
qp.get_execution_list(qobj)
qp.get_execution_list(qobj, verbose=True)
qp.get_compiled_configuration(qobj, 'GHZ', )
print(qp.get_compiled_qasm(qobj, 'GHZ'))
# Coupling map
coupling_map = {0: [1, 2, 3]}
# Place the qubits on a triangle in the bow-tie
initial_layout={("q1", 0): ("q", 0), ("q1", 1): ("q", 1), ("q1", 2): ("q", 2), ("q1", 3): ("q", 3)}
qobj = qp.compile(['GHZ'], backend='local_qasm_simulator', coupling_map=coupling_map, initial_layout=initial_layout)
print(qp.get_compiled_qasm(qobj,'GHZ'))
# Define methods for making QFT circuits
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
qp = QuantumProgram()
q = qp.create_quantum_register("q", 3)
c = qp.create_classical_register("c", 3)
qft3 = qp.create_circuit("qft3", [q], [c])
input_state(qft3, q, 3)
qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
print(qft3.qasm())
result = qp.execute(["qft3"], backend="local_qasm_simulator", shots=1024)
result.get_counts("qft3")
print(result.get_ran_qasm("qft3"))
# Coupling map for ibmqx2 "bowtie"
coupling_map = {0: [1, 2],
1: [2],
2: [],
3: [2, 4],
4: [2]}
# Place the qubits on a triangle in the bow-tie
initial_layout={("q", 0): ("q", 2), ("q", 1): ("q", 3), ("q", 2): ("q", 4)}
result2 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout)
result2.get_counts("qft3")
print(result2.get_ran_qasm("qft3"))
# Place the qubits on a linear segment of the ibmqx3
coupling_map = {0: [1], 1: [2], 2: [3], 3: [14], 4: [3, 5], 6: [7, 11], 7: [10], 8: [7], 9: [8, 10], 11: [10], 12: [5, 11, 13], 13: [4, 14], 15: [0, 14]}
initial_layout={("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)}
result3 = qp.execute(["qft3"], backend="local_qasm_simulator", coupling_map=coupling_map, initial_layout=initial_layout)
result3.get_counts("qft3")
print(result3.get_ran_qasm("qft3"))
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import random_clifford
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.synthesis import AICliffordSynthesis
from qiskit_transpiler_service.ai.collection import CollectCliffords
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_cairo").coupling_map
circuit = QuantumCircuit(27)
for c in range(3):
nq = 8
qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False)
circuit.compose(random_clifford(nq).to_circuit(), qubits=qs.tolist(), inplace=True)
for q in qs:
circuit.t(q)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.decompose(reps=3).depth()}, Gates(2q): {lvl3_transpiled_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
ai_optimize_cliffords = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name="ibm_canberra"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_cliffords.run(lvl3_transpiled_circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import random_clifford
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.synthesis import AILinearFunctionSynthesis
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_cairo").coupling_map
circuit = QuantumCircuit(27)
for c in range(3):
nq = 8
qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False)
circuit.compose(random_clifford(nq).to_circuit(), qubits=qs.tolist(), inplace=True)
for q in qs:
circuit.t(q)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.decompose(reps=3).depth()}, Gates(2q): {lvl3_transpiled_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
ai_optimize_cliffords = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name="ibm_cairo"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_cliffords.run(lvl3_transpiled_circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectPermutations
from qiskit_transpiler_service.ai.synthesis import AIPermutationSynthesis
from qiskit.circuit.library import Permutation
num_qubits = 27
circuit = QuantumCircuit(num_qubits)
circuit.append(
Permutation(
num_qubits=num_qubits, pattern=[(i + 1) % num_qubits for i in range(num_qubits)]
),
qargs=range(num_qubits),
)
circuit = circuit.decompose(reps=2)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
ai_optimize_perms = PassManager(
[
CollectPermutations(do_commutative_analysis=True),
AIPermutationSynthesis(backend_name="ibm_cairo"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_perms.run(circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.routing import AIRouting
from qiskit.circuit.library import EfficientSU2
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
print(
f"Original circuit -> Depth: {circuit.depth()}, Gates(2q): {circuit.num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
qiskit_ai_transpiler = PassManager(
[AIRouting(backend_name="ibm_torino", optimization_level=1, layout_mode="optimize")]
)
ai_transpiled_circuit = qiskit_ai_transpiler.run(circuit)
print(
f"Qiskit AI Transpiler -> Depth: {ai_transpiled_circuit.depth()}, Gates(2q): {ai_transpiled_circuit.num_nonlocal_gates()}"
)
ai_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_torino").coupling_map
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.depth()}, Gates(2q): {lvl3_transpiled_circuit.num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
from qiskit_transpiler_service.transpiler_service import TranspilerService
qiskit_lvl3_transpiler_service = TranspilerService(
backend_name="ibm_torino",
ai="false",
optimization_level=3,
)
lvl3_transpiled_circuit_v2 = qiskit_lvl3_transpiler_service.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit_v2.depth()}, Gates(2q): {lvl3_transpiled_circuit_v2.num_nonlocal_gates()}"
)
lvl3_transpiled_circuit_v2.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
qiskit_lvl3_ai_transpiler_service = TranspilerService(
backend_name="ibm_torino",
ai="true",
optimization_level=3,
)
lvl3_transpiled_ai_circuit_v2 = qiskit_lvl3_ai_transpiler_service.run(circuit)
print(
f"Qiskit lvl3 AI Transpiler -> Depth: {lvl3_transpiled_ai_circuit_v2.depth()}, Gates(2q): {lvl3_transpiled_ai_circuit_v2.num_nonlocal_gates()}"
)
lvl3_transpiled_ai_circuit_v2.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
from qiskit.circuit.library import EfficientSU2
from qiskit_transpiler_service.transpiler_service import TranspilerService
circuit = EfficientSU2(101, entanglement="circular", reps=1).decompose()
cloud_transpiler_service = TranspilerService(
backend_name="ibm_sherbrooke",
ai="false",
optimization_level=3,
)
transpiled_circuit_no_ai = cloud_transpiler_service.run(circuit)
from qiskit.circuit.library import EfficientSU2
from qiskit_transpiler_service.transpiler_service import TranspilerService
circuit = EfficientSU2(101, entanglement="circular", reps=1).decompose()
cloud_transpiler_service = TranspilerService(
backend_name="ibm_sherbrooke",
ai="true",
optimization_level=1,
)
transpiled_circuit_ai = cloud_transpiler_service.run(circuit)
from qiskit.circuit.library import EfficientSU2
from qiskit_transpiler_service.transpiler_service import TranspilerService
circuit = EfficientSU2(101, entanglement="circular", reps=1).decompose()
cloud_transpiler_service = TranspilerService(
backend_name="ibm_sherbrooke",
ai="auto",
optimization_level=1,
)
transpiled_circuit_ai_auto = cloud_transpiler_service.run(circuit)
from qiskit.circuit.library import EfficientSU2
from qiskit_transpiler_service.transpiler_service import TranspilerService
circuit = EfficientSU2(101, entanglement="circular", reps=1).decompose()
cloud_transpiler_service = TranspilerService(
backend_name="ibm_sherbrooke",
ai="auto",
optimization_level=1,
)
transpiled_circuit = cloud_transpiler_service.run(circuit)
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.routing import AIRouting
from qiskit.circuit.library import EfficientSU2
ai_passmanager = PassManager(
[
AIRouting(
backend_name="ibm_sherbrooke", optimization_level=2, layout_mode="optimize"
)
]
)
circuit = EfficientSU2(101, entanglement="circular", reps=1).decompose()
transpiled_circuit_ai_lvl2 = ai_passmanager.run(circuit)
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.routing import AIRouting
from qiskit_transpiler_service.ai.synthesis import AILinearFunctionSynthesis
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
from qiskit.circuit.library import EfficientSU2
ai_passmanager = PassManager(
[
AIRouting(
backend_name="ibm_torino", optimization_level=3, layout_mode="optimize"
), # Route circuit
CollectLinearFunctions(), # Collect Linear Function blocks
AILinearFunctionSynthesis(
backend_name="ibm_torino"
), # Re-synthesize Linear Function blocks
]
)
circuit = EfficientSU2(10, entanglement="full", reps=1).decompose()
transpiled_circuit_synthesis = ai_passmanager.run(circuit)
print(
f"Depth: {transpiled_circuit_no_ai.decompose(reps=3).depth()}, Gates(2q): {transpiled_circuit_no_ai.decompose(reps=3).num_nonlocal_gates()}"
)
print(
f"Depth: {transpiled_circuit_ai.decompose(reps=3).depth()}, Gates(2q): {transpiled_circuit_ai.decompose(reps=3).num_nonlocal_gates()}"
)
print(
f"Depth: {transpiled_circuit_ai_auto.decompose(reps=3).depth()}, Gates(2q): {transpiled_circuit_ai_auto.decompose(reps=3).num_nonlocal_gates()}"
)
print(
f"Depth: {transpiled_circuit_ai_lvl2.decompose(reps=3).depth()}, Gates(2q): {transpiled_circuit_ai_lvl2.decompose(reps=3).num_nonlocal_gates()}"
)
print(
f"Depth: {transpiled_circuit_synthesis.decompose(reps=3).depth()}, Gates(2q): {transpiled_circuit_synthesis.decompose(reps=3).num_nonlocal_gates()}"
)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""
===============================================================================
Qiskit Transpiler Service (:mod:`qiskit_transpiler_service.transpiler_service`)
===============================================================================
.. currentmodule:: qiskit_transpiler_service.transpiler_service
Classes
=======
.. autosummary::
:toctree: ../stubs/
TranspilerService
"""
import logging
from typing import Dict, List, Union, Literal
from qiskit import QuantumCircuit
from .wrappers.transpile import TranspileAPI
logger = logging.getLogger(__name__)
class TranspilerService:
"""Class for using the transpiler service.
:param optimization_level: The optimization level to use during the transpilation. There are 4 optimization levels ranging from 0 to 3, where 0 is intended for not performing any optimizations and 3 spends the most effort to optimize the circuit.
:type optimization_level: int
:param ai: Specifies if the transpilation should use AI or not, defaults to True.
:type ai: str, optional
:param coupling_map: A list of pairs that represents physical links between qubits.
:type coupling_map: list[list[int]], optional
:param backend_name: Name of the backend used for doing the transpilation.
:type backend_name: str, optional
:param qiskit_transpile_options: Other options to transpile with qiskit.
:type qiskit_transpile_options: dict, optional
:param ai_layout_mode: Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections).
:type ai_layout_mode: str, optional
"""
def __init__(
self,
optimization_level: int,
ai: Literal["true", "false", "auto"] = "true",
coupling_map: Union[List[List[int]], None] = None,
backend_name: Union[str, None] = None,
qiskit_transpile_options: Dict = None,
ai_layout_mode: str = None,
) -> None:
"""Initializes the instance."""
self.transpiler_service = TranspileAPI()
self.backend_name = backend_name
self.coupling_map = coupling_map
self.optimization_level = optimization_level
self.ai = ai
self.qiskit_transpile_options = qiskit_transpile_options
if ai_layout_mode is not None:
if ai_layout_mode.upper() not in ["KEEP", "OPTIMIZE", "IMPROVE"]:
raise (
f"ERROR. Unknown ai_layout_mode: {ai_layout_mode.upper()}. Valid modes: 'KEEP', 'OPTIMIZE', 'IMPROVE'"
)
self.ai_layout_mode = ai_layout_mode.upper()
else:
self.ai_layout_mode = ai_layout_mode
super().__init__()
def run(
self,
circuits: Union[List[Union[str, QuantumCircuit]], Union[str, QuantumCircuit]],
):
"""Transpile the circuit(s) by calling the service /transpile endpoint.
Args:
circuits: circuit(s) to transpile.
Returns:
The transpiled circuit(s)
"""
logger.info(f"Requesting transpile to the service")
transpile_result = self.transpiler_service.transpile(
circuits=circuits,
backend=self.backend_name,
coupling_map=self.coupling_map,
optimization_level=self.optimization_level,
ai=self.ai,
qiskit_transpile_options=self.qiskit_transpile_options,
)
if transpile_result is None:
logger.warning(
"Qiskit transpiler service couldn't transpile the circuit(s)"
)
return None
logger.info("Qiskit transpiler service returned a result")
return transpile_result
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
import pydoc
import re
import pytket.passes as tkps
def get_arguments_from_doc(tket_pass):
arguments = []
_doc = pydoc.getdoc(tket_pass)
if 'Overloaded function.' in _doc:
#Return the first signature
#TODO: We should return all possible signatures. This would requires changes in ToQiskitPass also.
matches = re.findall("[1-9]\. (" + tket_pass.__name__ + '[^\n]+)', _doc)
synopsis_line = matches[0]
else:
synopsis_line = pydoc.splitdoc(_doc)[0]
# To avoid issue caused by callable parentheses:
synopsis_line = re.sub('Callable\[\[[^\[]+\][^\[]+\]', 'Callable', synopsis_line)
match = re.search("\(([^(]+)\)", synopsis_line)
if match is not None:
splitted_args = match.group(1).split(', ')
for arg_str in splitted_args:
if arg_str == '**kwargs':
continue
else:
argument = arg_str.split(': ')
eq_index = argument[1].find('=')
if eq_index > 0:
(_type, _default) = argument[1].split(' = ')
arguments.append((argument[0], _type, _default))
else:
arguments.append(tuple(argument))
return arguments
# This is **temp**. Conversion should be done in a better way
# https://github.com/CQCL/pytket-qiskit/blob/develop/pytket/extensions/qiskit/qiskit_convert.py
from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit
from qiskit.converters import dag_to_circuit, circuit_to_dag
from pytket.circuit import Circuit
from qiskit.dagcircuit import DAGCircuit
def qiskit_dag_to_tk(dag: DAGCircuit):
# Replace any gate that is not known to pyket by its definition
from pytket.extensions.qiskit.qiskit_convert import _known_qiskit_gate
for node in dag.op_nodes():
if not type(node.op) in _known_qiskit_gate:
dag.substitute_node_with_dag(node, circuit_to_dag(node.op.definition))
return qiskit_to_tk(dag_to_circuit(dag))
def tk_to_qiskit_dag(tkcirc: Circuit):
return circuit_to_dag(tk_to_qiskit(tkcirc))
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Replace each sequence of Clifford, Linear Function or Permutation gates by a single block of these types of gate."""
from functools import partial
from qiskit import QuantumCircuit
from qiskit.circuit import Instruction
from qiskit.circuit.barrier import Barrier
from qiskit.circuit.library import LinearFunction, PermutationGate
from qiskit.converters import circuit_to_dag, dag_to_dagdependency, dagdependency_to_dag
from qiskit.dagcircuit.dagcircuit import DAGCircuit
from qiskit.quantum_info.operators import Clifford
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.passes.optimization.collect_and_collapse import (
CollectAndCollapse,
collapse_to_operation,
)
from qiskit.transpiler.passes.utils import control_flow
CLIFFORD_MAX_BLOCK_SIZE = 9
LINEAR_MAX_BLOCK_SIZE = 9
PERMUTATION_MAX_BLOCK_SIZE = 12
clifford_gate_names = [
"x",
"y",
"z",
"h",
"s",
"sdg",
"cx",
"cy",
"cz",
"swap",
"clifford",
"linear_function",
"pauli",
]
linear_gate_names = ["cx", "swap", "linear_function"]
permutation_gate_names = ["swap"]
class Flatten(TransformationPass):
"""Replaces all instructions that contain a circuit with their circuit"""
def __init__(self, node_names):
super().__init__()
self.node_names = node_names
def run(self, dag: DAGCircuit):
for node in dag.named_nodes(*self.node_names):
if (
hasattr(node.op, "params")
and len(node.op.params) > 1
and isinstance(node.op.params[1], QuantumCircuit)
):
dag.substitute_node_with_dag(node, circuit_to_dag(node.op.params[1]))
return dag
_flatten_cliffords = Flatten(("clifford", "Clifford"))
_flatten_linearfunctions = Flatten(("linear_function", "Linear_function"))
_flatten_permutations = Flatten(("permutation", "Permutation"))
from qiskit.dagcircuit.collect_blocks import BlockCollector
class GreedyBlockCollector(BlockCollector):
def __init__(self, dag, max_block_size):
super().__init__(dag)
self.max_block_size = max_block_size
def collect_matching_block(self, filter_fn):
"""Iteratively collects the largest block of input nodes (that is, nodes with
``_in_degree`` equal to 0) that match a given filtering function, limiting the
maximum size of the block.
"""
current_block = []
unprocessed_pending_nodes = self._pending_nodes
self._pending_nodes = []
block_qargs = set()
# Iteratively process unprocessed_pending_nodes:
# - any node that does not match filter_fn is added to pending_nodes
# - any node that match filter_fn is added to the current_block,
# and some of its successors may be moved to unprocessed_pending_nodes.
while unprocessed_pending_nodes:
node = unprocessed_pending_nodes.pop()
if isinstance(node.op, Barrier):
continue
new_qargs = block_qargs.copy()
for q in node.qargs:
new_qargs.add(q)
if filter_fn(node) and len(new_qargs) <= self.max_block_size:
current_block.append(node)
block_qargs = new_qargs
# update the _in_degree of node's successors
for suc in self._direct_succs(node):
self._in_degree[suc] -= 1
if self._in_degree[suc] == 0:
unprocessed_pending_nodes.append(suc)
else:
self._pending_nodes.append(node)
return current_block
class BlockChecker:
def __init__(self, gates, block_class):
self.gates = gates
self.block_class = block_class
self.current_set = set()
def select(self, node):
"""Decides if the node should be added to the block."""
return (
node.op.name in self.gates and getattr(node.op, "condition", None) is None
)
def collapse(self, circuit):
"""Construcs an Gate object for the block."""
self.current_set = set()
return self.block_class(circuit)
class CliffordInstruction(Instruction):
def __init__(self, circuit):
circuit = _flatten_cliffords(circuit)
super().__init__(
name="Clifford",
num_qubits=circuit.num_qubits,
num_clbits=0,
params=[Clifford(circuit), circuit],
)
def construct_permutation_gate(circuit):
circuit = _flatten_permutations(circuit)
return PermutationGate(LinearFunction(circuit).permutation_pattern())
def construct_linearfunction_gate(circuit):
circuit = _flatten_linearfunctions(circuit)
return LinearFunction(circuit)
class RepeatedCollectAndCollapse(CollectAndCollapse):
def __init__(
self,
block_checker: BlockChecker,
do_commutative_analysis=True,
split_blocks=True,
min_block_size=2,
max_block_size=1000,
split_layers=False,
collect_from_back=False,
num_reps=10,
):
collect_function = lambda dag: GreedyBlockCollector(
dag, max_block_size
).collect_all_matching_blocks(
filter_fn=block_checker.select,
split_blocks=split_blocks,
min_block_size=min_block_size,
split_layers=split_layers,
collect_from_back=collect_from_back,
)
collapse_function = partial(
collapse_to_operation, collapse_function=block_checker.collapse
)
super().__init__(
collect_function=collect_function,
collapse_function=collapse_function,
do_commutative_analysis=do_commutative_analysis,
)
self.num_reps = num_reps
@control_flow.trivial_recurse
def run(self, dag):
"""Run the CollectLinearFunctions pass on `dag`.
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
"""
# If the option commutative_analysis is set, construct DAGDependency from the given DAGCircuit.
if self.do_commutative_analysis:
dag = dag_to_dagdependency(dag)
for _ in range(self.num_reps):
# call collect_function to collect blocks from DAG
blocks = self.collect_function(dag)
# call collapse_function to collapse each block in the DAG
self.collapse_function(dag, blocks)
# If the option commutative_analysis is set, construct back DAGCircuit from DAGDependency.
if self.do_commutative_analysis:
dag = dagdependency_to_dag(dag)
return dag
class CollectCliffords(RepeatedCollectAndCollapse):
"""CollectCliffords(do_commutative_analysis: bool = True, min_block_size: int = 2, max_block_size: int = CLIFFORD_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects Clifford blocks as `Instruction` objects and stores the original sub-circuit to compare against it after synthesis.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect Cliffords pass, defaults to 2.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect Cliffords pass, defaults to 9.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=2,
max_block_size=CLIFFORD_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=clifford_gate_names,
block_class=CliffordInstruction,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
class CollectLinearFunctions(RepeatedCollectAndCollapse):
"""CollectLinearFunctions(do_commutative_analysis: bool = True, min_block_size: int = 4, max_block_size: int = LINEAR_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects blocks of `SWAP` and `CX` as `LinearFunction` objects and stores the original sub-circuit to compare against it after synthesis.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect linear functions pass, defaults to 4.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect linear functions pass, defaults to 9.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=4,
max_block_size=LINEAR_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=linear_gate_names,
block_class=construct_linearfunction_gate,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
class CollectPermutations(RepeatedCollectAndCollapse):
"""CollectPermutations(do_commutative_analysis: bool = True, min_block_size: int = 4, max_block_size: int = PERMUTATION_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects blocks of `SWAP` circuits as `Permutations`.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect permutations pass, defaults to 4.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect permutations pass, defaults to 12.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=4,
max_block_size=PERMUTATION_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=permutation_gate_names,
block_class=construct_permutation_gate,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Routing and Layout selection with AI"""
# import torch
# torch.set_num_threads(1)
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler import CouplingMap, TranspilerError
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.layout import Layout
from qiskit_transpiler_service.wrappers import AIRoutingAPI
class AIRouting(TransformationPass):
"""AIRouting(backend_name: str | None = None, coupling_map: list[list[int]] | None = None, optimization_level: int = 2, layout_mode: str = "OPTIMIZE")
The `AIRouting` pass acts both as a layout stage and a routing stage.
:param backend_name: Name of the backend used for doing the transpilation.
:type backend_name: str, optional
:param coupling_map: A list of pairs that represents physical links between qubits.
:type coupling_map: list[list[int]], optional
:param optimization_level: With a range from 1 to 3, determines the computational effort to spend in the process (higher usually gives better results but takes longer), defaults to 2.
:type optimization_level: int
:param layout_mode: Specifies how to handle the layout selection. There are 3 layout modes: keep (respects the layout set by the previous transpiler passes), improve (uses the layout set by the previous transpiler passes as a starting point) and optimize (ignores previous layout selections), defaults to `OPTIMIZE`.
:type layout_mode: str
"""
def __init__(
self,
backend_name=None,
coupling_map=None,
optimization_level: int = 2,
layout_mode: str = "OPTIMIZE",
):
super().__init__()
if backend_name is not None and coupling_map is not None:
raise ValueError(
f"ERROR. Both backend_name and coupling_map were specified as options. Please just use one of them."
)
if backend_name is not None:
self.backend = backend_name
elif coupling_map is not None:
if isinstance(coupling_map, CouplingMap):
self.backend = list(coupling_map.get_edges())
elif isinstance(coupling_map, list):
self.backend = coupling_map
else:
raise ValueError(
f"ERROR. coupling_map should either be a list of int tuples or a Qiskit CouplingMap object."
)
else:
raise ValueError(f"ERROR. Either backend_name OR coupling_map must be set.")
self.optimization_level = optimization_level
if layout_mode is not None and layout_mode.upper() not in [
"KEEP",
"OPTIMIZE",
"IMPROVE",
]:
raise ValueError(
f"ERROR. Unknown ai_layout_mode: {layout_mode}. Valid modes: 'KEEP', 'OPTIMIZE', 'IMPROVE'"
)
self.layout_mode = layout_mode.upper()
self.service = AIRoutingAPI()
def run(self, dag):
"""Run the AIRouting pass on `dag`.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped.
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG, or if the coupling_map=None
"""
if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None:
raise TranspilerError("AIRouting runs on physical circuits only")
# Pass dag to circuit for sending to AIRouting
qc = dag_to_circuit(dag)
# Remove measurements before sending to AIRouting
# TODO: Fix this for mid-circuit measurements
cregs = []
measurements = []
if len(qc.cregs) > 0:
cregs = qc.cregs.copy()
measurements = [g for g in qc if g.operation.name == "measure"]
qc.remove_final_measurements(inplace=True)
routed_qc, init_layout, final_layout = self.service.routing(
qc,
self.backend,
self.optimization_level,
False,
self.layout_mode,
)
# TODO: Improve this
nq = max(init_layout) + 1
routed_qc = QuantumCircuit(nq).compose(
routed_qc, qubits=range(routed_qc.num_qubits)
)
# Restore final measurements if they were removed
if len(measurements) > 0:
meas_qubits = [final_layout[g.qubits[0]._index] for g in measurements]
routed_qc.barrier(meas_qubits)
for creg in cregs:
routed_qc.add_register(creg)
for g, q in zip(measurements, meas_qubits):
routed_qc.append(g.operation, qargs=(q,), cargs=g.clbits)
# Pass routed circuit to dag
# TODO: Improve this
routed_dag = circuit_to_dag(routed_qc)
if routed_qc.num_qubits > dag.num_qubits():
new_dag = copy_dag_metadata(dag, routed_dag)
else:
new_dag = dag.copy_empty_like()
new_dag.compose(routed_dag)
qubits = new_dag.qubits
input_qubit_mapping = {q: i for i, q in enumerate(qubits)}
full_initial_layout = init_layout + sorted(
set(range(len(qubits))) - set(init_layout)
)
full_final_layout = final_layout + list(range(len(final_layout), len(qubits)))
full_final_layout_p = [
full_final_layout[i] for i in np.argsort(full_initial_layout)
]
initial_layout_qiskit = Layout(dict(zip(full_initial_layout, qubits)))
final_layout_qiskit = Layout(dict(zip(full_final_layout_p, qubits)))
self.property_set["layout"] = initial_layout_qiskit
self.property_set["original_qubit_indices"] = input_qubit_mapping
self.property_set["final_layout"] = final_layout_qiskit
return new_dag
def add_measurements(circ, qubits):
circ.add_register(ClassicalRegister(len(qubits)))
circ.barrier()
for i, q in enumerate(qubits):
circ.measure(q, i)
return circ
def copy_dag_metadata(dag, target_dag):
"""Return a copy of self with the same structure but empty.
That structure includes:
* name and other metadata
* global phase
* duration
* all the qubits and clbits, including the registers.
Returns:
DAGCircuit: An empty copy of self.
"""
target_dag.name = dag.name
target_dag._global_phase = dag._global_phase
target_dag.duration = dag.duration
target_dag.unit = dag.unit
target_dag.metadata = dag.metadata
target_dag._key_cache = dag._key_cache
return target_dag
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import os
from urllib.parse import urljoin
from qiskit import QuantumCircuit, qasm2, qasm3
from qiskit.qasm2 import QASM2ExportError
from .base import QiskitTranspilerService
class AIRoutingAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the AIRouting API"""
def __init__(self):
super().__init__("routing")
def routing(
self,
circuit: QuantumCircuit,
coupling_map,
optimization_level: int = 1,
check_result: bool = False,
layout_mode: str = "OPTIMIZE",
):
is_qasm3 = False
try:
qasm = qasm2.dumps(circuit)
except QASM2ExportError:
qasm = qasm3.dumps(circuit)
is_qasm3 = True
json_args = {"qasm": qasm.replace("\n", " "), "coupling_map": coupling_map}
params = {
"check_result": check_result,
"layout_mode": layout_mode,
"optimization_level": optimization_level,
}
routing_resp = self.request_and_wait(
endpoint="routing", body=json_args, params=params
)
if routing_resp.get("success"):
routed_circuit = (
qasm3.loads(routing_resp["qasm"])
if is_qasm3
else QuantumCircuit.from_qasm_str(routing_resp["qasm"])
)
return (
routed_circuit,
routing_resp["layout"]["initial"],
routing_resp["layout"]["final"],
)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
from typing import Union, List
from qiskit import QuantumCircuit
from qiskit.circuit.library import LinearFunction
from qiskit.quantum_info import Clifford
from .base import QiskitTranspilerService
logging.basicConfig()
logging.getLogger(__name__).setLevel(logging.INFO)
class AICliffordAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Clifford AI Synthesis API"""
def __init__(self):
super().__init__("clifford")
def transpile(
self,
circuits: List[Union[QuantumCircuit, Clifford]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={
"clifford_dict": [Clifford(circuit).to_dict() for circuit in circuits],
"qargs": qargs,
},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
class AILinearFunctionAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Linear Function AI Synthesis API"""
def __init__(self):
super().__init__("linear_functions")
def transpile(
self,
circuits: List[Union[QuantumCircuit, LinearFunction]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={
"clifford_dict": [Clifford(circuit).to_dict() for circuit in circuits],
"qargs": qargs,
},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
class AIPermutationAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Permutation AI Synthesis API"""
def __init__(self):
super().__init__("permutations")
def transpile(
self,
patterns: List[List[int]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={"permutation": patterns, "qargs": qargs},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
from typing import Dict, List, Union, Literal
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, qasm2, qasm3
from qiskit.circuit import QuantumCircuit, QuantumRegister, Qubit
from qiskit.qasm2 import QASM2ExportError, QASM2ParseError
from qiskit.transpiler import TranspileLayout
from qiskit.transpiler.layout import Layout
from qiskit_transpiler_service.wrappers import QiskitTranspilerService
# setting backoff logger to error level to avoid too much logging
logging.getLogger("backoff").setLevel(logging.ERROR)
logger = logging.getLogger(__name__)
class TranspileAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Qiskit Transpiler API"""
def __init__(self):
super().__init__()
def transpile(
self,
circuits: Union[
Union[List[str], str], Union[List[QuantumCircuit], QuantumCircuit]
],
optimization_level: int = 1,
backend: Union[str, None] = None,
coupling_map: Union[List[List[int]], None] = None,
ai: Literal["true", "false", "auto"] = "true",
qiskit_transpile_options: Dict = None,
ai_layout_mode: str = None,
):
circuits = circuits if isinstance(circuits, list) else [circuits]
qasm_circuits = [_input_to_qasm(circ) for circ in circuits]
json_args = {
"qasm_circuits": qasm_circuits,
}
if qiskit_transpile_options is not None:
json_args["qiskit_transpile_options"] = qiskit_transpile_options
if coupling_map is not None:
json_args["backend_coupling_map"] = coupling_map
params = {
"backend": backend,
"optimization_level": optimization_level,
"ai": ai,
}
if ai_layout_mode is not None:
params["ai_layout_mode"] = ai_layout_mode
transpile_resp = self.request_and_wait(
endpoint="transpile", body=json_args, params=params
)
logger.debug(f"transpile_resp={transpile_resp}")
transpiled_circuits = []
for res, orig_circ in zip(transpile_resp, circuits):
try:
transpiled_circuits.append(_get_circuit_from_result(res, orig_circ))
except Exception as ex:
logger.error("Error transforming the result to a QuantumCircuit object")
raise
return (
transpiled_circuits
if len(transpiled_circuits) > 1
else transpiled_circuits[0]
)
def benchmark(
self,
circuits: Union[
Union[List[str], str], Union[List[QuantumCircuit], QuantumCircuit]
],
backend: str,
optimization_level: int = 1,
qiskit_transpile_options: Dict = None,
):
raise Exception("Not implemented")
def _input_to_qasm(input_circ: Union[QuantumCircuit, str]):
if isinstance(input_circ, QuantumCircuit):
try:
qasm = qasm2.dumps(input_circ).replace("\n", " ")
except QASM2ExportError:
qasm = qasm3.dumps(input_circ).replace("\n", " ")
elif isinstance(input_circ, str):
qasm = input_circ.replace("\n", " ")
else:
raise TypeError("Input circuits must be QuantumCircuit or qasm string.")
return qasm
def _get_circuit_from_result(transpile_resp, orig_circuit):
transpiled_circuit = _get_circuit_from_qasm(transpile_resp["qasm"])
init_layout = transpile_resp["layout"]["initial"]
final_layout = transpile_resp["layout"]["final"]
orig_circuit = (
_get_circuit_from_qasm(orig_circuit)
if isinstance(orig_circuit, str)
else orig_circuit
)
transpiled_circuit = QuantumCircuit(len(init_layout)).compose(transpiled_circuit)
transpiled_circuit._layout = _create_transpile_layout(
init_layout, final_layout, transpiled_circuit, orig_circuit
)
return transpiled_circuit
def _create_initial_layout(initial, n_used_qubits):
"""Create initial layout using the initial index layout and the number of active qubits."""
total_qubits = len(initial)
q_total = n_used_qubits
a_total = total_qubits - q_total
initial_layout = Layout()
for q in range(q_total):
initial_layout.add(initial[q], Qubit(QuantumRegister(q_total, "q"), q))
for a in range(q_total, total_qubits):
initial_layout.add(
initial[a], Qubit(QuantumRegister(a_total, "ancilla"), a - q_total)
)
return initial_layout
def _create_input_qubit_mapping(qubits_used, total_qubits):
"""Create input qubit mapping with the number of active qubits and the total number of qubits."""
input_qubit_mapping = {
Qubit(QuantumRegister(qubits_used, "q"), q): q for q in range(qubits_used)
}
input_ancilla_mapping = {
Qubit(
QuantumRegister(total_qubits - qubits_used, "ancilla"), q - qubits_used
): q
for q in range(qubits_used, total_qubits)
}
input_qubit_mapping.update(input_ancilla_mapping)
return input_qubit_mapping
def _create_final_layout(initial, final, circuit):
"""Create final layout with the initial and final index layout and the circuit."""
final_layout = Layout()
q_total = len(initial)
q_reg = QuantumRegister(q_total, "q")
for i, j in zip(final, initial):
q_index = circuit.find_bit(Qubit(q_reg, j)).index
qubit = circuit.qubits[q_index]
final_layout.add(i, qubit)
return final_layout
def _create_transpile_layout(initial, final, circuit, orig_circuit):
"""Build the full transpile layout."""
n_used_qubits = orig_circuit.num_qubits
return TranspileLayout(
initial_layout=_create_initial_layout(
initial=initial, n_used_qubits=n_used_qubits
), # final=final),
input_qubit_mapping=_create_input_qubit_mapping(
qubits_used=n_used_qubits, total_qubits=len(initial)
),
final_layout=_create_final_layout(
initial=initial, final=final, circuit=circuit
),
_input_qubit_count=n_used_qubits,
_output_qubit_list=circuit.qubits,
)
def _get_circuit_from_qasm(qasm_string):
try:
return qasm2.loads(
qasm_string,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
)
except QASM2ParseError:
return qasm3.loads(qasm_string)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing Transpiler Service"""
import numpy as np
import pytest
from qiskit import QuantumCircuit, qasm2, qasm3
from qiskit.circuit.library import IQP, EfficientSU2, QuantumVolume
from qiskit.circuit.random import random_circuit
from qiskit.compiler import transpile
from qiskit.quantum_info import SparsePauliOp, random_hermitian
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_transpiler_service.wrappers import _get_circuit_from_result
@pytest.mark.parametrize(
"optimization_level", [1, 2, 3], ids=["opt_level_1", "opt_level_2", "opt_level_3"]
)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize(
"qiskit_transpile_options",
[None, {"seed_transpiler": 0}],
ids=["no opt", "one option"],
)
def test_rand_circ_backend_routing(optimization_level, ai, qiskit_transpile_options):
backend_name = "ibm_brisbane"
random_circ = random_circuit(5, depth=3, seed=42)
cloud_transpiler_service = TranspilerService(
backend_name=backend_name,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(random_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
@pytest.mark.parametrize(
"optimization_level", [1, 2, 3], ids=["opt_level_1", "opt_level_2", "opt_level_3"]
)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize(
"qiskit_transpile_options",
[None, {"seed_transpiler": 0}],
ids=["no opt", "one option"],
)
def test_qv_backend_routing(optimization_level, ai, qiskit_transpile_options):
backend_name = "ibm_brisbane"
qv_circ = QuantumVolume(27, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name=backend_name,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(qv_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
@pytest.mark.parametrize(
"coupling_map",
[
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]],
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]],
],
)
@pytest.mark.parametrize("optimization_level", [1, 2, 3])
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
@pytest.mark.parametrize("qiskit_transpile_options", [None, {"seed_transpiler": 0}])
def test_rand_circ_cmap_routing(
coupling_map, optimization_level, ai, qiskit_transpile_options
):
random_circ = random_circuit(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
coupling_map=coupling_map,
ai=ai,
optimization_level=optimization_level,
qiskit_transpile_options=qiskit_transpile_options,
)
transpiled_circuit = cloud_transpiler_service.run(random_circ)
assert isinstance(transpiled_circuit, QuantumCircuit)
def test_qv_circ_several_circuits_routing():
qv_circ = QuantumVolume(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai="true",
optimization_level=1,
)
transpiled_circuit = cloud_transpiler_service.run([qv_circ] * 2)
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
transpiled_circuit = cloud_transpiler_service.run([qasm2.dumps(qv_circ)] * 2)
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
transpiled_circuit = cloud_transpiler_service.run([qasm2.dumps(qv_circ), qv_circ])
for circ in transpiled_circuit:
assert isinstance(circ, QuantumCircuit)
def test_qv_circ_wrong_input_routing():
qv_circ = QuantumVolume(5, depth=3, seed=42).decompose(reps=3)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai="true",
optimization_level=1,
)
circ_dict = {"a": qv_circ}
with pytest.raises(TypeError):
cloud_transpiler_service.run(circ_dict)
@pytest.mark.parametrize("ai", ["false", "true"], ids=["no_ai", "ai"])
def test_transpile_layout_reconstruction(ai):
n_qubits = 27
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
observable = SparsePauliOp("Z" * n_qubits)
cloud_transpiler_service = TranspilerService(
backend_name="ibm_brisbane",
ai=ai,
optimization_level=1,
)
transpiled_circuit = cloud_transpiler_service.run(circuit)
# This fails if initial layout is not correct
try:
observable.apply_layout(transpiled_circuit.layout)
except Exception:
pytest.fail(
"This should not fail. Probably something wrong with the reconstructed layout."
)
def test_transpile_non_valid_backend():
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
non_valid_backend_name = "ibm_torin"
transpiler_service = TranspilerService(
backend_name=non_valid_backend_name,
ai="false",
optimization_level=3,
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert (
str(e)
== f'"User doesn\'t have access to the specified backend: {non_valid_backend_name}"'
)
def test_transpile_exceed_circuit_size():
circuit = EfficientSU2(100, entanglement="circular", reps=50).decompose()
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert str(e) == "'Circuit has more gates than the allowed maximum of 5000.'"
def test_transpile_malformed_body():
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
qiskit_transpile_options={"failing_option": 0},
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert (
str(e)
== "\"transpile() got an unexpected keyword argument 'failing_option'\""
)
def test_transpile_failing_task():
open_qasm_circuit = 'OPENQASM 2.0;\ninclude "qelib1.inc";\ngate dcx q0,q1 { cx q0,q1; cx q1,q0; }\nqreg q[3];\ncz q[0],q[2];\nsdg q[1];\ndcx q[2],q[1];\nu3(3.890139082217223,3.447697582994976,1.1583481971959322) q[0];\ncrx(2.3585459177723522) q[1],q[0];\ny q[2];'
circuit = QuantumCircuit.from_qasm_str(open_qasm_circuit)
transpiler_service = TranspilerService(
backend_name="ibm_kyoto",
ai="false",
optimization_level=3,
coupling_map=[[1, 2], [2, 1]],
qiskit_transpile_options={
"basis_gates": ["u1", "u2", "u3", "cx"],
"seed_transpiler": 0,
},
)
try:
transpiler_service.run(circuit)
pytest.fail("Error expected")
except Exception as e:
assert "The background task" in str(e)
assert "FAILED" in str(e)
def compare_layouts(plugin_circ, non_ai_circ):
assert (
plugin_circ.layout.initial_layout == non_ai_circ.layout.initial_layout
), "initial_layouts differs"
assert (
plugin_circ.layout.initial_index_layout()
== non_ai_circ.layout.initial_index_layout()
), "initial_index_layout differs"
assert (
plugin_circ.layout.input_qubit_mapping == non_ai_circ.layout.input_qubit_mapping
), "input_qubit_mapping differs"
assert (
plugin_circ.layout._input_qubit_count == non_ai_circ.layout._input_qubit_count
), "_input_qubit_count differs"
assert (
plugin_circ.layout._output_qubit_list == non_ai_circ.layout._output_qubit_list
), "_output_qubit_list differs"
# Sometimes qiskit transpilation does not add final_layout
if non_ai_circ.layout.final_layout:
assert (
plugin_circ.layout.final_layout == non_ai_circ.layout.final_layout
), "final_layout differs"
assert (
plugin_circ.layout.final_index_layout()
== non_ai_circ.layout.final_index_layout()
), "final_index_layout differs"
def get_circuit_as_in_service(circuit):
return {
"qasm": qasm3.dumps(circuit),
"layout": {
"initial": circuit.layout.initial_index_layout(),
"final": circuit.layout.final_index_layout(False),
},
}
def transpile_and_check_layout(cmap, circuit):
non_ai_circ = transpile(
circuits=circuit,
coupling_map=cmap,
optimization_level=1,
)
service_resp = get_circuit_as_in_service(non_ai_circ)
plugin_circ = _get_circuit_from_result(service_resp, circuit)
compare_layouts(plugin_circ, non_ai_circ)
def test_layout_construction_no_service(backend, cmap_backend):
for n_qubits in [5, 10, 15, 20, 27]:
circuit = random_circuit(n_qubits, 4, measure=True)
transpile_and_check_layout(cmap_backend[backend], circuit)
for n_qubits in [5, 10, 15, 20, 27]:
circuit = EfficientSU2(n_qubits, entanglement="circular", reps=1).decompose()
transpile_and_check_layout(cmap_backend[backend], circuit)
for n_qubits in [5, 10, 15, 20, 27]:
circuit = QuantumCircuit(n_qubits)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.h(4)
transpile_and_check_layout(cmap_backend[backend], circuit)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
import pytest
from qiskit import QuantumCircuit
from qiskit.circuit.library import QuantumVolume
from qiskit.quantum_info import random_clifford
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def create_random_circuit(total_n_ubits, cliffords_n_qubits, clifford_num):
circuit = QuantumCircuit(total_n_ubits)
nq = cliffords_n_qubits
for c in range(clifford_num):
qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False)
circuit.compose(
random_clifford(nq, seed=42).to_circuit(), qubits=qs.tolist(), inplace=True
)
for q in qs:
circuit.t(q)
return circuit
def create_linear_circuit(n_qubits, gates):
circuit = QuantumCircuit(n_qubits)
for q in range(n_qubits - 1):
if gates == "cx":
circuit.cx(q, q + 1)
elif gates == "swap":
circuit.swap(q, q + 1)
elif gates == "cz":
circuit.cz(q, q + 1)
elif gates == "rzz":
circuit.rzz(1.23, q, q + 1)
return circuit
@pytest.fixture(scope="module")
def random_circuit_transpiled(backend, cmap_backend):
circuit = create_random_circuit(27, 4, 2)
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=cmap_backend[backend]
)
return qiskit_lvl3_transpiler.run(circuit)
@pytest.fixture(scope="module")
def qv_circ():
return QuantumVolume(10, depth=3, seed=42).decompose(reps=1)
@pytest.fixture(scope="module", params=[3, 10, 30])
def cnot_circ(request):
return create_linear_circuit(request.param, "cx")
@pytest.fixture(scope="module", params=[3, 10, 30])
def swap_circ(request):
return create_linear_circuit(request.param, "swap")
@pytest.fixture(scope="module", params=[3, 10, 30])
def cz_circ(request):
return create_linear_circuit(request.param, "cz")
@pytest.fixture(scope="module", params=[3, 10, 30])
def rzz_circ(request):
return create_linear_circuit(request.param, "rzz")
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing clifford_ai"""
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectCliffords
from qiskit_transpiler_service.ai.synthesis import AICliffordSynthesis
def test_clifford_function(random_circuit_transpiled, backend):
ai_optimize_lf = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_clifford_wrong_backend(random_circuit_transpiled, caplog):
ai_optimize_lf = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name="wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing linear_function_collection"""
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectCliffords
def test_clifford_collection_pass(random_circuit_transpiled):
collect = PassManager(
[
CollectCliffords(),
]
)
collected_circuit = collect.run(random_circuit_transpiled)
assert isinstance(collected_circuit, QuantumCircuit)
def test_clifford_collection_pass_collect(cz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=1, max_block_size=5),
]
)
collected_circuit = collect.run(cz_circ)
assert isinstance(collected_circuit, QuantumCircuit)
assert any(g.operation.name.lower() == "clifford" for g in collected_circuit)
def test_clifford_collection_pass_no_collect(rzz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(rzz_circ)
assert all(g.operation.name.lower() != "clifford" for g in collected_circuit)
def test_clifford_collection_max_block_size(cz_circ):
collect = PassManager(
[
CollectCliffords(max_block_size=7),
]
)
collected_circuit = collect.run(cz_circ)
assert all(len(g.qubits) <= 7 for g in collected_circuit)
def test_clifford_collection_min_block_size(cz_circ):
collect = PassManager(
[
CollectCliffords(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(cz_circ)
assert all(
len(g.qubits) >= 7 or g.operation.name.lower() != "clifford"
for g in collected_circuit
)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing linear_function_ai"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
from qiskit_transpiler_service.ai.synthesis import AILinearFunctionSynthesis
def test_linear_function_pass(random_circuit_transpiled, backend, caplog):
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_function_wrong_backend(caplog):
circuit = QuantumCircuit(10)
for i in range(8):
circuit.cx(i, i + 1)
for i in range(8):
circuit.h(i)
for i in range(8):
circuit.cx(i, i + 1)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(backend_name="a_wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(circuit)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_always_replace(backend, caplog):
orig_qc = QuantumCircuit(3)
orig_qc.cx(0, 1)
orig_qc.cx(1, 2)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(),
AILinearFunctionSynthesis(
backend_name=backend, replace_only_if_better=False
),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert "Keeping the original circuit" not in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_linear_function_only_replace_if_better(backend, caplog):
orig_qc = QuantumCircuit(3)
orig_qc.cx(0, 1)
orig_qc.cx(1, 2)
ai_optimize_lf = PassManager(
[
CollectLinearFunctions(min_block_size=2),
AILinearFunctionSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert ai_optimized_circuit == orig_qc
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing linear_function_collection"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectLinearFunctions
def test_lf_collection_pass(random_circuit_transpiled):
collect = PassManager(
[
CollectLinearFunctions(),
]
)
collected_circuit = collect.run(random_circuit_transpiled)
assert isinstance(collected_circuit, QuantumCircuit)
def test_lf_collection_pass_collect(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=1, max_block_size=5),
]
)
collected_circuit = collect.run(cnot_circ)
assert isinstance(collected_circuit, QuantumCircuit)
assert any(g.operation.name.lower() == "linear_function" for g in collected_circuit)
def test_lf_collection_pass_no_collect(rzz_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(rzz_circ)
assert all(g.operation.name.lower() != "linear_function" for g in collected_circuit)
def test_lf_collection_max_block_size(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(max_block_size=7),
]
)
collected_circuit = collect.run(cnot_circ)
assert all(len(g.qubits) <= 7 for g in collected_circuit)
def test_lf_collection_min_block_size(cnot_circ):
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
collected_circuit = collect.run(cnot_circ)
assert all(
len(g.qubits) >= 7 or g.operation.name.lower() != "linear_function"
for g in collected_circuit
)
@pytest.mark.timeout(10)
def test_collection_with_barrier(cnot_circ):
cnot_circ.measure_all()
collect = PassManager(
[
CollectLinearFunctions(min_block_size=7, max_block_size=12),
]
)
# Without proper handling this test timeouts (actually the collect runs forever)
collect.run(cnot_circ)
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# 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.
"""Unit-testing permutation_ai"""
import pytest
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.ai.collection import CollectPermutations
from qiskit_transpiler_service.ai.synthesis import AIPermutationSynthesis
@pytest.fixture
def permutations_circuit(backend, cmap_backend):
coupling_map = cmap_backend[backend]
cmap = list(coupling_map.get_edges())
orig_qc = QuantumCircuit(27)
for i, j in cmap:
orig_qc.h(i)
orig_qc.cx(i, j)
for i, j in cmap:
orig_qc.swap(i, j)
for i, j in cmap:
orig_qc.h(i)
orig_qc.cx(i, j)
for i, j in cmap[:4]:
orig_qc.swap(i, j)
for i, j in cmap:
orig_qc.cx(i, j)
return orig_qc
def test_permutation_collector(permutations_circuit, backend, cmap_backend):
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=1, coupling_map=cmap_backend[backend]
)
permutations_circuit = qiskit_lvl3_transpiler.run(permutations_circuit)
pm = PassManager(
[
CollectPermutations(max_block_size=27),
]
)
perm_only_circ = pm.run(permutations_circuit)
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(perm_only_circ)
perm_nodes = dag.named_nodes("permutation", "Permutation")
assert len(perm_nodes) == 2
assert perm_nodes[0].op.num_qubits == 27
assert perm_nodes[1].op.num_qubits == 4
assert not dag.named_nodes("linear_function", "Linear_function")
assert not dag.named_nodes("clifford", "Clifford")
def test_permutation_pass(permutations_circuit, backend, cmap_backend, caplog):
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=1, coupling_map=cmap_backend[backend]
)
permutations_circuit = qiskit_lvl3_transpiler.run(permutations_circuit)
ai_optimize_lf = PassManager(
[
CollectPermutations(max_block_size=27),
AIPermutationSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(permutations_circuit)
assert "Using the synthesized circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_permutation_wrong_backend(caplog):
orig_qc = QuantumCircuit(3)
orig_qc.swap(0, 1)
orig_qc.swap(1, 2)
ai_optimize_lf = PassManager(
[
CollectPermutations(min_block_size=2, max_block_size=27),
AIPermutationSynthesis(backend_name="a_wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(orig_qc)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.