repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
import numpy as np
import rustworkx as rx
import matplotlib.pyplot as plt
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit import QuantumCircuit
from qiskit_experiments.framework import ParallelExperiment, BatchExperiment, ExperimentData
from qiskit_experiments.library import StandardRB
from qiskit_device_benchmarking.bench_code.prb import PurityRB
from qiskit_device_benchmarking.utilities import graph_utils as gu
#enter your device hub/group/project here
#and device
hgp = 'ibm-q/open/main'
service = QiskitRuntimeService()
backend_real=service.backend('ibm_kyiv',instance=hgp)
nq = backend_real.configuration().n_qubits
coupling_map = backend_real.configuration().coupling_map
#build a set of gates
G = gu.build_sys_graph(nq, coupling_map)
#get all length 2 paths in the device
paths = rx.all_pairs_all_simple_paths(G,2,2)
#flatten those paths into a list from the rustwork x iterator
paths = gu.paths_flatten(paths)
#remove permutations
paths = gu.remove_permutations(paths)
#convert to the coupling map of the device
paths = gu.path_to_edges(paths,coupling_map)
#make into separate sets
sep_sets = gu.get_separated_sets(G, paths, min_sep=2)
#rb of all the edges in parallel
rb_batch_list = []
prb_batch_list = []
#RB options
lengths = [1, 10, 20, 50, 100, 150, 250, 400]
num_samples = 5
#also do purity (optional)
#use less samples because we need 9 circuits per length per sample
#also less lengths because they decay faster
do_purity = True
lengths_pur = [1, 5, 10, 25, 50, 100, 175, 250]
num_samples_pur = 3
if 'ecr' in backend_real.configuration().basis_gates:
twoq_gate='ecr'
elif 'cz' in backend_real.configuration().basis_gates:
twoq_gate='cz'
#go through for each of the edge sets
for ii in range(len(sep_sets)):
rb_list = []
prb_list = []
for two_i, two_set in enumerate(sep_sets[ii]):
exp1 = StandardRB(two_set, lengths, num_samples=num_samples)
rb_list.append(exp1)
rb_exp_p = ParallelExperiment(rb_list, backend = backend_real)
rb_batch_list.append(rb_exp_p)
if do_purity:
for two_i, two_set in enumerate(sep_sets[ii]):
exp1 = PurityRB(two_set, lengths_pur, num_samples=num_samples_pur)
prb_list.append(exp1)
rb_exp_p = ParallelExperiment(prb_list, backend = backend_real)
prb_batch_list.append(rb_exp_p)
#batch all of them together
#put the purity ones last
full_rb_exp = BatchExperiment(rb_batch_list + prb_batch_list, backend = backend_real)
full_rb_exp.set_experiment_options(max_circuits=100)
full_rb_exp.set_run_options(shots=200)
#run
rb_data = full_rb_exp.run()
print(rb_data.job_ids)
#Run this cell if you want to reload data from a previous job(s)
if (0):
# List of job IDs for the experiment
job_ids= ['']
rb_data = ExperimentData(experiment = full_rb_exp)
rb_data.add_jobs([service.job(job_id) for job_id in job_ids])
full_rb_exp.analysis.run(rb_data, replace_results=True)
# Block execution of subsequent code until analysis is complete
rb_data.block_for_results()
rb_data.analysis_status()
#Plot the data
#Input the edge to plot here
fig_edge = [26,16]
fig_id = []
for i in range(len(sep_sets)):
for j in range(len(sep_sets[i])):
if fig_edge==sep_sets[i][j]:
fig_id = [i,j]
rb_data.child_data()[fig_id[0]].child_data()[fig_id[1]].figure(0)
#Plot the PURITY data
#Input the edge to plot here
if not do_purity:
print("No Purity data was run!")
fig_edge = [26,16]
fig_id = []
for i in range(len(sep_sets)):
for j in range(len(sep_sets[i])):
if fig_edge==sep_sets[i][j]:
fig_id = [i,j]
rb_data.child_data()[len(sep_sets)+fig_id[0]].child_data()[fig_id[1]].figure(0)
#Load the RB Error into a list
set_list = []
rb_err = []
pur_rb_err = []
gate_err = []
back_prop = backend_real.properties()
for i in range(len(sep_sets)):
for j in range(len(sep_sets[i])):
set_list.append(sep_sets[i][j])
rb_err.append(rb_data.child_data()[i].child_data()[j].analysis_results()[2].value.nominal_value/1.5)
if do_purity:
#sometimes the purity doesn't fit
if len(rb_data.child_data()[len(sep_sets)+i].child_data()[j].analysis_results())==1:
pur_rb_err.append(1.)
else:
pur_rb_err.append(rb_data.child_data()[len(sep_sets)+i].child_data()[j].analysis_results()[2].value.nominal_value/1.5)
gate_err.append(back_prop.gate_error(twoq_gate,set_list[-1]))
if do_purity:
print('Q%s, rb error (purity) %.2e (%.2e)/ reported err %.2e'%(sep_sets[i][j],
rb_err[-1],
pur_rb_err[-1], gate_err[-1]))
else:
print('Q%s, rb error %.2e (%.2e)/ reported err %.2e'%(sep_sets[i][j],
rb_err[-1],
gate_err[-1]))
#plot the data ordered by Bell state fidelity (need to run the cell above first)
plt.figure(dpi=150,figsize=[15,5])
argind = np.argsort(rb_err)
plt.semilogy(range(len(set_list)),np.array(gate_err)[argind],label='Gate Err (Reported)', marker='.', color='grey')
plt.semilogy(range(len(set_list)),np.array(rb_err)[argind],label='RB Err (Measured)', marker='.')
if do_purity:
plt.semilogy(range(len(set_list)),np.array(pur_rb_err)[argind],label='Pur RB Err (Measured)', marker='x')
plt.xticks(range(len(set_list)),np.array(set_list)[argind],rotation=90,fontsize=5);
plt.ylim([1e-3,1])
plt.grid(True)
plt.legend()
plt.title('Device Gate Errors for %s, job %s'%(backend_real.name, rb_data.job_ids[0]))
import datetime
from IPython.display import HTML, display
def qiskit_copyright(line="", cell=None):
"""IBM copyright"""
now = datetime.datetime.now()
html = "<div style='width: 100%; background-color:#d5d9e0;"
html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>"
html += "<p>© Copyright IBM 2017, %s.</p>" % now.year
html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>"
html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> "
html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0."
html += "<p>Any modifications or derivative works of this code must retain this<br>"
html += "copyright notice, and modified files need to carry a notice indicating<br>"
html += "that they have been altered from the originals.</p>"
html += "</div>"
return display(HTML(html))
qiskit_copyright()
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
from qiskit_experiments.library.randomized_benchmarking import LayerFidelity
import numpy as np
import rustworkx as rx
import matplotlib.pyplot as plt
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
# specify backend and two-qubit gate to be layered
backend = service.backend("ibm_kyoto")
twoq_gate = "ecr"
print(f"Device {backend.name} Loaded with {backend.num_qubits} qubits")
print(f"Two Qubit Gate: {twoq_gate}")
num_qubits_in_chain = 100
coupling_map = backend.target.build_coupling_map(twoq_gate)
G = coupling_map.graph
def to_edges(path):
edges = []
prev_node = None
for node in path:
if prev_node is not None:
if G.has_edge(prev_node, node):
edges.append((prev_node, node))
else:
edges.append((node, prev_node))
prev_node = node
return edges
def path_fidelity(path, correct_by_duration: bool = True, readout_scale: float = None):
"""Compute an estimate of the total fidelity of 2-qubit gates on a path.
If `correct_by_duration` is true, each gate fidelity is worsen by
scale = max_duration / duration, i.e. gate_fidelity^scale.
If `readout_scale` > 0 is supplied, readout_fidelity^readout_scale
for each qubit on the path is multiplied to the total fielity.
The path is given in node indices form, e.g. [0, 1, 2].
An external function `to_edges` is used to obtain edge list, e.g. [(0, 1), (1, 2)]."""
path_edges = to_edges(path)
max_duration = max(backend.target[twoq_gate][qs].duration for qs in path_edges)
def gate_fidelity(qpair):
duration = backend.target[twoq_gate][qpair].duration
scale = max_duration / duration if correct_by_duration else 1.0
# 1.25 = (d+1)/d) with d = 4
return max(0.25, 1 - (1.25 * backend.target[twoq_gate][qpair].error)) ** scale
def readout_fidelity(qubit):
return max(0.25, 1 - backend.target["measure"][(qubit,)].error)
total_fidelity = np.prod([gate_fidelity(qs) for qs in path_edges])
if readout_scale:
total_fidelity *= np.prod([readout_fidelity(q) for q in path]) ** readout_scale
return total_fidelity
def flatten(paths, cutoff=None): # cutoff not to make run time too large
return [
path
for s, s_paths in paths.items()
for t, st_paths in s_paths.items()
for path in st_paths[:cutoff]
if s < t
]
paths = rx.all_pairs_all_simple_paths(
G.to_undirected(multigraph=False),
min_depth=num_qubits_in_chain,
cutoff=num_qubits_in_chain,
)
paths = flatten(paths, cutoff=400)
if not paths:
raise Exception(
f"No qubit chain with length={num_qubits_in_chain} exists in {backend.name}. Try smaller num_qubits_in_chain."
)
print(f"Selecting the best from {len(paths)} candidate paths (will take a few minutes)")
best_qubit_chain = max(paths, key=path_fidelity)
# from functools import partial
# best_qubit_chain = max(paths, key=partial(path_fidelity, correct_by_duration=True, readout_scale=1.0))
assert len(best_qubit_chain) == num_qubits_in_chain
print(f"Predicted LF from reported 2q-gate EPGs: {path_fidelity(best_qubit_chain)}")
np.array(best_qubit_chain)
# decompose the chain into two disjoint layers
all_pairs = to_edges(best_qubit_chain)
two_disjoint_layers = [all_pairs[0::2], all_pairs[1::2]]
two_disjoint_layers
%%time
lfexp = LayerFidelity(
physical_qubits=best_qubit_chain,
two_qubit_layers=two_disjoint_layers,
lengths=[2, 4, 8, 16, 30, 50, 70, 100, 150, 200, 300, 500],
backend=backend,
num_samples=12,
seed=42,
# two_qubit_gate="ecr",
# one_qubit_basis_gates=["rz", "sx", "x"],
)
# set maximum number of circuits per job to avoid errors due to too large payload
lfexp.experiment_options.max_circuits = 144
lfexp.experiment_options
print(f"Two Qubit Gate: {lfexp.experiment_options.two_qubit_gate}")
print(f"One Qubit Gate Set: {lfexp.experiment_options.one_qubit_basis_gates}")
%%time
# look at one of the first three 2Q direct RB circuits quickly
circ_iter = lfexp.circuits_generator()
first_three_circuits = list(next(circ_iter) for _ in range(3))
first_three_circuits[1].draw(output="mpl", style="clifford", idle_wires=False, fold=-1)
%%time
# generate all circuits to run
circuits = lfexp.circuits()
print(f"{len(circuits)} circuits are generated.")
%%time
# number of shots per job
nshots = 400
# Run the LF experiment (generate circuits and submit the job)
exp_data = lfexp.run(shots=nshots)
# exp_data.auto_save = True
print(f"Run experiment: ID={exp_data.experiment_id} with jobs {exp_data.job_ids}]")
%%time
exp_data.block_for_results()
# Get the result data as a pandas DataFrame
df = exp_data.analysis_results(dataframe=True)
# LF and LF of each disjoing set
df[(df.name == "LF") | (df.name == "EPLG") | (df.name == "SingleLF")]
# 1Q/2Q process fidelities
df[(df.name == "ProcessFidelity")].head()
# Plot 1Q/2Q simultaneous direct RB curves
for i in range(0, 5):
display(exp_data.figure(i))
pfdf = df[(df.name == "ProcessFidelity")]
pfdf[pfdf.value < 0.8]
# find bad quality analysis results
pfdf[pfdf.quality == "bad"]
# Display "bad" 1Q/2Q direct RB plots
# for qubits in pfdf[pfdf.quality=="bad"].qubits:
# figname = "DirectRB_Q" + "_Q".join(map(str, qubits))
# display(exp_data.figure(figname))
# fill Process Fidelity values with zeros
pfdf = pfdf.fillna({"value": 0})
# Compute LF by chain length assuming the first layer is full with 2q-gates
lf_sets, lf_qubits = two_disjoint_layers, best_qubit_chain
full_layer = [None] * (len(lf_sets[0]) + len(lf_sets[1]))
full_layer[::2] = lf_sets[0]
full_layer[1::2] = lf_sets[1]
full_layer = [(lf_qubits[0],)] + full_layer + [(lf_qubits[-1],)]
len(full_layer)
assert len(full_layer) == len(lf_qubits) + 1
pfs = [pfdf.loc[pfdf[pfdf.qubits == qubits].index[0], "value"] for qubits in full_layer]
pfs = list(map(lambda x: x.n if x != 0 else 0, pfs))
pfs[0] = pfs[0] ** 2
pfs[-1] = pfs[-1] ** 2
np.array(pfs)
len(pfs)
job = service.job(exp_data.job_ids[0])
JOB_DATE = job.creation_date
# Approximate 1Q RB fidelities at both ends by the square root of 2Q RB fidelity at both ends.
# For example, if we have [(0, 1), (1, 2), (2, 3), (3, 4)] 2Q RB fidelities and if we want to compute a layer fidelity for [1, 2, 3],
# we approximate the 1Q filedities for (1,) and (3,) by the square root of 2Q fidelities of (0, 1) and (3, 4).
chain_lens = list(range(4, len(pfs), 2))
chain_fids = []
for length in chain_lens:
w = length + 1 # window size
fid_w = max(
np.sqrt(pfs[s]) * np.prod(pfs[s + 1 : s + w - 1]) * np.sqrt(pfs[s + w - 1])
for s in range(len(pfs) - w + 1)
)
chain_fids.append(fid_w)
# Plot LF by chain length
plt.title(f"Backend: {backend.name}, {JOB_DATE.strftime('%Y/%m/%d %H:%M')}")
plt.plot(
chain_lens,
chain_fids,
marker="o",
linestyle="-",
)
plt.xlim(0, chain_lens[-1] * 1.05)
plt.ylim(0.95 * min(chain_fids), 1)
plt.ylabel("Layer Fidelity")
plt.xlabel("Chain Length")
plt.grid()
plt.show()
# Plot EPLG by chain length
num_2q_gates = [length - 1 for length in chain_lens]
chain_eplgs = [
1 - (fid ** (1 / num_2q)) for num_2q, fid in zip(num_2q_gates, chain_fids)
]
plt.title(f"Backend: {backend.name}, {JOB_DATE.strftime('%Y/%m/%d %H:%M')}")
plt.plot(
chain_lens,
chain_eplgs,
marker="o",
linestyle="-",
)
plt.xlim(0, chain_lens[-1] * 1.05)
plt.ylabel("Error per Layered Gates")
plt.xlabel("Chain Length")
plt.grid()
plt.show()
import datetime
from IPython.display import HTML, display
def qiskit_copyright(line="", cell=None):
"""IBM copyright"""
now = datetime.datetime.now()
html = "<div style='width: 100%; background-color:#d5d9e0;"
html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>"
html += "<p>© Copyright IBM 2017, %s.</p>" % now.year
html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>"
html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> "
html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0."
html += "<p>Any modifications or derivative works of this code must retain this<br>"
html += "copyright notice, and modified files need to carry a notice indicating<br>"
html += "that they have been altered from the originals.</p>"
html += "</div>"
return display(HTML(html))
qiskit_copyright()
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Mirror RB analysis class.
"""
from typing import List, Union
import numpy as np
from uncertainties import unumpy as unp
from scipy.spatial.distance import hamming
import qiskit_experiments.curve_analysis as curve
from qiskit_experiments.framework import AnalysisResultData, ExperimentData
from qiskit_experiments.data_processing import DataProcessor
from qiskit_experiments.data_processing.data_action import DataAction
from qiskit_experiments.library.randomized_benchmarking.rb_analysis import RBAnalysis
class MirrorRBAnalysis(RBAnalysis):
r"""A class to analyze mirror randomized benchmarking experiment.
# section: overview
This analysis takes a series for Mirror RB curve fitting.
From the fit :math:`\alpha` value this analysis estimates the mean entanglement infidelity (EI)
and the error per Clifford (EPC), also known as the average gate infidelity (AGI).
The EPC (AGI) estimate is obtained using the equation
.. math::
EPC = \frac{2^n - 1}{2^n}\left(1 - \alpha\right)
where :math:`n` is the number of qubits (width of the circuit).
The EI is obtained using the equation
.. math::
EI = \frac{4^n - 1}{4^n}\left(1 - \alpha\right)
The fit :math:`\alpha` parameter can be fit using one of the following three quantities
plotted on the y-axis:
Success Probabilities (:math:`p`): The proportion of shots that return the correct bitstring
Adjusted Success Probabilities (:math:`p_0`):
.. math::
p_0 = \sum_{k = 0}^n \left(-\frac{1}{2}\right)^k h_k
where :math:`h_k` is the probability of observing a bitstring of Hamming distance of k from the
correct bitstring
Effective Polarizations (:math:`S`):
.. math::
S = \frac{4^n}{4^n-1}\left(\sum_{k=0}^n\left(-\frac{1}{2}\right)^k h_k\right)-\frac{1}{4^n-1}
# section: fit_model
The fit is based on the following decay functions:
.. math::
F(x) = a \alpha^{x} + b
# section: fit_parameters
defpar a:
desc: Height of decay curve.
init_guess: Determined by :math:`1 - b`.
bounds: [0, 1]
defpar b:
desc: Base line.
init_guess: Determined by :math:`(1/2)^n` (for success probability) or :math:`(1/4)^n`
(for adjusted success probability and effective polarization).
bounds: [0, 1]
defpar \alpha:
desc: Depolarizing parameter.
init_guess: Determined by :func:`~rb_decay` with standard RB curve.
bounds: [0, 1]
# section: reference
.. ref_arxiv:: 1 2112.09853
"""
@classmethod
def _default_options(cls):
"""Default analysis options.
Analysis Options:
analyzed_quantity (str): Set the metric to plot on the y-axis. Must be one of
"Effective Polarization" (default), "Success Probability", or "Adjusted
Success Probability".
gate_error_ratio (Optional[Dict[str, float]]): A dictionary with gate name keys
and error ratio values used when calculating EPG from the estimated EPC.
The default value will use standard gate error ratios.
If you don't know accurate error ratio between your basis gates,
you can skip analysis of EPGs by setting this options to ``None``.
epg_1_qubit (List[AnalysisResult]): Analysis results from previous RB experiments
for individual single qubit gates. If this is provided, EPC of
2Q RB is corrected to exclude the depolarization of underlying 1Q channels.
"""
default_options = super()._default_options()
# Set labels of axes
default_options.plotter.set_figure_options(
xlabel="Clifford Length",
ylabel="Effective Polarization",
)
# Plot all (adjusted) success probabilities
default_options.plot_raw_data = True
# Exponential decay parameter
default_options.result_parameters = ["alpha"]
# Default gate error ratio for calculating EPG
default_options.gate_error_ratio = "default"
# By default, EPG for single qubits aren't set
default_options.epg_1_qubit = None
# By default, effective polarization is plotted (see arXiv:2112.09853). We can
# also plot success probability or adjusted success probability (see PyGSTi).
# Do this by setting options to "Success Probability" or "Adjusted Success Probability"
default_options.analyzed_quantity = "Effective Polarization"
default_options.set_validator(
field="analyzed_quantity",
validator_value=[
"Success Probability",
"Adjusted Success Probability",
"Effective Polarization",
],
)
return default_options
def _generate_fit_guesses(
self,
user_opt: curve.FitOptions,
curve_data: curve.ScatterTable,
) -> Union[curve.FitOptions, List[curve.FitOptions]]:
"""Create algorithmic guess with analysis options and curve data.
Args:
user_opt: Fit options filled with user provided guess and bounds.
curve_data: Formatted data collection to fit.
Returns:
List of fit options that are passed to the fitter function.
"""
user_opt.bounds.set_if_empty(a=(0, 1), alpha=(0, 1), b=(0, 1))
num_qubits = len(self._physical_qubits)
# Initialize guess for baseline and amplitude based on infidelity type
b_guess = 1 / 4**num_qubits
if self.options.analyzed_quantity == "Success Probability":
b_guess = 1 / 2**num_qubits
mirror_curve = curve_data.get_subset_of("rb_decay")
alpha_mirror = curve.guess.rb_decay(mirror_curve.x, mirror_curve.y, b=b_guess)
a_guess = (curve_data.y[0] - b_guess) / (alpha_mirror ** curve_data.x[0])
user_opt.p0.set_if_empty(b=b_guess, a=a_guess, alpha=alpha_mirror)
return user_opt
def _create_analysis_results(
self,
fit_data: curve.CurveFitResult,
quality: str,
**metadata,
) -> List[AnalysisResultData]:
"""Create analysis results for important fit parameters. Besides the
default standard RB parameters, Entanglement Infidelity (EI) is also calculated.
Args:
fit_data: Fit outcome.
quality: Quality of fit outcome.
Returns:
List of analysis result data.
"""
outcomes = super()._create_analysis_results(fit_data, quality, **metadata)
num_qubits = len(self._physical_qubits)
# nrb is calculated for both EPC and EI per the equations in the docstring
ei_nrb = 4**num_qubits
ei_scale = (ei_nrb - 1) / ei_nrb
ei = ei_scale * (1 - fit_data.ufloat_params["alpha"])
outcomes.append(
AnalysisResultData(
name="EI", value=ei, chisq=fit_data.reduced_chisq, quality=quality, extra=metadata
)
)
return outcomes
def _initialize(self, experiment_data: ExperimentData):
"""Initialize curve analysis by setting up the data processor for Mirror
RB data.
Args:
experiment_data: Experiment data to analyze.
"""
super()._initialize(experiment_data)
num_qubits = len(self._physical_qubits)
target_bs = []
for circ_result in experiment_data.data():
if circ_result["metadata"]["inverting_pauli_layer"] is True:
target_bs.append("0" * num_qubits)
else:
target_bs.append(circ_result["metadata"]["target"])
self.set_options(
data_processor=DataProcessor(
input_key="counts",
data_actions=[
_ComputeQuantities(
analyzed_quantity=self.options.analyzed_quantity,
num_qubits=num_qubits,
target_bs=target_bs,
)
],
)
)
class _ComputeQuantities(DataAction):
"""Data processing node for computing useful mirror RB quantities from raw results."""
def __init__(
self,
num_qubits,
target_bs,
analyzed_quantity: str = "Effective Polarization",
validate: bool = True,
):
"""
Args:
num_qubits: Number of qubits.
quantity: The quantity to calculate.
validate: If set to False the DataAction will not validate its input.
"""
super().__init__(validate)
self._num_qubits = num_qubits
self._analyzed_quantity = analyzed_quantity
self._target_bs = target_bs
def _process(self, data: np.ndarray):
# Arrays to store the y-axis data and uncertainties
y_data = []
y_data_unc = []
for i, circ_result in enumerate(data):
target_bs = self._target_bs[i]
# h[k] = proportion of shots that are Hamming distance k away from target bitstring
hamming_dists = np.zeros(self._num_qubits + 1)
success_prob = 0.0
success_prob_unc = 0.0
for bitstring, count in circ_result.items():
# Compute success probability
if self._analyzed_quantity == "Success Probability":
if bitstring == target_bs:
success_prob = count / sum(circ_result.values())
success_prob_unc = np.sqrt(success_prob * (1 - success_prob))
break
else:
# Compute hamming distance proportions
target_bs_to_list = [int(char) for char in target_bs]
actual_bs_to_list = [int(char) for char in bitstring]
k = int(round(hamming(target_bs_to_list, actual_bs_to_list) * self._num_qubits))
hamming_dists[k] += count / sum(circ_result.values())
if self._analyzed_quantity == "Success Probability":
y_data.append(success_prob)
y_data_unc.append(success_prob_unc)
continue
# Compute hamming distance uncertainties
hamming_dist_unc = np.sqrt(hamming_dists * (1 - hamming_dists))
# Compute adjusted success probability and standard deviation
adjusted_success_prob = 0.0
adjusted_success_prob_unc = 0.0
for k in range(self._num_qubits + 1):
adjusted_success_prob += (-0.5) ** k * hamming_dists[k]
adjusted_success_prob_unc += (0.5) ** k * hamming_dist_unc[k] ** 2
adjusted_success_prob_unc = np.sqrt(adjusted_success_prob_unc)
if self._analyzed_quantity == "Adjusted Success Probability":
y_data.append(adjusted_success_prob)
y_data_unc.append(adjusted_success_prob_unc)
# Compute effective polarization and standard deviation (arXiv:2112.09853v1)
pol_factor = 4**self._num_qubits
pol = pol_factor / (pol_factor - 1) * adjusted_success_prob - 1 / (pol_factor - 1)
pol_unc = np.sqrt(pol_factor / (pol_factor - 1)) * adjusted_success_prob_unc
if self._analyzed_quantity == "Effective Polarization":
y_data.append(pol)
y_data_unc.append(pol_unc)
return unp.uarray(y_data, y_data_unc)
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Purity RB analysis class.
"""
from typing import List, Dict, Union
from qiskit.result import sampled_expectation_value
from qiskit_experiments.curve_analysis import ScatterTable
import qiskit_experiments.curve_analysis as curve
from qiskit_experiments.framework import AnalysisResultData
from qiskit_experiments.library.randomized_benchmarking import RBAnalysis
from qiskit_experiments.library.randomized_benchmarking.rb_analysis import (_calculate_epg,
_exclude_1q_error)
class PurityRBAnalysis(RBAnalysis):
r"""A class to analyze purity randomized benchmarking experiments.
# section: overview
This analysis takes only single series.
This series is fit by the exponential decay function.
From the fit :math:`\alpha` value this analysis estimates the error per Clifford (EPC).
When analysis option ``gate_error_ratio`` is provided, this analysis also estimates
errors of individual gates assembling a Clifford gate.
In computation of two-qubit EPC, this analysis can also decompose
the contribution from the underlying single qubit depolarizing channels when
``epg_1_qubit`` analysis option is provided [1].
# section: fit_model
.. math::
F(x) = a \alpha^x + b
# section: fit_parameters
defpar a:
desc: Height of decay curve.
init_guess: Determined by :math:`1 - b`.
bounds: [0, 1]
defpar b:
desc: Base line.
init_guess: Determined by :math:`(1/2)^n` where :math:`n` is number of qubit.
bounds: [0, 1]
defpar \alpha:
desc: Depolarizing parameter.
init_guess: Determined by :func:`~.guess.rb_decay`.
bounds: [0, 1]
# section: reference
.. ref_arxiv:: 1 1712.06550
"""
def __init__(self):
super().__init__()
def _run_data_processing(
self,
raw_data: List[Dict],
category: str = "raw",
) -> ScatterTable:
"""Perform data processing from the experiment result payload.
For purity this converts the counts into Trace(rho^2) and then runs the
rest of the standard RB fitters
For now this does it by spoofing a new counts dictionary and then
calling the super _run_data_processing
Args:
raw_data: Payload in the experiment data.
category: Category string of the output dataset.
Returns:
Processed data that will be sent to the formatter method.
Raises:
DataProcessorError: When key for x values is not found in the metadata.
ValueError: When data processor is not provided.
"""
#figure out the number of qubits... has to be 1 or 2 for now
if self.options.outcome=='0':
nq=1
elif self.options.outcome=='00':
nq=2
else:
raise ValueError("Only supporting 1 or 2Q purity")
ntrials = int(len(raw_data)/3**nq)
raw_data2 = []
nshots = int(sum(raw_data[0]['counts'].values()))
for i in range(ntrials):
trial_raw = [d for d in raw_data if d["metadata"]["trial"]==i]
raw_data2.append(trial_raw[0])
purity = 1/2**nq
if nq==1:
for ii in range(3):
purity += sampled_expectation_value(trial_raw[ii]['counts'],'Z')**2/2**nq
else:
for ii in range(9):
purity += sampled_expectation_value(trial_raw[ii]['counts'],'ZZ')**2/2**nq
purity += sampled_expectation_value(trial_raw[ii]['counts'],'IZ')**2/2**nq/3**(nq-1)
purity += sampled_expectation_value(trial_raw[ii]['counts'],'ZI')**2/2**nq/3**(nq-1)
raw_data2[-1]['counts'] = {'0'*nq: int(purity*nshots*10),'1'*nq: int((1-purity)*nshots*10)}
return super()._run_data_processing(raw_data2,category)
def _create_analysis_results(
self,
fit_data: curve.CurveFitResult,
quality: str,
**metadata,
) -> List[AnalysisResultData]:
"""Create analysis results for important fit parameters.
Args:
fit_data: Fit outcome.
quality: Quality of fit outcome.
Returns:
List of analysis result data.
"""
outcomes = curve.CurveAnalysis._create_analysis_results(self, fit_data, quality, **metadata)
num_qubits = len(self._physical_qubits)
# Calculate EPC
# For purity we need to correct by
alpha = fit_data.ufloat_params["alpha"]**0.5
scale = (2**num_qubits - 1) / (2**num_qubits)
epc = scale * (1 - alpha)
outcomes.append(
AnalysisResultData(
name="EPC",
value=epc,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
# Correction for 1Q depolarizing channel if EPGs are provided
if self.options.epg_1_qubit and num_qubits == 2:
epc = _exclude_1q_error(
epc=epc,
qubits=self._physical_qubits,
gate_counts_per_clifford=self._gate_counts_per_clifford,
extra_analyses=self.options.epg_1_qubit,
)
outcomes.append(
AnalysisResultData(
name="EPC_corrected",
value=epc,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
# Calculate EPG
if self._gate_counts_per_clifford is not None and self.options.gate_error_ratio:
epg_dict = _calculate_epg(
epc=epc,
qubits=self._physical_qubits,
gate_error_ratio=self.options.gate_error_ratio,
gate_counts_per_clifford=self._gate_counts_per_clifford,
)
if epg_dict:
for gate, epg_val in epg_dict.items():
outcomes.append(
AnalysisResultData(
name=f"EPG_{gate}",
value=epg_val,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
return outcomes
def _generate_fit_guesses(
self,
user_opt: curve.FitOptions,
curve_data: curve.ScatterTable,
) -> Union[curve.FitOptions, List[curve.FitOptions]]:
"""Create algorithmic initial fit guess from analysis options and curve data.
Args:
user_opt: Fit options filled with user provided guess and bounds.
curve_data: Formatted data collection to fit.
Returns:
List of fit options that are passed to the fitter function.
"""
user_opt.bounds.set_if_empty(
a=(0, 1),
alpha=(0, 1),
b=(0, 1),
)
b_guess = 1 / 2 ** len(self._physical_qubits)
if len(curve_data.x)>3:
alpha_guess = curve.guess.rb_decay(curve_data.x[0:3], curve_data.y[0:3], b=b_guess)
else:
alpha_guess = curve.guess.rb_decay(curve_data.x, curve_data.y, b=b_guess)
alpha_guess = alpha_guess**2
if alpha_guess < 0.6:
a_guess = (curve_data.y[0] - b_guess)
else:
a_guess = (curve_data.y[0] - b_guess) / (alpha_guess ** curve_data.x[0])
user_opt.p0.set_if_empty(
b=b_guess,
a=a_guess,
alpha=alpha_guess,
)
return user_opt
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Purity RB Experiment class.
"""
import numpy as np
from numpy.random import Generator
from numpy.random.bit_generator import BitGenerator, SeedSequence
from numbers import Integral
from typing import Union, Iterable, Optional, List, Sequence
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
from qiskit.providers.backend import Backend
from qiskit.circuit import CircuitInstruction, Barrier
from qiskit_experiments.library.randomized_benchmarking import StandardRB
SequenceElementType = Union[Clifford, Integral, QuantumCircuit]
from .purrb_analysis import PurityRBAnalysis
class PurityRB(StandardRB):
"""An experiment to characterize the error rate of a gate set on a device.
using purity RB
# section: overview
Randomized Benchmarking (RB) is an efficient and robust method
for estimating the average error rate of a set of quantum gate operations.
See `Qiskit Textbook
<https://github.com/Qiskit/textbook/blob/main/notebooks/quantum-hardware/randomized-benchmarking.ipynb>`_
for an explanation on the RB method.
A standard RB experiment generates sequences of random Cliffords
such that the unitary computed by the sequences is the identity.
After running the sequences on a backend, it calculates the probabilities to get back to
the ground state, fits an exponentially decaying curve, and estimates
the Error Per Clifford (EPC), as described in Refs. [1, 2].
.. note::
In 0.5.0, the default value of ``optimization_level`` in ``transpile_options`` changed
from ``0`` to ``1`` for RB experiments. That may result in shorter RB circuits
hence slower decay curves than before.
# section: analysis_ref
:class:`RBAnalysis`
# section: manual
:doc:`/manuals/verification/randomized_benchmarking`
# section: reference
.. ref_arxiv:: 1 1009.3639
.. ref_arxiv:: 2 1109.6887
"""
def __init__(
self,
physical_qubits: Sequence[int],
lengths: Iterable[int],
backend: Optional[Backend] = None,
num_samples: int = 3,
seed: Optional[Union[int, SeedSequence, BitGenerator, Generator]] = None,
full_sampling: Optional[bool] = False,
):
"""Initialize a standard randomized benchmarking experiment.
Args:
physical_qubits: List of physical qubits for the experiment.
lengths: A list of RB sequences lengths.
backend: The backend to run the experiment on.
num_samples: Number of samples to generate for each sequence length.
seed: Optional, seed used to initialize ``numpy.random.default_rng``.
when generating circuits. The ``default_rng`` will be initialized
with this seed value every time :meth:`circuits` is called.
full_sampling: If True all Cliffords are independently sampled for all lengths.
If False for sample of lengths longer sequences are constructed
by appending additional samples to shorter sequences.
The default is False.
Raises:
QiskitError: If any invalid argument is supplied.
"""
# Initialize base experiment (RB)
super().__init__(physical_qubits, lengths, backend, num_samples, seed, full_sampling)
#override the analysis
self.analysis = PurityRBAnalysis()
self.analysis.set_options(outcome="0" * self.num_qubits)
self.analysis.plotter.set_figure_options(
xlabel="Clifford Length",
ylabel="Purity",
)
def circuits(self) -> List[QuantumCircuit]:
"""Return a list of RB circuits.
Returns:
A list of :class:`QuantumCircuit`.
"""
# Sample random Clifford sequences
sequences = self._sample_sequences()
# Convert each sequence into circuit and append the inverse to the end.
# and the post-rotations
circuits = self._sequences_to_circuits(sequences)
# Add metadata for each circuit
# trial links all from the same trial
# needed for post processing the purity RB
for circ_i, circ in enumerate(circuits):
circ.metadata = {
"xval": len(sequences[int(circ_i/3**self.num_qubits)]),
"trial": int(circ_i/3**self.num_qubits),
"group": "Clifford",
}
return circuits
def _sequences_to_circuits(
self, sequences: List[Sequence[SequenceElementType]]
) -> List[QuantumCircuit]:
"""Convert an RB sequence into circuit and append the inverse to the end and
then the post rotations for purity RB
Returns:
A list of purity RB circuits.
"""
synthesis_opts = self._get_synthesis_options()
#post rotations as cliffords
post_rot = []
for i in range(3**self.num_qubits):
##find clifford
qc = QuantumCircuit(self.num_qubits)
for j in range(self.num_qubits):
qg_ind = np.mod(int(i/3**j),3)
if qg_ind==1:
qc.sx(j)
elif qg_ind==2:
qc.sdg(j)
qc.sx(j)
qc.s(j)
post_rot.append(self._to_instruction(Clifford(qc), synthesis_opts))
# Circuit generation
circuits = []
for i, seq in enumerate(sequences):
if (
self.experiment_options.full_sampling
or i % len(self.experiment_options.lengths) == 0
):
prev_elem, prev_seq = self._StandardRB__identity_clifford(), []
circ = QuantumCircuit(self.num_qubits)
for elem in seq:
circ.append(self._to_instruction(elem, synthesis_opts), circ.qubits)
circ._append(CircuitInstruction(Barrier(self.num_qubits), circ.qubits))
# Compute inverse, compute only the difference from the previous shorter sequence
prev_elem = self._StandardRB__compose_clifford_seq(prev_elem, seq[len(prev_seq) :])
prev_seq = seq
inv = self._StandardRB__adjoint_clifford(prev_elem)
circ.append(self._to_instruction(inv, synthesis_opts), circ.qubits)
#copy the circuit and apply post rotations
for j in range(3**self.num_qubits):
circ2 = circ.copy()
circ2.append(post_rot[j], circ.qubits)
circ2.measure_all() # includes insertion of the barrier before measurement
circuits.append(circ2)
return circuits
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Analyze the benchmarking results
"""
import argparse
import numpy as np
import qiskit_device_benchmarking.utilities.file_utils as fu
import matplotlib.pyplot as plt
def generate_plot(out_data, config_data, args):
"""Generate a plot from the fast_bench data
Generates a plot of the name result_plot_<XXX>.pdf where XXX is the
current date and time
Args:
out_data: data from the run
config_data: configuration data from the run
args: arguments passed to the parser
Returns:
None
"""
markers = ['o','x','.','s','^','v','*']
for i, backend in enumerate(out_data):
plt.semilogy(out_data[backend][0],out_data[backend][1], label=backend, marker=markers[np.mod(i,len(markers))])
plt.legend()
plt.xlabel('Depth')
plt.ylabel('Success Probability (%s over sets)'%args.value)
plt.ylim(top=1.0)
plt.title('Running Mirror - HE: %s, DD: %s, Trials: %d'%(config_data['he'],
config_data['dd'],
config_data['trials']))
plt.grid(True)
plt.savefig('result_plot_%s.pdf'%fu.timestamp_name())
plt.close()
return
if __name__ == '__main__':
"""Analyze a benchmarking run from `fast_bench.py`
Args:
Call -h for arguments
"""
parser = argparse.ArgumentParser(description = 'Analyze the results of a '
+ 'benchmarking run.')
parser.add_argument('-f', '--files', help='Comma separated list of files')
parser.add_argument('-b', '--backends', help='Comma separated list of '
+ 'backends to plot. If empty plot all.')
parser.add_argument('-v', '--value', help='Statistical value to compute',
choices=['mean','median', 'max', 'min'], default='mean')
parser.add_argument('--plot', help='Generate a plot', action='store_true')
args = parser.parse_args()
#import from results files and concatenate into a larger results
results_dict = {}
for file in args.files.split(','):
results_dict_new = fu.import_yaml(file)
for backend in results_dict_new:
if backend not in results_dict:
results_dict[backend] = results_dict_new[backend]
elif backend!='config':
#backend in the results dict but maybe not that depth
for depth in results_dict_new[backend]:
if depth in results_dict[backend]:
err_str = 'Depth %s already exists for backend %s, duplicate results'%(depth,backend)
raise ValueError(err_str)
else:
#check the metadata is the same
#TO DO
results_dict[backend][depth] = results_dict_new[backend][depth]
if args.backends is not None:
backends_filt = args.backends.split(',')
else:
backends_filt = []
out_data = {}
for backend in results_dict:
if len(backends_filt)>0:
if backend not in backends_filt:
continue
if backend=='config':
continue
print(backend)
depth_list = []
depth_list_i = []
out_data[backend] = []
for depth in results_dict[backend]:
if depth=='job_ids':
continue
depth_list_i.append(depth)
if args.value=='mean':
depth_list.append(np.mean(results_dict[backend][depth]['mean']))
elif args.value=='max':
depth_list.append(np.max(results_dict[backend][depth]['mean']))
elif args.value=='min':
depth_list.append(np.min(results_dict[backend][depth]['mean']))
else:
depth_list.append(np.median(results_dict[backend][depth]['mean']))
print('Backend %s'%backend)
print('Depths: %s'%depth_list_i)
if args.value=='mean':
print('Means: %s'%depth_list)
elif args.value=='max':
print('Max: %s'%depth_list)
elif args.value=='min':
print('Min: %s'%depth_list)
else:
print('Median: %s'%depth_list)
out_data[backend].append(depth_list_i)
out_data[backend].append(depth_list)
if args.plot:
generate_plot(out_data, results_dict['config'], args)
elif args.plot:
print('Need to run mean/max also')
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Analyze the fast_count results
"""
import argparse
import numpy as np
import qiskit_device_benchmarking.utilities.file_utils as fu
import matplotlib.pyplot as plt
def generate_plot(out_data, degree_data, args):
"""Generate a bar plot of the qubit numbers of each backend
Generates a plot of the name count_plot_<XXX>.pdf where XXX is the
current date and time
Args:
out_data: data from the run (count data)
degree_data: average degree
args: arguments passed to the parser
Returns:
None
"""
count_data = np.array([out_data[i] for i in out_data])
degree_data = np.array([degree_data[i] for i in out_data])
backend_lbls = np.array([i for i in out_data])
sortinds = np.argsort(count_data)
plt.bar(backend_lbls[sortinds], count_data[sortinds])
plt.xticks(rotation=45, ha='right')
ax1 = plt.gca()
ax2 = ax1.twinx()
ax2.plot(range(len(sortinds)),degree_data[sortinds],marker='x', color='black')
plt.xlabel('Backend')
plt.grid(axis='y')
ax1.set_ylabel('Largest Connected Region')
ax2.set_ylabel('Average Degree')
plt.title('CHSH Test on Each Edge to Determine Qubit Count')
plt.savefig('count_plot_%s.pdf'%fu.timestamp_name(),bbox_inches='tight')
plt.close()
return
if __name__ == '__main__':
"""Analyze a benchmarking run from `fast_bench.py`
Args:
Call -h for arguments
"""
parser = argparse.ArgumentParser(description = 'Analyze the results of a '
+ 'benchmarking run.')
parser.add_argument('-f', '--files', help='Comma separated list of files')
parser.add_argument('-b', '--backends', help='Comma separated list of '
+ 'backends to plot. If empty plot all.')
parser.add_argument('--plot', help='Generate a plot', action='store_true')
args = parser.parse_args()
#import from results files and concatenate into a larger results
results_dict = {}
for file in args.files.split(','):
results_dict_new = fu.import_yaml(file)
for backend in results_dict_new:
if backend not in results_dict:
results_dict[backend] = results_dict_new[backend]
elif backend!='config':
#backend in the results dict but maybe not that depth
err_str = 'Backend %s already exists, duplicate results'%(backend)
raise ValueError(err_str)
if args.backends is not None:
backends_filt = args.backends.split(',')
else:
backends_filt = []
count_data = {}
degree_data = {}
for backend in results_dict:
if len(backends_filt)>0:
if backend not in backends_filt:
continue
if backend=='config':
continue
count_data[backend] = results_dict[backend]['largest_region']
degree_data[backend] = results_dict[backend]['average_degree']
print('Backend %s, Largest Connected Region: %d'%(backend,count_data[backend]))
print('Backend %s, Average Degree: %f'%(backend,degree_data[backend]))
if args.plot:
generate_plot(count_data, degree_data, args)
elif args.plot:
print('Need to run mean/max also')
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Fast benchmark via mirror circuits
"""
import argparse
import numpy as np
import rustworkx as rx
from qiskit_ibm_provider import IBMProvider
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.transpiler import Target, CouplingMap
from qiskit_experiments.framework import (ParallelExperiment, BatchExperiment)
import qiskit_device_benchmarking.utilities.file_utils as fu
import qiskit_device_benchmarking.utilities.graph_utils as gu
from qiskit_device_benchmarking.bench_code.mrb import MirrorQuantumVolume
def run_bench(hgp, backends, depths=[8], trials=10,
nshots=100, he=True, dd=True, opt_level=3, act_name=''):
"""Run a benchmarking test (mirror QV) on a set of devices
Args:
hgp: hub/group/project
backends: list of backends
depths: list of mirror depths (square circuits)
trials: number of randomizations
nshots: number of shots
he: hardware efficient True/False (False is original QV circ all to all,
True assumes a line)
dd: add dynamic decoupling
opt_level: optimization level of the transpiler
act_name: account name to be passed to the runtime service
Returns:
flat list of lists of qubit chains
"""
#load the service
service = QiskitRuntimeService(name=act_name)
job_list = []
result_dict = {}
result_dict['config'] = {'hgp': hgp, 'depths': depths,
'trials': trials,
'nshots': nshots,
'dd': dd,
'he': he,
'pregenerated': False,
'opt_level': opt_level,
'act_name': act_name}
print('Running Fast Bench with options %s'%result_dict['config'])
#run all the circuits
for backend in backends:
print('Loading backend %s'%backend)
result_dict[backend] = {}
backend_real=service.backend(backend,instance=hgp)
mqv_exp_list_d = []
for depth in depths:
print('Generating Depth %d Circuits for Backend %s'%(depth, backend))
result_dict[backend][depth] = {}
#compute the sets for this
#NOTE: I want to replace this with fixed sets from
#a config file!!!
nq = backend_real.configuration().n_qubits
coupling_map = backend_real.configuration().coupling_map
G = gu.build_sys_graph(nq, coupling_map)
paths = rx.all_pairs_all_simple_paths(G,depth,depth)
paths = gu.paths_flatten(paths)
new_sets = gu.get_separated_sets(G,paths,min_sep=2,nsets=1)
mqv_exp_list = []
result_dict[backend][depth]['sets'] = new_sets[0]
#Construct mirror QV circuits on each parallel set
for qset in new_sets[0]:
#generate the circuits
mqv_exp = MirrorQuantumVolume(qubits=qset,backend=backend_real,trials=trials,
pauli_randomize=True, he = he)
mqv_exp.analysis.set_options(plot=False,
calc_hop=False,
analyzed_quantity='Success Probability')
#Do this so it won't compile outside the qubit sets
cust_map = []
for i in coupling_map:
if i[0] in qset and i[1] in qset:
cust_map.append(i)
cust_target = Target.from_configuration(basis_gates = backend_real.configuration().basis_gates,
num_qubits=nq,
coupling_map=CouplingMap(cust_map))
mqv_exp.set_transpile_options(target=cust_target, optimization_level=opt_level)
mqv_exp_list.append(mqv_exp)
new_exp_mqv = ParallelExperiment(mqv_exp_list, backend=backend_real, flatten_results=False)
if dd:
#this forces the circuits to have DD on them
print('Transpiling and DD')
for i in mqv_exp_list:
i.dd_circuits()
mqv_exp_list_d.append(new_exp_mqv)
new_exp_mqv = BatchExperiment(mqv_exp_list_d, backend=backend_real, flatten_results=False)
new_exp_mqv.set_run_options(shots=nshots)
job_list.append(new_exp_mqv.run())
result_dict[backend]['job_ids'] = job_list[-1].job_ids
#get the jobs back
for i, backend in enumerate(backends):
print('Loading results for backend: %s'%backend)
expdata = job_list[i]
try:
expdata.block_for_results()
except:
#remove backend from results
print('Error loading backend %s results'%backend)
result_dict.pop(backend)
continue
for j, depth in enumerate(depths):
result_dict[backend][depth]['data'] = []
result_dict[backend][depth]['mean'] = []
result_dict[backend][depth]['std'] = []
for k in range(len(result_dict[backend][depth]['sets'])):
result_dict[backend][depth]['data'].append([float(probi) for probi in list(expdata.child_data()[j].child_data()[k].artifacts()[0].data)])
result_dict[backend][depth]['mean'].append(float(np.mean(result_dict[backend][depth]['data'][-1])))
result_dict[backend][depth]['std'].append(float(np.std(result_dict[backend][depth]['data'][-1])))
fu.export_yaml('MQV_' + fu.timestamp_name() + '.yaml', result_dict)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Run fast benchmark of '
+ 'devices using mirror. Specify a config '
+' yaml and override settings on the command line')
parser.add_argument('-c', '--config', help='config file name',
default='config.yaml')
parser.add_argument('-b', '--backend', help='Specify backend and override '
+ 'backend_group')
parser.add_argument('-bg', '--backend_group',
help='specify backend group in config file',
default='backends')
parser.add_argument('--hgp', help='specify hgp')
parser.add_argument('--he', help='Hardware efficient', action='store_true')
parser.add_argument('--name', help='Account name', default='')
args = parser.parse_args()
#import from config
config_dict = fu.import_yaml(args.config)
print('Config File Found')
print(config_dict)
#override from the command line
if args.backend is not None:
backends = [args.backend]
else:
backends = config_dict[args.backend_group]
if args.hgp is not None:
hgp = args.hgp
else:
hgp = config_dict['hgp']
if args.he is True:
he = True
else:
he = config_dict['he']
opt_level = config_dict['opt_level']
dd = config_dict['dd']
depths = config_dict['depths']
trials = config_dict['trials']
nshots = config_dict['shots']
#print(hgp, backends, he, opt_level, dd, depths, trials, nshots)
run_bench(hgp, backends, depths=depths, trials=trials,
nshots=nshots, he=he, dd=dd, opt_level=opt_level, act_name=args.name)
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Fast benchmark of qubit count using the CHSH inequality
"""
import argparse
import rustworkx as rx
import networkx as nx
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_experiments.framework import (ParallelExperiment, BatchExperiment)
import qiskit_device_benchmarking.utilities.file_utils as fu
import qiskit_device_benchmarking.utilities.graph_utils as gu
from qiskit_device_benchmarking.bench_code.bell import CHSHExperiment
def run_count(hgp, backends, nshots=100, act_name=''):
"""Run a chsh inequality on a number of devices
Args:
hgp: hub/group/project
backends: list of backends
nshots: number of shots
act_name: account name to be passed to the runtime service
Returns:
flat list of all the edges
"""
#load the service
service = QiskitRuntimeService(name=act_name)
job_list = []
result_dict = {}
result_dict['config'] = {'hgp': hgp,
'nshots': nshots,
'act_name': act_name}
print('Running Fast Count with options %s'%result_dict['config'])
#run all the circuits
for backend in backends:
print('Loading backend %s'%backend)
result_dict[backend] = {}
backend_real=service.backend(backend,instance=hgp)
chsh_exp_list_b = []
#compute the sets for this
#NOTE: I want to replace this with fixed sets from
#a config file!!!
nq = backend_real.configuration().n_qubits
coupling_map = backend_real.configuration().coupling_map
#build a set of gates
G = gu.build_sys_graph(nq, coupling_map)
#get all length 2 paths in the device
paths = rx.all_pairs_all_simple_paths(G,2,2)
#flatten those paths into a list from the rustwork x iterator
paths = gu.paths_flatten(paths)
#remove permutations
paths = gu.remove_permutations(paths)
#convert to the coupling map of the device
paths = gu.path_to_edges(paths,coupling_map)
#make into separate sets
sep_sets = gu.get_separated_sets(G, paths, min_sep=2)
result_dict[backend]['sets'] = sep_sets
#Construct mirror QV circuits on each parallel set
for qsets in sep_sets:
chsh_exp_list = []
for qset in qsets:
#generate the circuits
chsh_exp = CHSHExperiment(physical_qubits=qset,backend=backend_real)
chsh_exp.set_transpile_options(optimization_level=1)
chsh_exp_list.append(chsh_exp)
new_exp_chsh = ParallelExperiment(chsh_exp_list,
backend=backend_real,
flatten_results=False)
chsh_exp_list_b.append(new_exp_chsh)
new_exp_chsh = BatchExperiment(chsh_exp_list_b, backend=backend_real,
flatten_results=False)
new_exp_chsh.set_run_options(shots=nshots)
job_list.append(new_exp_chsh.run())
result_dict[backend]['job_ids'] = job_list[-1].job_ids
#get the jobs back
for i, backend in enumerate(backends):
print('Loading results for backend: %s'%backend)
expdata = job_list[i]
try:
expdata.block_for_results()
except:
#remove backend from results
print('Error loading backend %s results'%backend)
result_dict.pop(backend)
continue
result_dict[backend]['chsh_values'] = {}
for qsets_i, qsets in enumerate(result_dict[backend]['sets']):
for qset_i, qset in enumerate(qsets):
anal_res = expdata.child_data()[qsets_i].child_data()[qset_i].analysis_results()[0]
qedge = '%d_%d'%(anal_res.device_components[0].index,anal_res.device_components[1].index)
result_dict[backend]['chsh_values'][qedge] = anal_res.value
#calculate number of connected qubits
G = nx.Graph()
#add all possible edges
for i in result_dict[backend]['chsh_values']:
if result_dict[backend]['chsh_values'][i]>=2:
G.add_edge(int(i.split('_')[0]),int(i.split('_')[1]))
#catch error if the graph is empty
try:
largest_cc = max(nx.connected_components(G), key=len)
#look at the average degree of the largest region
avg_degree = 0
for i in largest_cc:
avg_degree += nx.degree(G,i)
avg_degree = avg_degree/len(largest_cc)
except:
largest_cc = {}
avg_degree = 1
result_dict[backend]['largest_region'] = len(largest_cc)
result_dict[backend]['average_degree'] = avg_degree
fu.export_yaml('CHSH_' + fu.timestamp_name() + '.yaml', result_dict)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Run fast benchmark of '
+ 'qubit count using chsh. Specify a config '
+' yaml and override settings on the command line')
parser.add_argument('-c', '--config', help='config file name',
default='config.yaml')
parser.add_argument('-b', '--backend', help='Specify backend and override '
+ 'backend_group')
parser.add_argument('-bg', '--backend_group',
help='specify backend group in config file',
default='backends')
parser.add_argument('--hgp', help='specify hgp')
parser.add_argument('--shots', help='specify number of shots')
parser.add_argument('--name', help='Account name', default='')
args = parser.parse_args()
#import from config
config_dict = fu.import_yaml(args.config)
print('Config File Found')
print(config_dict)
#override from the command line
if args.backend is not None:
backends = [args.backend]
else:
backends = config_dict[args.backend_group]
if args.hgp is not None:
hgp = args.hgp
else:
hgp = config_dict['hgp']
if args.shots is not None:
nshots = int(args.shots)
else:
nshots = config_dict['shots']
#print(hgp, backends, he, opt_level, dd, depths, trials, nshots)
run_count(hgp, backends, nshots=nshots, act_name=args.name)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Example use of the ProjectQ based simulators
"""
import os
from qiskit_addon_projectq import ProjectQProvider
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
def use_projectq_backends():
ProjectQ = ProjectQProvider()
qasm_sim = ProjectQ.get_backend('projectq_qasm_simulator')
sv_sim = ProjectQ.get_backend('projectq_statevector_simulator')
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
# ProjectQ statevector simulator
result = execute(qc, backend=sv_sim).result()
print("final quantum amplitude vector: ")
print(result.get_statevector(qc))
qc.measure(qr, cr)
# ProjectQ simulator
result = execute(qc, backend=qasm_sim, shots=100).result()
print("counts: ")
print(result.get_counts(qc))
if __name__ == "__main__":
use_projectq_backends()
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Exception for errors raised by ProjectQ simulators.
"""
from qiskit import QISKitError
class ProjectQSimulatorError(QISKitError):
"""Class for errors raised by the ProjectQ simulators."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,missing-docstring,broad-except,no-member
from test._random_circuit_generator import RandomCircuitGenerator
from test.common import QiskitProjectQTestCase
import random
import unittest
import numpy
from scipy.stats import chi2_contingency
from qiskit import (QuantumCircuit, QuantumRegister,
ClassicalRegister, execute)
from qiskit import BasicAer
from qiskit_addon_projectq import ProjectQProvider
class TestQasmSimulatorProjectQ(QiskitProjectQTestCase):
"""
Test projectq simulator.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# Set up random circuits
n_circuits = 5
min_depth = 1
max_depth = 10
min_qubits = 1
max_qubits = 4
random_circuits = RandomCircuitGenerator(min_qubits=min_qubits,
max_qubits=max_qubits,
min_depth=min_depth,
max_depth=max_depth,
seed=None)
for _ in range(n_circuits):
basis = list(random.sample(random_circuits.op_signature.keys(),
random.randint(2, 7)))
if 'reset' in basis:
basis.remove('reset')
if 'u0' in basis:
basis.remove('u0')
random_circuits.add_circuits(1, basis=basis)
cls.rqg = random_circuits
def setUp(self):
ProjectQ = ProjectQProvider()
self.projectq_sim = ProjectQ.get_backend('projectq_qasm_simulator')
self.aer_sim = BasicAer.get_backend('qasm_simulator')
def test_gate_x(self):
shots = 100
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr, name='test_gate_x')
qc.x(qr[0])
qc.measure(qr, cr)
result_pq = execute(qc, backend=self.projectq_sim,
shots=shots).result(timeout=30)
self.assertEqual(result_pq.get_counts(qc), {'1': shots})
def test_entangle(self):
shots = 100
N = 5
qr = QuantumRegister(N)
cr = ClassicalRegister(N)
qc = QuantumCircuit(qr, cr, name='test_entangle')
qc.h(qr[0])
for i in range(1, N):
qc.cx(qr[0], qr[i])
qc.measure(qr, cr)
result = execute(qc, backend=self.projectq_sim, shots=shots).result(timeout=30)
counts = result.get_counts(qc)
self.log.info(counts)
for key, _ in counts.items():
with self.subTest(key=key):
self.assertTrue(key in ['0' * N, '1' * N])
def test_random_circuits(self):
for circuit in self.rqg.get_circuits():
self.log.info(circuit.qasm())
shots = 100
result_pq = execute(circuit, backend=self.projectq_sim,
shots=shots).result(timeout=30)
result_qk = execute(circuit, backend=self.aer_sim,
shots=shots).result(timeout=30)
counts_pq = result_pq.get_counts(circuit)
counts_qk = result_qk.get_counts(circuit)
self.log.info('qasm_simulator_projectq: %s', str(counts_pq))
self.log.info('qasm_simulator: %s', str(counts_qk))
states = counts_qk.keys() | counts_pq.keys()
# contingency table
ctable = numpy.array([[counts_pq.get(key, 0) for key in states],
[counts_qk.get(key, 0) for key in states]])
result = chi2_contingency(ctable)
self.log.info('chi2_contingency: %s', str(result))
with self.subTest(circuit=circuit):
self.assertGreater(result[1], 0.01)
def test_all_bits_measured(self):
shots = 2
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr, name='all_bits_measured')
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.h(qr[0])
execute(qc, backend=self.projectq_sim,
shots=shots).result(timeout=30)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,missing-docstring,broad-except
from test.common import QiskitProjectQTestCase
import unittest
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit_addon_projectq import ProjectQProvider
class StatevectorSimulatorProjectQTest(QiskitProjectQTestCase):
"""Test ProjectQ C++ statevector simulator."""
def setUp(self):
ProjectQ = ProjectQProvider()
self.projectq_sim = ProjectQ.get_backend('projectq_statevector_simulator')
def test_sv_simulator_projectq(self):
"""Test final state vector for single circuit run."""
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
result = execute(qc, backend=self.projectq_sim).result()
self.assertEqual(result.status, 'COMPLETED')
actual = result.get_statevector(qc)
# state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase
self.assertAlmostEqual((abs(actual[0]))**2, 1/2)
self.assertAlmostEqual(abs(actual[1]), 0)
self.assertAlmostEqual(abs(actual[2]), 0)
self.assertAlmostEqual((abs(actual[3]))**2, 1/2)
def test_qubit_order(self):
"""Verify Qiskit qubit ordering in state vector"""
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
qc = QuantumCircuit(qr, cr)
qc.x(qr[0])
result = execute(qc, backend=self.projectq_sim).result()
self.assertEqual(result.status, 'COMPLETED')
actual = result.get_statevector(qc)
# state is |01> (up to a global phase), because qubit 0 is LSB
self.assertAlmostEqual(abs(actual[0]), 0)
self.assertAlmostEqual((abs(actual[1]))**2, 1)
self.assertAlmostEqual(abs(actual[2]), 0)
self.assertAlmostEqual(abs(actual[3]), 0)
if __name__ == '__main__':
unittest.main()
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Generate random circuits."""
import random
import numpy
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
def choices(population, weights=None, k=1):
"""
Replacement for `random.choices()`, which is only available in Python 3.6+.
TODO: drop once Python 3.6 is required by the sdk.
"""
if weights and sum(weights) != 1:
# Normalize the weights if needed, as numpy.random.choice requires so.
weights = [float(i)/sum(weights) for i in weights]
return numpy.random.choice(population, size=k, p=weights)
class RandomCircuitGenerator(object):
"""
Generate random size circuits for profiling.
"""
def __init__(self, seed=None,
max_qubits=5, min_qubits=1,
max_depth=100, min_depth=1):
"""
Args:
seed (int): Random number seed. If none, don't seed the generator.
max_qubits (int): Maximum number of qubits in a circuit.
min_qubits (int): Minimum number of operations in a cirucit.
max_depth (int): Maximum number of operations in a circuit.
min_depth (int): Minimum number of operations in circuit.
"""
self.max_depth = max_depth
self.max_qubits = max_qubits
self.min_depth = min_depth
self.min_qubits = min_qubits
self.circuit_list = []
self.n_qubit_list = []
self.depth_list = []
self.basis_gates = None
self.circuit_name_list = []
if seed is not None:
random.seed(a=seed)
# specify number of parameters and args for each op
# in the standard extension. If type hints (PEP484) are followed
# maybe we can guess this. "nregs" are the number of qubits the
# operation uses. If nregs=0 then it means either 1 qubit or
# 1 register. "nparams" are the number of parameters the operation takes.
self.op_signature = {
'barrier': {'nregs': 0, 'nparams': None},
'ccx': {'nregs': 3, 'nparams': None},
'ch': {'nregs': 2, 'nparams': None},
'crz': {'nregs': 2, 'nparams': 1},
'cswap': {'nregs': 3, 'nparams': None},
'cu1': {'nregs': 2, 'nparams': 1},
'cu3': {'nregs': 2, 'nparams': 3},
'cx': {'nregs': 2, 'nparams': None},
'cy': {'nregs': 2, 'nparams': None},
'cz': {'nregs': 2, 'nparams': None},
'h': {'nregs': 1, 'nparams': None},
'iden': {'nregs': 1, 'nparams': None},
'measure': {'nregs': 0, 'nparams': None},
'reset': {'nregs': 1, 'nparams': None},
'rx': {'nregs': 1, 'nparams': 1},
'ry': {'nregs': 1, 'nparams': 1},
'rz': {'nregs': 1, 'nparams': 1},
's': {'nregs': 1, 'nparams': None},
't': {'nregs': 1, 'nparams': None},
'u1': {'nregs': 1, 'nparams': 1},
'u2': {'nregs': 1, 'nparams': 2},
'u3': {'nregs': 1, 'nparams': 3},
'x': {'nregs': 1, 'nparams': None},
'y': {'nregs': 1, 'nparams': None},
'z': {'nregs': 1, 'nparams': None}}
def add_circuits(self, n_circuits, do_measure=True, basis=None,
basis_weights=None):
"""Adds circuits to program.
Generates a circuit with a random number of operations in `basis`.
Also adds a random number of measurements in
[1,nQubits] to end of circuit.
Args:
n_circuits (int): Number of circuits to add.
do_measure (bool): Whether to add measurements.
basis (list(str) or None): List of op names. If None, basis
is randomly chosen with unique ops in (2,7)
basis_weights (list(float) or None): List of weights
corresponding to indices in `basis`.
Raises:
AttributeError: if operation is not recognized.
"""
if basis is None:
basis = list(random.sample(self.op_signature.keys(),
random.randint(2, 7)))
basis_weights = [1./len(basis)] * len(basis)
if basis_weights is not None:
assert len(basis) == len(basis_weights)
uop_basis = basis[:]
if basis_weights:
uop_basis_weights = basis_weights[:]
else:
uop_basis_weights = None
# remove barrier from uop basis if it is specified
if 'barrier' in uop_basis:
ind = uop_basis.index('barrier')
del uop_basis[ind]
if uop_basis_weights:
del uop_basis_weights[ind]
# remove measure from uop basis if it is specified
if 'measure' in uop_basis:
ind = uop_basis.index('measure')
del uop_basis[ind]
if uop_basis_weights:
del uop_basis_weights[ind]
# self.basis_gates = uop_basis
self.basis_gates = basis
self.circuit_name_list = []
# TODO: replace choices with random.choices() when python 3.6 is
# required.
self.n_qubit_list = choices(
range(self.min_qubits, self.max_qubits + 1), k=n_circuits)
self.depth_list = choices(
range(self.min_depth, self.max_depth + 1), k=n_circuits)
for i_circuit in range(n_circuits):
n_qubits = self.n_qubit_list[i_circuit]
if self.min_regs_exceeds_nqubits(uop_basis, n_qubits):
# no gate operation from this circuit can fit in the available
# number of qubits.
continue
depth_cnt = self.depth_list[i_circuit]
reg_pop = numpy.arange(1, n_qubits+1)
register_weights = reg_pop[::-1].astype(float)
register_weights /= register_weights.sum()
max_registers = numpy.random.choice(reg_pop, p=register_weights)
reg_weight = numpy.ones(max_registers) / float(max_registers)
reg_sizes = rand_register_sizes(n_qubits, reg_weight)
n_registers = len(reg_sizes)
circuit = QuantumCircuit()
for i_size, size in enumerate(reg_sizes):
cr_name = 'cr' + str(i_size)
qr_name = 'qr' + str(i_size)
creg = ClassicalRegister(size, cr_name)
qreg = QuantumRegister(size, qr_name)
circuit.add_register(qreg, creg)
while depth_cnt > 0:
# TODO: replace choices with random.choices() when python 3.6
# is required.
op_name = choices(basis, weights=basis_weights)[0]
if hasattr(circuit, op_name):
operator = getattr(circuit, op_name)
else:
raise AttributeError('operation \"{0}\"'
' not recognized'.format(op_name))
n_regs = self.op_signature[op_name]['nregs']
n_params = self.op_signature[op_name]['nparams']
if n_regs == 0: # this is a barrier or measure
n_regs = random.randint(1, n_qubits)
if n_qubits >= n_regs:
# warning: assumes op function signature specifies
# op parameters before qubits
op_args = []
if n_params:
op_args = [random.random() for _ in range(n_params)]
if op_name == 'measure':
# if measure occurs here, assume it's to do a conditional
# randomly select a register to measure
ireg = random.randint(0, n_registers-1)
qreg = circuit.qregs[ireg]
creg = circuit.cregs[ireg]
for qind in range(qreg.size):
operator(qreg[qind], creg[qind])
ifval = random.randint(0, (1 << qreg.size) - 1)
# TODO: replace choices with random.choices() when
# python 3.6 is required.
uop_name = choices(uop_basis, weights=uop_basis_weights)[0]
if hasattr(circuit, uop_name):
uop = getattr(circuit, uop_name)
else:
raise AttributeError('operation \"{0}\"'
' not recognized'.format(uop_name))
unregs = self.op_signature[uop_name]['nregs']
unparams = self.op_signature[uop_name]['nparams']
if unregs == 0: # this is a barrier or measure
unregs = random.randint(1, n_qubits)
if qreg.size >= unregs:
qind_list = random.sample(range(qreg.size), unregs)
uop_args = []
if unparams:
uop_args = [random.random() for _ in range(unparams)]
uop_args.extend([qreg[qind] for qind in qind_list])
uop(*uop_args).c_if(creg, ifval)
depth_cnt -= 1
elif op_name == 'barrier':
ireg = random.randint(0, n_registers-1)
qreg = circuit.qregs[ireg]
bar_args = [(qreg, mi) for mi in range(qreg.size)]
operator(*bar_args)
else:
# select random register
ireg = random.randint(0, n_registers-1)
qreg = circuit.qregs[ireg]
if qreg.size >= n_regs:
qind_list = random.sample(range(qreg.size), n_regs)
op_args.extend([qreg[qind] for qind in qind_list])
operator(*op_args)
depth_cnt -= 1
else:
break
nmeasure = random.randint(1, n_qubits)
m_list = random.sample(range(nmeasure), nmeasure)
if do_measure:
for qind in m_list:
rind = 0 # register index
cumtot = 0
while qind >= cumtot + circuit.qregs[rind].size:
cumtot += circuit.qregs[rind].size
rind += 1
qrind = int(qind - cumtot)
qreg = circuit.qregs[rind]
creg = circuit.cregs[rind]
circuit.measure(qreg[qrind], creg[qrind])
self.circuit_list.append(circuit)
def min_regs_exceeds_nqubits(self, basis, n_qubits):
"""Check whether the minimum number of qubits used by the operations
in basis is between 1 and the number of qubits.
Args:
basis (list): list of basis names
n_qubits (int): number of qubits in circuit
Returns:
boolean: result of the check.
"""
return not any((n_qubits >= self.op_signature[opName]['nregs'] > 0
for opName in basis))
def get_circuits(self):
"""Get random circuits
Returns:
list: List of QuantumCircuit objects.
"""
return self.circuit_list
def rand_register_sizes(n_registers, pvals):
"""Return a randomly chosen list of nRegisters summing to nQubits."""
vector = numpy.random.multinomial(n_registers, pvals)
return vector[vector.nonzero()]
|
https://github.com/goodrahstar/hello-quantum-world
|
goodrahstar
|
pip install pylatexenc
!pip install qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_histogram
# Create a Quantum Register called "qr" with 2 qubits.
qr = QuantumRegister(2,'qr')
# Create a Classical Register called "cr" with 2 bits.
cr = ClassicalRegister(2,'cr')
qc = QuantumCircuit(qr,cr)
# Add the H gate in the Qubit 1, putting this qubit in superposition.
qc.h(qr[1])
# Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement
qc.cx(qr[1], qr[0])
# Add a Measure gate to see the state.
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
# Compile and execute the Quantum Program in the ibmqx5
qc.draw(output='mpl')
qasm_simulator = Aer.get_backend('qasm_simulator')
shots = 1024
result = results = execute(qc, backend=qasm_simulator, shots=shots).result()
Ans=result.get_counts()
plot_histogram(Ans)
|
https://github.com/lvillasen/Introduccion-a-la-Computacion-Cuantica
|
lvillasen
|
!pip install numpy
import numpy as np
print(np.round(np.pi,4))
lista = [0,1,2,3,4,5]
print(lista[1])
print(lista[0:-1])
for i in range(5):
print("Hola mundo i=%d" %i)
lista = [i for i in range(10)]
lista
import matplotlib.pyplot as plt
plt.plot(lista)
plt.draw()
i = 10
while (i < 15):
print(i,end=",")
i = i + 1
def f(x):
return 2*x
f(3)
a = np.array([1,3,5.31,2,-10.3])
print("El mínimo es %2.3f y el mínimo %2.3e" %(a.min(),a.max()))
b=np.where(a<3) # da los índices donde se cumple la condición
print(b)
a = [1,3,5,2,0]
for i in a:
if i < 3 :
print(i, " es < que 3")
else:
print(i, " es >= que 3")
!pip install qiskit[machine-learning]
!pip install pylatexenc # instalamos la librería *pylatexenc* para dibujar circuitos con matplotlib
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, Aer
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)
# Ahora hacemos mediciones de cada qubit
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
qc.draw(output='mpl')
from qiskit import QuantumCircuit, Aer
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)
# Ahora hacemos mediciones de cada qubit
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3)
for qubit in range(3):
qc.h(qubit)
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1)
qc.measure(0,0)
qc.draw("mpl")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(1,1)
qc.ry(-np.pi/2,0)
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1)
qc.ry(np.pi/2,0)
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv)
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=471)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import IBMQ
#IBMQ.save_account('CLAVE', overwrite=True)
from qiskit import IBMQ
IBMQ.load_account() # Load account from disk
print(IBMQ.providers()) # List all available providers
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op = X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|Op|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = Zero
from IPython.display import display, Latex,Math
display(Math('|\psi> = |0>'))
display(Latex(f'$<\psi|XX|\psi>$'))
print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = One
from IPython.display import display, Latex,Math
display(Math('|\psi> = |1>'))
display(Latex(f'$<\psi|XX|\psi>$'))
print("=",np.round(psi.adjoint().compose(X).compose(X).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Y).compose(Y).compose(psi).eval().real,1))
display(Latex(f'$<\psi|YY|\psi>$'))
print("=",np.round(psi.adjoint().compose(Z).compose(Z).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^One ^ Zero^ Zero) - (Zero ^Zero ^ One^ One))
op1 = -0.8105479805373275 * I^I^I^I + 0.1721839326191556 * I^I^I^Z - 0.2257534922240239 * I^I^Z^I \
+ 0.17218393261915554 * I^Z^I^I - 0.2257534922240239 * Z^I^I^I
# Step 1: Define operator
op = SparsePauliOp.from_list(
[
("IIII", -0.8105479805373275),
("IIIZ", + 0.1721839326191556),
("IIZI", - 0.2257534922240239),
("IZII", + 0.17218393261915554),
("ZIII", - 0.2257534922240239),
("IIZZ", + 0.12091263261776629),
("IZIZ", + 0.16892753870087907),
("YYYY", + 0.04523279994605784),
("XXYY", + 0.04523279994605784),
("YYXX", + 0.04523279994605784),
("XXXX", + 0.04523279994605784),
("ZIIZ", + 0.16614543256382414),
("IZZI", +0.16614543256382414),
("ZIZI", + 0.17464343068300445),
("ZIZI", + 0.12091263261776629),
]
)
# Step 2: Define quantum state
state = QuantumCircuit(4)
state.h(0)
state.h(1)
state.x(2)
from qiskit.primitives import Estimator
estimator = Estimator()
expectation_value = estimator.run(state, op).result().values
# for shot-based simulation:
expectation_value = estimator.run(state, op, shots=1000).result().values
print("expectation: ", expectation_value)
print("=",np.round(psi.adjoint().compose(op1).compose(psi).eval().real,16))
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.z(1) # NOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.x(1) # NOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.x(1) # NOT gate
qc.z(1) # Z gate
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
from IPython.display import display, Latex,Math
Op1 = X^X
Op2 = Y^Y
Op3 = Z^Z
for j in range(4):
if j == 0:
psi = 1 / np.sqrt(2) * ((Zero^ Zero) + (One^ One))
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>+|1>|1>)'))
if j == 1:
psi = 1 / np.sqrt(2) * ((Zero^ Zero) - (One^ One))
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>-|1>|1>)'))
if j == 2:
psi = 1 / np.sqrt(2) * ((Zero^ One) + (One^ Zero))
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>+|1>|0>)'))
if j == 3:
psi = 1 / np.sqrt(2) * ((Zero^ One) - (One^ Zero))
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|1>-|1>|0>)'))
display(Latex(f'$<\psi|2(X\otimes X+Y\otimes Y+Z\otimes Z)|\psi>$'))
print("=",2*(np.round(psi.adjoint().compose(Op1).compose(psi).eval().real,1)
+np.round(psi.adjoint().compose(Op2).compose(psi).eval().real,1)+
np.round(psi.adjoint().compose(Op3).compose(psi).eval().real,1)),"\n")
from qiskit import QuantumCircuit, Aer,transpile
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
qc.measure(qubit,qubit)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
print(job.result().get_counts())
plot_histogram(job.result().get_counts())
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
#IBMQ.save_account('CLAVE', overwrite=True)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
sim_backend = AerSimulator.from_backend(backend)
print("least busy backend: ", sim_backend)
# Transpile the circuit for the noisy basis gates
tqc = transpile(qc, sim_backend,optimization_level=3)
# Execute noisy simulation and get counts
job = sim_backend.run(tqc,shots=1000)
print("Counts for 3-qubit GHZ state with simulated noise model for", backend)
plot_histogram(job.result().get_counts())
tqc.draw("mpl")
from qiskit import QuantumCircuit, Aer,transpile
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
qc.measure(qubit,qubit)
qc.draw("mpl")
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
# Load local account information
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit
tqc = transpile(qc, backend, optimization_level=3)
job = backend.run(tqc,shots = 100)
from qiskit.providers.jobstatus import JobStatus
print(job.status(),job.queue_position())
print("Counts for 3-qubit GHZ state with real computer", backend)
plot_histogram(job.result().get_counts())
import numpy as np
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import random_statevector
psi = random_statevector(2)
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(psi)
from qiskit import QuantumCircuit, assemble, Aer
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,2)
qc.initialize(psi, 0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.measure(1,1)
qc.draw("mpl")
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)
stv.draw('latex', prefix='Estado \quad del \quad sistema \quad de \quad 3 \quad qubits \quad = \quad')
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1)
print(job.result().get_counts(qc))
plot_histogram(job.result().get_counts())
import qiskit.quantum_info as qi
import numpy as np
qc1 = QuantumCircuit(3,2)
print(job.result().get_counts())
for key in job.result().data()["counts"]:
if int(key,0) == 0 :
print("El resultado es 00")
q2_state = [np.round(stv[0],3),np.round(stv[4],3)]
qc1.initialize(0, 0)
qc1.initialize(0, 1)
elif int(key,0) == 1 :
print("El resultado es 01")
q2_state = [np.round(stv[1],3),np.round(stv[5],3)]
qc1.initialize(1, 0)
qc1.initialize(0, 1)
elif int(key,0) == 2 :
print("El resultado es 10")
q2_state = [np.round(stv[2],3),np.round(stv[6],3)]
qc1.initialize(0, 0)
qc1.initialize(1, 1)
elif int(key,0) == 3 :
print("El resultado es 11")
q2_state = [np.round(stv[3],3),np.round(stv[7],3)]
qc1.initialize(1, 0)
qc1.initialize(1, 1)
q2_normalizado = q2_state/np.linalg.norm(q2_state)
qc1.barrier()
qc1.initialize(q2_normalizado, 2)
for key in job.result().data()["counts"]:
if int(key,0) == 1 :
qc1.z(2)
if int(key,0) == 2 :
qc1.x(2)
if int(key,0) == 3 :
qc1.x(2)
qc1.z(2)
stv1 = qi.Statevector.from_instruction(qc1)
stv1.draw('latex', prefix='Estado \quad del \quad qubit \quad 2 = ')
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv1)
import qiskit.quantum_info as qi
import numpy as np
qc2 = QuantumCircuit(3,2)
for key in job.result().data(qc)["counts"]:
if int(key,0) != 0 :
qc2.initialize(psi, 2)
qcc = qc.compose(qc1)
qc3 = qcc.compose(qc2)
qc3.draw("mpl")
from qiskit import QuantumCircuit, assemble, Aer
from qiskit import IBMQ, transpile
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
theta=np.pi*np.random.rand()
phi = 2*np.pi*np.random.rand()
print("theta =",np.round(theta,2),"rad, theta =",np.round(180*theta/np.pi,2),"grados")
print("phi=",np.round(phi,2),"rad, phi =",np.round(180*phi/np.pi,2),"grados")
qc = QuantumCircuit(3,3)
qc.ry(theta,0)
qc.rz(phi,0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
qc.rz(-phi,2)
qc.ry(-theta,2)
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(stv0)
backend = Aer.get_backend('qasm_simulator')
job = backend.run(qc, shots=1000)
#print(job.result().get_counts(qc))
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))
states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()
#plot_histogram(job.result().get_counts())
from qiskit_aer import AerSimulator
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
sim_backend = AerSimulator.from_backend(backend)
print("least busy backend: ", sim_backend,"\n\n")
# Transpile the circuit for the noisy basis gates
tqc = transpile(qc, sim_backend,optimization_level=3)
# Execute noisy simulation and get counts
job = sim_backend.run(tqc,shots=1000)
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
try :
n_error = job.result().get_counts(qc)['100']
except:
n_error = 0
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,6))
states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()
tqc.draw("mpl")
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
tqc = transpile(qc, backend, optimization_level=3)
job_teleportation = backend.run(tqc,shots = 1000)
print(job_teleportation.status(),job_teleportation.queue_position())
print(job_teleportation.result().get_counts(),"\n\n")
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,8))
states = ['000', '100']
counts = [job.result().get_counts(qc)['000'],n_error]
plt.rcParams.update({'font.size': 20})
plt.bar(states,counts,width=0.4, bottom=None,align='center', data=None)
for index, value in enumerate(counts):
plt.text(index, value, str(value),fontsize=20)
plt.xlabel('States',fontsize=20)
plt.ylabel('Counts',fontsize=20)
plt.show()
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
backend = Aer.get_backend('qasm_simulator')
N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print(" Experimento A1B1")
qc11=qc
print(qc11)
qc11=qc.compose(qc3)
job11 = execute(qc11,backend, shots=1000)
result = job11.result()
print("Resultados :",result.get_counts(qc11))
if job11.result().get_counts().get('11') is not None:
N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']
print()
print(" Experimento A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
job12 = execute(qc12,backend, shots=1000)
result = job12.result()
print("Resultados :",result.get_counts(qc12))
N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']
print()
print(" Experimento A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
job13 = execute(qc13,backend, shots=1000)
result = job13.result()
print("Resultados :",result.get_counts(qc13))
N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']
print()
print(" Experimento A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
job21 = execute(qc21,backend, shots=1000)
result = job21.result()
print("Resultados :",result.get_counts(qc21))
N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']
print()
print(" Experimento A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
job22 = execute(qc22,backend, shots=1000)
result = job22.result()
print("Resultados :",result.get_counts(qc22))
if job22.result().get_counts().get('11') is not None:
N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']
print()
print(" Experimento A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
job23 = execute(qc23,backend, shots=1000)
result = job23.result()
print("Resultados :",result.get_counts(qc23))
N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']
print()
print(" Experimento A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
job31 = execute(qc31,backend, shots=1000)
result = job31.result()
print("Resultados :",result.get_counts(qc31))
N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']
print()
print(" Experimento A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
job32 = execute(qc32,backend, shots=1000)
result = job31.result()
print("Resultados :",result.get_counts(qc32))
N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']
print()
print(" Experimento A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
job33 = execute(qc33,backend, shots=1000)
result = job33.result()
print("Resultados :",result.get_counts(qc33))
if job33.result().get_counts().get('11') is not None:
N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']
print("Total correlated:", N_corr, " Total anti-correlated:", N_anticorr)
from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
IBMQ.save_account('your-IBMQ-password', overwrite=True)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
backend = AerSimulator.from_backend(backend)
shots = 1000
N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print(" Experiment A1B1")
qc11=qc
qc11=qc.compose(qc3)
print(qc11)
tqc11 = transpile(qc11, backend, optimization_level=3)
job11 = backend.run(tqc11,shots =shots)
print("Results :",job11.result().get_counts())
if job11.result().get_counts().get('11') is not None:
N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']
print("\n Experiment A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
tqc12 = transpile(qc12, backend, optimization_level=3)
job12 = backend.run(tqc12,shots =shots)
print("Results :",job12.result().get_counts())
N_corr += job12.result().get_counts()['11']+job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']
print("\n Experiment A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
tqc13 = transpile(qc13, backend, optimization_level=3)
job13 = backend.run(tqc13,shots =shots)
print("Results :",job13.result().get_counts())
N_corr += job13.result().get_counts()['11']+job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']
print("\n Experiment A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
tqc21 = transpile(qc21, backend, optimization_level=3)
job21 = backend.run(tqc21,shots =shots)
print("Results :",job21.result().get_counts())
N_corr += job21.result().get_counts()['11']+job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']
print("\n Experiment A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
tqc22 = transpile(qc22, backend, optimization_level=3)
job22 = backend.run(tqc22,shots =shots)
print("Results :",job22.result().get_counts())
if job22.result().get_counts().get('11') is not None:
N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']
print("\n Experiment A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
tqc23 = transpile(qc23, backend, optimization_level=3)
job23 = backend.run(tqc23,shots =shots)
print("Results :",job23.result().get_counts())
N_corr += job23.result().get_counts()['11']+job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']
print("\n Experiment A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
tqc31 = transpile(qc31, backend, optimization_level=3)
job31 = backend.run(tqc31,shots =shots)
print("Results :",job31.result().get_counts())
N_corr += job31.result().get_counts()['11']+job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']
print("\n Experiment A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
tqc32 = transpile(qc32, backend, optimization_level=3)
job32 = backend.run(tqc32,shots =shots)
print("Results :",job32.result().get_counts(qc32))
N_corr += job32.result().get_counts()['11']+job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']
print("\n Experiment A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
tqc33 = transpile(qc33, backend, optimization_level=3)
job33 = backend.run(tqc33,shots =shots)
print("Results :",job33.result().get_counts(qc33))
if job33.result().get_counts().get('11') is not None:
N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']
print("\nOut of a total of",9*shots,"measurements, we obtained")
print("Total correlated measurements:", N_corr)
print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%")
from qiskit import IBMQ, Aer
from qiskit_aer.noise import NoiseModel
IBMQ.save_account('your-IBMQ-password', overwrite=True)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_manila')
noise_model = NoiseModel.from_backend(backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
IBMQ.load_account()
# Get the least busy backend
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
print("----------Noise Model for",backend,"--------------\n",noise_model)
from qiskit import QuantumCircuit, Aer
import qiskit.quantum_info as qi
import numpy as np
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.z(1)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.draw("mpl")
stv.draw('latex', prefix="|\\psi\\rangle =")
shots = 1000
N_corr = 0
N_anticorr = 0
qc3 = QuantumCircuit(2, 2)
qc3.measure(0,0)
qc3.measure(1,1)
print(" Experiment A1B1")
qc11=qc
qc11=qc.compose(qc3)
print(qc11)
tqc11 = transpile(qc11, backend, optimization_level=3)
job11 = backend.run(tqc11,shots =shots)
print("\n Experiment A1B2")
qc12 = QuantumCircuit(2, 2)
qc12.rz(0,1)
qc12.ry(-2*np.pi/3,1)
qc12.barrier()
qc12=qc.compose(qc12)
qc12=qc12.compose(qc3)
print(qc12)
tqc12 = transpile(qc12, backend, optimization_level=3)
job12 = backend.run(tqc12,shots =shots)
print("\n Experiment A1B3")
qc13 = QuantumCircuit(2, 2)
qc13.rz(-np.pi,1)
qc13.ry(-2*np.pi/3,1)
qc13.barrier()
qc13=qc.compose(qc13)
qc13=qc13.compose(qc3)
print(qc13)
tqc13 = transpile(qc13, backend, optimization_level=3)
job13 = backend.run(tqc13,shots =shots)
print("\n Experiment A2B1")
qc21 = QuantumCircuit(2, 2)
qc21.rz(0,0)
qc21.ry(-2*np.pi/3,0)
qc21.barrier()
qc21=qc.compose(qc21)
qc21=qc21.compose(qc3)
print(qc21)
tqc21 = transpile(qc21, backend, optimization_level=3)
job21 = backend.run(tqc21,shots =shots)
print("\n Experiment A2B2")
qc22 = QuantumCircuit(2, 2)
qc22.rz(0,0)
qc22.ry(-2*np.pi/3,0)
qc22.rz(0,1)
qc22.ry(-2*np.pi/3,1)
qc22.barrier()
qc22=qc.compose(qc22)
qc22=qc22.compose(qc3)
print(qc22)
tqc22 = transpile(qc22, backend, optimization_level=3)
job22 = backend.run(tqc22,shots =shots)
from qiskit.providers.jobstatus import JobStatus
print(job11.status(),job11.queue_position())
print(job12.status(),job12.queue_position())
print(job13.status(),job13.queue_position())
print(job21.status(),job21.queue_position())
print(job22.status(),job22.queue_position())
print("\n Experiment A2B3")
qc23 = QuantumCircuit(2, 2)
qc23.rz(0,0)
qc23.ry(-2*np.pi/3,0)
qc23.rz(-np.pi,1)
qc23.ry(-2*np.pi/3,1)
qc23.barrier()
qc23=qc.compose(qc23)
qc23=qc23.compose(qc3)
print(qc23)
tqc23 = transpile(qc23, backend, optimization_level=3)
job23 = backend.run(tqc23,shots =shots)
print("\n Experiment A3B1")
qc31 = QuantumCircuit(2, 2)
qc31.rz(-np.pi,0)
qc31.ry(-2*np.pi/3,0)
qc31.barrier()
qc31=qc.compose(qc31)
qc31=qc31.compose(qc3)
print(qc31)
tqc31 = transpile(qc31, backend, optimization_level=3)
job31 = backend.run(tqc31,shots =shots)
print("\n Experiment A3B2")
qc32 = QuantumCircuit(2, 2)
qc32.rz(-np.pi,0)
qc32.ry(-2*np.pi/3,0)
qc32.rz(0,1)
qc32.ry(-2*np.pi/3,1)
qc32.barrier()
qc32=qc.compose(qc32)
qc32=qc32.compose(qc3)
print(qc32)
tqc32 = transpile(qc32, backend, optimization_level=3)
job32 = backend.run(tqc32,shots =shots)
print("\n Experiment A3B3")
qc33 = QuantumCircuit(2, 2)
qc33.rz(-np.pi,0)
qc33.ry(-2*np.pi/3,0)
qc33.rz(-np.pi,1)
qc33.ry(-2*np.pi/3,1)
qc33.barrier()
qc33=qc.compose(qc33)
qc33=qc33.compose(qc3)
print(qc33)
tqc33 = transpile(qc33, backend, optimization_level=3)
job33 = backend.run(tqc33,shots =shots)
print(job23.status(),job23.queue_position())
print(job31.status(),job31.queue_position())
print(job32.status(),job32.queue_position())
print(job33.status(),job33.queue_position())
N_corr = 0
N_anticorr = 0
print(" Experiment A1B1")
print("Results :",job11.result().get_counts())
if job11.result().get_counts().get('11') is not None:
N_corr += job11.result().get_counts()['11']
if job11.result().get_counts().get('00') is not None:
N_corr += job11.result().get_counts()['00']
N_anticorr += job11.result().get_counts()['01']+job11.result().get_counts()['10']
print(" Experiment A1B2")
print("Results :",job12.result().get_counts())
N_corr += job12.result().get_counts()['11']
N_corr += job12.result().get_counts()['00']
N_anticorr += job12.result().get_counts()['01']+job12.result().get_counts()['10']
print(" Experiment A1B3")
print("Results :",job13.result().get_counts())
N_corr += job13.result().get_counts()['11']
N_corr += job13.result().get_counts()['00']
N_anticorr += job13.result().get_counts()['01']+job13.result().get_counts()['10']
print(" Experiment A2B1")
print("Results :",job21.result().get_counts())
N_corr += job21.result().get_counts()['11']
N_corr += job21.result().get_counts()['00']
N_anticorr += job21.result().get_counts()['01']+job21.result().get_counts()['10']
print(" Experiment A2B2")
print("Results :",job22.result().get_counts())
if job22.result().get_counts().get('11') is not None:
N_corr += job22.result().get_counts()['11']
if job22.result().get_counts().get('00') is not None:
N_corr += job22.result().get_counts()['00']
N_anticorr += job22.result().get_counts()['01']+job22.result().get_counts()['10']
print(" Experiment A2B3")
print("Results :",job23.result().get_counts())
N_corr += job23.result().get_counts()['11']
N_corr += job23.result().get_counts()['00']
N_anticorr += job23.result().get_counts()['01']+job23.result().get_counts()['10']
print(" Experiment A3B1")
print("Results :",job31.result().get_counts())
N_corr += job31.result().get_counts()['11']
N_corr += job31.result().get_counts()['00']
N_anticorr += job31.result().get_counts()['01']+job31.result().get_counts()['10']
print(" Experiment A3B2")
print("Results :",job32.result().get_counts())
N_corr += job32.result().get_counts()['11']
N_corr += job32.result().get_counts()['00']
N_anticorr += job32.result().get_counts()['01']+job32.result().get_counts()['10']
print(" Experiment A3B3")
print("Results :",job33.result().get_counts())
if job33.result().get_counts().get('11') is not None:
N_corr += job33.result().get_counts()['11']
if job33.result().get_counts().get('00') is not None:
N_corr += job33.result().get_counts()['00']
N_anticorr += job33.result().get_counts()['01']+job33.result().get_counts()['10']
print("\nOut of a total of",9*shots,"measurements, we obtained")
print("Total correlated measurements:", N_corr)
print("Total anti-correlated measurements:", N_anticorr," corresponding to ",np.round(100*N_anticorr/(9*shots),2),"%")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1000)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
from qiskit import QuantumCircuit, Aer,execute
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(1,1) # Ponemos 1 qubit y 1 bit
psi = [np.cos(2*np.pi/3/2),np.sin(2*np.pi/3/2)]
qc.initialize(psi, 0)
stv = qi.Statevector.from_instruction(qc)
stv.draw('latex', prefix="|\\psi\\rangle =")
qc.measure(0,0)
qc.draw(output='mpl')
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(psi)
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
n_shots = 1000
job = execute(qc,backend, shots=n_shots, memory=True)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))
Data =result.get_memory()
np.array(list(map(int, Data)))
print(np.array(list(map(int, Data))))
print("Suma de 1s =",sum(np.array(list(map(int, Data)))),"Suma de 0s =",n_shots-sum(np.array(list(map(int, Data)))))
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(2,2) # Ponemos 2 qubits y 2 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(2):
qc.measure(qubit,qubit)
qc.draw("mpl")
from qiskit import QuantumCircuit, Aer,execute
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,3) # Ponemos 3 qubits y 3 bits
# Aplicamos algunas compuertas
qc.h(0) # Hadamard gate
qc.cx(0,1) # CNOT gate
qc.cx(1,2) # CNOT gate
stv = qi.Statevector.from_instruction(qc)
for qubit in range(3):
qc.measure(qubit,qubit)
qc.draw("mpl")
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op = X^Y^Y +X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
display(Latex(f'$<\psi|Op|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
import numpy as np
from qiskit.opflow import Z, X,Y,I, Zero, One
#operator = (X+X)** +(Y+Y)**2 +(Z+Z)**2
operator = X
psi = 1 / np.sqrt(2) * ((Zero + One))
expectation_value = (~psi @ operator @ psi).eval()
print(expectation_value.real)
psi = 1 / np.sqrt(2) * ((Zero - One))
expectation_value = (psi.adjoint() @ operator @ psi).eval()
print(expectation_value.real)
# Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf
import numpy as np
from qiskit.opflow import Z, X,Y,I, Zero, One
operator = np.sin(2*np.pi/3)*X^Z+np.cos(2*np.pi/3)*Z^Z
psi = 1 / np.sqrt(2) * ((Zero ^ One) - (One ^ Zero))
expectation_value = (psi.adjoint() @ operator @ psi).eval()
print(expectation_value.real)
# Para más detalles ver https://arxiv.org/pdf/2206.14584.pdf
from qiskit import QuantumCircuit, assemble, Aer
import qiskit.quantum_info as qi
import numpy as np
import qiskit.quantum_info as qi
qc = QuantumCircuit(3,2)
qc.initialize([1/np.sqrt(2),1/np.sqrt(2)], 0)
stv0 = qi.Statevector.from_instruction(qc)
qc.barrier()
qc.h(1) # Hadamard
qc.cx(1,2) # CNOT
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.barrier()
stv = qi.Statevector.from_instruction(qc)
qc.measure(0,0)
qc.measure(1,1)
qc.draw("mpl")
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))
from qiskit.opflow import CircuitStateFn
import qiskit.quantum_info as qi
import numpy as np
psi=QuantumCircuit(3)
psi.h(0) # Hadamard gate
psi.cx(0,1) # CNOT gate
psi.cx(1,2) # CNOT gate
stv0 = qi.Statevector.from_instruction(psi)
psi=CircuitStateFn(psi)
stv0.draw('latex', prefix="|\\psi\\rangle =")
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes X\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.y(0)
qc.y(1)
qc.x(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|X\otimes Y\otimes Y|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.y(0)
qc.x(1)
qc.y(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|Y\otimes X\otimes Y|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp
qc=QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.y(2)
op=CircuitOp(qc)
from IPython.display import display, Latex
display(Latex(f'$<\psi|Y\otimes Y\otimes X|\psi>$'))
print("=",np.round(psi.adjoint().compose(op).compose(psi).eval().real,1))
from qiskit import QuantumCircuit
from qiskit.opflow import CircuitOp,Zero, One, Z, X,Y,I
import numpy as np
psi = 1 / np.sqrt(2) * ((One ^ One^ One) + (Zero ^ Zero^ Zero))
op = X^X^X
from IPython.display import display, Latex,Math
display(Math('|\psi> = \\frac{1}{\sqrt{2}}(|0>|0>|0>+|1>|1>|1>)'))
for i in range(4):
if i==0: Op = X^X^X
if i==1: Op = X^Y^Y
if i==2: Op = Y^X^Y
if i==3: Op = Y^Y^X
print("\nOp =",Op)
display(Latex(f'$<\psi|Op|\psi>$'))
print("=",np.round(psi.adjoint().compose(Op).compose(psi).eval().real,1))
# Código tomado de https://github.com/lvillasen/Euclidean-Algorithm
def f(i,N1,N2,n1,n2,c1,c2):
n3=n1%n2
e3 = n1//n2
c3 = c1 -e3*c2
print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
return N1,N2,n2,n3,c2,c3
# Input the two integers here (N1 >N2)
N1 = 51
N2 = 13
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:
print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')
print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')
print("\nGCD(",N1, "," ,N2,") = ",n2)
p =3490529510847650949147849619903898133417764638493387843990820577
q = 32769132993266709549961988190834461413177642967992942539798288533
N = p*q
y = 200805001301070903002315180419000118050019172105011309190800151919090618010705
# Código tomado de https://github.com/lvillasen/Euclidean-Algorithm
def f(i,N1,N2,n1,n2,c1,c2):
n3=n1%n2
e3 = n1//n2
c3 = c1 -e3*c2
print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
return N1,N2,n2,n3,c2,c3
# Input the two integers here (N1 >N2)
N1 = (p-1)*(q-1)
N2 = 9007
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:
print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')
print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')
# Código tomado de https://github.com/jacksoninfosec/youtube-videos/blob/master/modular_exp.py
# https://www.youtube.com/watch?v=3Bh7ztqBpmw
def mod_power(a, n, m):
r = 1
while n > 0:
if n & 1 == 1:
r = (r * a) % m
a = (a * a) % m
n >>= 1
return r
p =3490529510847650949147849619903898133417764638493387843990820577
q = 32769132993266709549961988190834461413177642967992942539798288533
N = p*q
y = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154
d = 106698614368578024442868771328920154780709906633937862801226224496631063125911774470873340168597462306553968544513277109053606095
m = mod_power(y, d, N)
print("m=",m)
s = str(m)
list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(s)//2):
print(s[2*i:2*i+2],end =" ")
print()
list =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(s)//2):
print(list[int(s[2*i:2*i+2])],end =" ")
p = 1000003
q = 1000291
N = p*q
a =2
def f(i,N1,N2,n1,n2,c1,c2):
n3=n1%n2
e3 = n1//n2
c3 = c1 -e3*c2
print("\t\t",n3,"= ",n1,"-",e3,"*",n2," (mod N1)")
print("(",i,")\t",n3,"= ",c3,"*",N2," (mod N1)")
return N1,N2,n2,n3,c2,c3
# Input the two integers here (N1 >N2)
N1 = N
N2 = a
n1,n2,c1,c2 = N1,N2,0,1
print("( 1 )\t",N1,"= 0 (mod",N1,")")
print("( 2 )\t",N2,"= ",N2," (mod",N1,")")
i=3
while n2>1:
N1,N2,n1,n2,c1,c2 = f(i,N1,N2,n1,n2,c1,c2)
i+=1
if n2 == 0: print("\nThe greatest common divisor (GCD) of ",N1, " and " ,N2," is ",n1)
if n2 == 1:
print("\nThe inverse multiplicative of ",N2, " (mod ",N1,") is ",c2%N1,sep='')
print("i.e., ",N2, " * ",c2%N1, " = 1 (mod ",N1,")" ,sep='')
print("\n",N2, " y ",N1," son coprimos ")
import numpy as np
def mod_power(a, n, m):
r = 1
while n > 0:
if n & 1 == 1:
r = (r * a) % m
a = (a * a) % m
n >>= 1
return r
a=2
a = 3
p = 1000003
p=347# 1931 , 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999
q = 307 #, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
#p=61
q = 1931
p= 1933
N = p*q
N = 15
a=4
print("N =",N,"a =",a," MCD(a,N)=",np.gcd(a,N))
#dat = [a**i % N for i in range(100)]
i=2
while (mod_power(a, i, N)) > 1:
#while (a**i % N) > 1:
i += 2
r = i
print("Periodo = ",r)
dat = [a**i % N for i in range(3*r)]
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 8))
plt.plot(dat,'-*b')
plt.grid()
plt.draw()
p= 122949829
q = 141650939
N = p*q
i=3
while (N %i != 0):
i += 2
print("Factores : ",i,N//i)
import numpy as np
print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N))
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
def x(t):
return 1+2*np.cos(2*np.pi*5*t)+3*np.sin(2*np.pi*7*t)
T = 1
sr = 40
ts = np.linspace(0, T, sr*T)
t = np.linspace(0, T, 1000)
Corr_cos=np.zeros((sr*T))
Corr_sen=np.zeros((sr*T))
N=np.arange(0, sr*T)
def Grafica(n):
ax[0].clear()
ax[1].clear()
frec = n/T
Corr_cos[n] = np.dot(x(ts),np.cos(-2*np.pi*n*ts/T))
Corr_sen[n] = np.dot(x(ts),np.sin(-2*np.pi*n*ts/T))
ax[0].plot(t, x(t),'b')
ax[0].plot(t, np.cos(2*np.pi*n*t/T),'r')
ax[0].plot(t, np.sin(2*np.pi*n*t/T),'g')
ax[0].plot(ts, x(ts),'.b',ms=10)
ax[0].plot(ts, np.cos(2*np.pi*n*ts/T),'.r',ms=10)
ax[0].plot(ts, np.sin(2*np.pi*n*ts/T),'.g',ms=10)
#ax[1].title('Frecuencia Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18)
ax[0].set_xlabel('t', fontsize=18)
ax[0].set_ylabel('x(t)', fontsize=18)
ax[0].grid()
ax[1].plot(N, Corr_cos,'-r',ms=10,label='Corr Cos para k={}'.format(n))
ax[1].plot(N, Corr_sen,'-.g',ms=10,label='Corr Sen para k={}'.format(n))
#ax[2].title('Frecuencia Señal de Correlación = {}'.format(frec)+ ' Hz, GS'+'= {}'.format(np.round(GS,1)), fontsize=18)
ax[1].set_xlabel('k', fontsize=18)
ax[1].set_ylabel(r'$X_k$', fontsize=18)
ax[1].grid()
ax[1].legend()
fig=plt.figure(figsize=(10,6), dpi= 100)
ax= fig.subplots(2,1)
anim = animation.FuncAnimation(fig, Grafica, frames=40 , interval=800)
plt.close()
HTML(anim.to_html5_video())
from qiskit.circuit import Gate
U_f = Gate(name='U_f', num_qubits=2, params=[])
import qiskit as qk
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
from qiskit import *
qc = QuantumCircuit(8, 8)
for q in range(4):
qc.h(q)
# And auxiliary register in state |1>
qc.append(U_f [qr[0], qr[1]])
qc.barrier()
qc.measure(range(4), range(4))
style = {'backgroundcolor': 'lightgreen'}
qc.draw('mpl',fold=-1,style=style) # -1 means 'do not fold'
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
import qiskit.quantum_info as qi
from math import gcd
from numpy.random import randint
from fractions import Fraction
print("Imports Successful")
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.x(0)
qc.y(1)
qc.z(2)
qc.h(3)
stv = qi.Statevector.from_instruction(qc)
## Create 7mod15 gate
N = 15
m = int(np.ceil(np.log2(N)))
import qiskit.quantum_info as qi
U_qc = QuantumCircuit(m)
#U_qc.x(0)
U_qc.initialize('0010')
U_qc.swap(0, 1)
U_qc.swap(1, 2)
U_qc.swap(2, 3)
for q in range(4):
U_qc.x(q)
#U = U_qc.to_gate()
stv = qi.Statevector.from_instruction(U_qc)
#U.name ='{}Mod{}'.format(7, N)
U_qc.draw('mpl',fold=-1,style=style)
stv.draw('latex', prefix="|\\psi\\rangle =")
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,4,7,8,11,13]:
raise ValueError("'a' must be 2,4,7,8,11 or 13")
U = QuantumCircuit(4)
for iteration in range(power):
if a in [2,13]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a in [7,8]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [4, 11]:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
# Specify variables
n_count = 8 # number of counting qubits
a = 7
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count+ 4)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(n_count)
qc.barrier()
stv1 = qi.Statevector.from_instruction(qc)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.barrier()
stv2 = qi.Statevector.from_instruction(qc)
#for qubit in range(8,12):
# qc.measure(qubit,qubit)
qc.barrier()
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
style = {'backgroundcolor': 'lightgreen'}
qc.draw('mpl',fold=-1,style=style) # -1 means 'do not fold'
stv1.draw('latex', prefix="|\\psi\\rangle =")
stv2.draw('latex', prefix="|\\psi\\rangle =")
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
import cmath
a = 2
def suma(i):
b=0
for a in range(86):
b+= cmath.exp(-2*np.pi*1j*6*i*a/512)
return abs(b)**2
dat = [suma(i) for i in range(512)]
probability = np.array(dat)/512/86
import plotly.express as px
fig=px.line(probability,markers=True)
fig.show()
import numpy as np
a=2
N=21
r=6
print("Los factores primos son:",np.gcd(a**(r//2) +1,N),np.gcd(a**(r//2) -1,N))
# Importing everything
from qiskit import QuantumCircuit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
def create_bell_pair():
"""
Returns:
QuantumCircuit: Circuit that produces a Bell pair
"""
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
"""Encodes a two-bit message on qc using the superdense coding protocol
Args:
qc (QuantumCircuit): Circuit to encode message on
qubit (int): Which qubit to add the gate to
msg (str): Two-bit message to send
Returns:
QuantumCircuit: Circuit that, when decoded, will produce msg
Raises:
ValueError if msg is wrong length or contains invalid characters
"""
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
qc = create_bell_pair()
# We'll add a barrier for visual separation
qc.barrier()
# At this point, qubit 0 goes to Alice and qubit 1 goes to Bob
# Next, Alice encodes her message onto qubit 1. In this case,
# we want to send the message '10'. You can try changing this
# value and see how it affects the circuit
message = '10'
qc = encode_message(qc, 1, message)
qc.barrier()
# Alice then sends her qubit to Bob.
# After recieving qubit 0, Bob applies the recovery protocol:
qc = decode_message(qc)
# Finally, Bob measures his qubits to read Alice's message
qc.measure_all()
# Draw our output
qc.draw("mpl")
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, assemble, transpile,execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
import qiskit.quantum_info as qi
# import basic plot tools
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2)
qc.h(0) # Oracle
qc.h(1) # Oracle
qc.cz(0,1) # Oracle
# Diffusion operator (U_s)
qc.h([0,1])
qc.z([0,1])
qc.cz(0,1)
qc.h([0,1])
qc.measure_all()
qc.draw('mpl')
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend, shots=1000)
result = job.result()
print(result.get_counts(qc))
plot_histogram(result.get_counts(qc))
from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
import qiskit.quantum_info as qi
def change_sign(circuit, target_state):
# Aplicar una compuerta de fase controlada para cambiar el signo del estado objetivo
# Crear un circuito auxiliar con un qubit de control y el estado objetivo como objetivo
aux_circuit = QuantumCircuit(2)
aux_circuit.x(1) # Preparar el estado objetivo
# Aplicar una compuerta de fase controlada con el qubit de control en el estado |1⟩
aux_circuit.cp(-1 * target_state, 0, 1)
# Deshacer la preparación del estado objetivo
aux_circuit.x(1)
# Agregar el circuito auxiliar al circuito principal
circuit.compose(aux_circuit, inplace=True)
# Crear el circuito cuántico con n qubits y n bits clásicos
n = 3
circuit = QuantumCircuit(n, n)
# Definir el estado objetivo al que se le cambiará el signo
target_state = 0 # Por ejemplo, cambiamos el signo del componente |0...0⟩
# Aplicar la función change_sign al estado objetivo
change_sign(circuit, target_state)
import qiskit.quantum_info as qi
qc = QuantumCircuit(4,4) # Ponemos 4 qubits y 4 bits
# Aplicamos algunas compuertas
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
change_sign(qc, 0)
stv = qi.Statevector.from_instruction(qc)
style = {'backgroundcolor': 'lightgreen'}
qc.draw(output='mpl', style=style)
stv.draw('latex', prefix="|\\psi\\rangle =")
from qiskit import QuantumCircuit, transpile, assemble, Aer, execute
from qiskit.quantum_info import Statevector
# Crear un circuito cuántico con n qubits
n = 3
circuit = QuantumCircuit(n)
# Crear el estado ∑𝑖|𝑖⟩⟨𝑖| como un Statevector
statevector = Statevector.from_label('101') # Estado inicial |000⟩
# Aplicar el operador de densidad diagonal a los qubits utilizando el initialize method
circuit.initialize(statevector.data, range(n))
# Medir los qubits
circuit.measure_all()
# Simular y ejecutar el circuito
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
result = job.result()
counts = result.get_counts(circuit)
print(counts)
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
for i in range(10):
print(X_train[i],y_train[i])
import pandas as pd
df = pd.read_csv("heart.csv")
print(df.head())
#print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1])
X = df.iloc[:,:-1].values
y = df.target.values
print(X.shape,y.shape)
from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
import mglearn
import matplotlib.pyplot as plt
#from matplotlib.pyplot import figure
#figure(figsize=(8, 6), dpi=80)
#plt.rcParams["figure.figsize"] = (8,8)
# generate dataset
X, y = mglearn.datasets.make_forge()
# plot dataset
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
print("X.shape:", X.shape)
mglearn.plots.plot_knn_classification(n_neighbors=5)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = np.round(100*model.score(X_test, y_test),1)
print ('k=',k,'Porcentaje de aciertos:',score)
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
classifier = SVC(kernel='linear',random_state=0)
classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)
accuracy = accuracy_score(y_test,y_pred)
print("Support Vector Machine :")
print("Accuracy = ", accuracy)
import sklearn
import mglearn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import display
display(mglearn.plots.plot_logistic_regression_graph())
display(mglearn.plots.plot_single_hidden_layer_graph())
display(mglearn.plots.plot_two_hidden_layer_graph())
from IPython.display import YouTubeVideo
YouTubeVideo('aircAruvnKk', width=800, height=300)
from IPython.display import YouTubeVideo
YouTubeVideo('IHZwWFHWa-w', width=800, height=300)
from IPython.display import YouTubeVideo
YouTubeVideo('Ilg3gGewQ5U', width=800, height=300)
from IPython.display import YouTubeVideo
YouTubeVideo('tIeHLnjs5U8', width=800, height=300)
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
classifier = MLPClassifier(solver='lbfgs', alpha=1e-5,
hidden_layer_sizes=(5, 5,5), random_state=1)
classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)
accuracy = accuracy_score(y_test,y_pred)
print("Neural Network Classifier :")
print("Accuracy = ", accuracy)
from sklearn import datasets
import matplotlib.pyplot as plt
digits = datasets.load_digits()
X = np.array(digits.data)
Y = np.array(digits.target)
fig=plt.figure(figsize=(10, 10))
for i in range(16):
fig.add_subplot(4, 4, i+1)
j = randint(0, len(y))
plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest')
num = str(y[j])
plt.title('N='+str(num),fontsize=15)
plt.xticks(fontsize=10, rotation=90)
plt.yticks(fontsize=10, rotation=0)
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
import numpy as np
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
from random import randint
train_fraction = .8
train_len = int(train_fraction*len(X))
print ('Fraccion train:',train_fraction)
digits = datasets.load_digits()
X = np.array(digits.data)
Y = np.array(digits.target)
X_train = X[0:train_len]
Y_train = Y[0:train_len]
X_test = X[train_len:]
Y_test = Y[train_len:]
print ('Data shape:',X.shape)
print ('X_train shape:',X_train.shape)
print ('Y_train shape:',Y_train.shape)
print ('X_test shape:',X_test.shape)
print ('Y_test shape:',Y_test.shape)
for k in range(1,10):
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, Y_train)
predictions = model.predict(X_test)
score = np.round(100*model.score(X_test, Y_test),1)
print ('k=',k,'Porcentaje de aciertos:',score)
import seaborn as sb
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
model = KNeighborsClassifier(n_neighbors=4)
model.fit(X_train, Y_train)
cm = confusion_matrix(Y_test, model.predict(X_test))
plt.subplots(figsize=(10, 6))
sb.heatmap(cm, annot = True, fmt = 'g')
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()
import matplotlib.pyplot as plt
from random import randint
"""
#############################. 8x8 = 64
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target
print ( X.shape, y.shape )
#############################. 8x8 = 64
"""
#############################. 28x28 = 784
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X_train = X_train.reshape((60000,784))
X_test = X_test.reshape((10000,784))
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X = X_test
y = y_test
X = X[0:2000]
y = y[0:2000]
#############################. 28x28 = 784
fig=plt.figure(figsize=(10, 10))
for i in range(16):
fig.add_subplot(4, 4, i+1)
j = randint(0, len(y))
#plt.imshow(np.reshape(X[j],(8,8)),cmap=plt.cm.gray_r, interpolation='nearest')
plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.gray, interpolation='nearest')
#plt.imshow(np.reshape(X[j],(28,28)),cmap=plt.cm.RdBu, interpolation='nearest')
num = str(y[j])
plt.title('N='+str(num),fontsize=15)
plt.xticks(fontsize=10, rotation=90)
plt.yticks(fontsize=10, rotation=0)
from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
#############################. 8x8 = 64
from sklearn import datasets
digits = datasets.load_digits()
X = digits.data
y = digits.target
#############################. 8x8 = 64
"""
#############################. 28x28 = 784
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X_train = X_train.reshape((60000,784))
X_test = X_test.reshape((10000,784))
print ( X_train.shape, X_test.shape, y_train.shape, y_test.shape )
X = X_test
y = y_test
X = X[0:2000]
y = y[0:2000]
#############################. 28x28 = 784
"""
print ( X.shape,y.shape)
scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method
pca = PCA(n_components=3) # project from 64 to 3 dimensions
projected = pca.fit_transform(scaled_data)
print(projected.shape)
import plotly.express as px
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=4,
line=dict(width=2,
color='DarkSlateGrey')),
selector=dict(mode='markers'))
fig.show()
from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
print (X.shape,y.shape)
scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method
#tsne = TSNE(n_components=2, random_state=0)
tsne = TSNE(n_components=3, random_state=0)
projected = tsne.fit_transform(scaled_data)
print(projected.shape)
import plotly.express as px
#fig = px.scatter(x=projected[:,0], y=projected[:,1],
# symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=8,
line=dict(width=2,
color='DarkSlateGrey')),
selector=dict(mode='markers'))
fig.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
from google.colab import files
uploaded = files.upload()
!ls
import pandas as pd
df = pd.read_csv("heart.csv")
print(df.head())
print('Number of rows:',df.shape[0], ' number of columns: ',df.shape[1])
X = df.iloc[:,:-1].values
y = df.target.values
from sklearn import svm
# Scale data before applying PCA
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
print (X.shape,y.shape)
scaler.fit(X)
scaled_data=scaler.transform(X)
# Use fit and transform method
#pca = PCA(n_components=2) # project from 13 to 3 dimensions
pca = PCA(n_components=4) # project from 13 to 3 dimensions
#tsne = TSNE(n_components=2, random_state=0)
#tsne = TSNE(n_components=3, random_state=0)
projected = pca.fit_transform(scaled_data)
#projected = tsne.fit_transform(scaled_data)
print(projected.shape)
import plotly.express as px
#fig = px.scatter(x=projected[:,0], y=projected[:,1],
# symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig = px.scatter_3d(x=projected[:,0], y=projected[:,1], z=projected[:,2],
symbol=y,color=y,color_continuous_scale=px.colors.sequential.Inferno)
fig.update_layout(legend_orientation="h")
fig.update_traces(marker=dict(size=8,
line=dict(width=2,
color='DarkSlateGrey')),
selector=dict(mode='markers'))
fig.show()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,y, random_state=0)
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = np.round(100*model.score(X_test, y_test),1)
print ('k=',k,'Porcentaje de aciertos:',score)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
projected, y, random_state=0)
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn import datasets
#from skimage import exposure
import numpy as np
import sklearn
for k in range(1,10):
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = np.round(100*model.score(X_test, y_test),1)
print ('k=',k,'Porcentaje de aciertos:',score)
#Import svm model
from sklearn.svm import SVC
print(X_train.shape,X_test.shape,y_train.shape,y_test.shape)
clf = SVC(kernel='rbf', C=1000, gamma=.1) # Linear Kernel
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
from sklearn import metrics
print("Porcentaje de aciertos:",metrics.accuracy_score(y_test, y_pred))
from sklearn.model_selection import GridSearchCV
# defining parameter range
param_grid = {'C': [0.1, 10, 1000],
'gamma': [1, 0.01, 0.0001],
'kernel': ['rbf']}
grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=2)
# fitting the model for grid search
grid.fit(X_train, y_train)
# print best parameter after tuning
print(grid.best_params_)
# print how our model looks after hyper-parameter tuning
print(grid.best_estimator_)
grid_predictions = grid.predict(X_test)
# print classification report
print(classification_report(y_test, grid_predictions))
from qiskit.circuit.library import ZZFeatureMap
from qiskit.circuit.library import ZFeatureMap
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
def my_circuit1(X, reps_feature_map,theta,rep_ansatz):
feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map)
qc = QuantumCircuit(len(X),1)
qc.append(feature_map.decompose(), range(len(X)))
qc.barrier()
qc = qc.bind_parameters(X)
#W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz)
W = EfficientSU2(num_qubits=len(X), reps=rep_ansatz)
#W = W.bind_parameters(theta)
qc.append(W.decompose(), range(4))
qc.barrier()
qc.measure(0, 0)
return qc
reps_feature_map = 1
rep_ansatz = 1
theta_dim = 4+4*rep_ansatz
#theta = np.zeros(theta_dim)
theta = range(theta_dim)
qc = my_circuit1(X_train[0], 1,theta,rep_ansatz)
qc.decompose().draw(output="mpl", fold=20)
from qiskit import QuantumCircuit
import numpy as np
qc = QuantumCircuit(1)
qc.p(np.pi/2,0)
qc.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap
num_features = len(X_train[0])
feature_map = ZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2
num_features = len(X_train[0])
ansatz = RealAmplitudes(num_qubits=num_features, reps=1)
ansatz.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA,SPSA,SLSQP
optimizer = COBYLA(maxiter=60)
from qiskit.primitives import Sampler
sampler = Sampler()
from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(X_train, y_train)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4 = vqc.score(X_train, y_train)
test_score_q4 = vqc.score(X_test, y_test)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
for i in range(10):
print(X_train[i],y_train[i])
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
import qiskit.quantum_info as qi
def my_circuit0(X,theta):
qc = QuantumCircuit(len(X),1) # Ponemos 3 qubits y 1 bit
# Aplicamos algunas compuertas
for i,X_i in enumerate (X):
qc.h(i)
qc.p(2*X_i,i)
qc.barrier()
for i in range(len(X)):
qc.ry(theta[i],i)
for i in range(len(X)-1,0,-1):
qc.cx(i-1,i)
for i in range(len(X)):
qc.rx(theta[i+len(X)],i)
for i in range(len(X)-1,0,-1):
qc.cx(i-1,i)
for i in range(len(X)):
qc.rx(theta[i+2*len(X)],i)
qc.barrier()
qc.measure(0,0)
return qc
theta =range(12)
qc = my_circuit0(X_train[0],theta)
qc.draw(output='mpl')
from qiskit.circuit.library import ZZFeatureMap
from qiskit.circuit.library import ZFeatureMap
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister,Aer, execute
import numpy as np
def my_circuit1(X, reps_feature_map,theta,rep_ansatz):
feature_map = ZFeatureMap(feature_dimension=len(X), reps=reps_feature_map)
qc = QuantumCircuit(len(X),1)
qc.append(feature_map.decompose(), range(len(X)))
qc.barrier()
qc = qc.bind_parameters(X)
W = RealAmplitudes(num_qubits=len(X), reps=rep_ansatz)
W = W.bind_parameters(theta)
qc.append(W.decompose(), range(4))
qc.barrier()
qc.measure(0, 0)
return qc
theta = np.zeros(12)
#theta = range(12)
qc = my_circuit1(X_train[0], 1,theta,2)
qc.decompose().draw(output="mpl", fold=20)
def prediction(X,theta,shots):
#qc=my_circuit1(X, 1,theta,2)
qc=my_circuit0(X,theta)
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=shots)
result = job.result()
counts = result.get_counts()
try: counts["0"]
except: return 0
else: return counts["0"]/shots
print(prediction(X_train[3],np.zeros(12),1000))
def loss (X,y,theta,shots):
return (prediction(X,theta,shots)-y)**2
def loss_epoch (n_data,X,y,theta,shots):
loss_initial = 0
for i in range(n_data):
loss_initial += loss (X_train[i],y_train[i],theta,shots)
return loss_initial/n_data
print(loss(X_train[2],y[2],np.zeros(12),1000))
print(loss_epoch(80,X_train,y_train,np.zeros(12),1000))
def gradient(X,y,theta,shots):
delta = .01
grad=np.zeros(len(theta))
grad=np.zeros(len(theta))
theta1 = theta.copy()
L = loss(X,y,theta,shots)
for j in range(len(theta)):
theta_new = theta.copy()
theta_new [j] += delta
#print(theta,theta_new)
grad[j]= (loss(X,y,theta_new,shots) -L)/delta
return grad,L
def gradient_epoch(n_data,X,y,theta,shots):
delta = .01
grad=np.zeros(len(theta))
theta1 = theta.copy()
L = loss_epoch(n_data,X,y,theta,shots)
for j in range(len(theta)):
theta_new = theta.copy()
theta_new [j] += delta
#print(theta,theta_new)
grad [j]=(loss_epoch(n_data,X,y,theta_new,shots) -L)/delta
return grad,L
theta = np.zeros(12)
shots = 10000
eta = 1
grad, L = gradient(X_train[2],y_train[2],theta,shots)
print(theta)
theta = theta - eta*grad
print(theta)
theta = np.zeros(12)
grad, L = gradient_epoch(80,X_train,y_train,theta,shots)
print(theta)
theta = theta - eta*grad
print(theta)
def accuracy (N_points,X,y,theta,shots):
acc = 0
for i in range(N_points):
#print(prediction(X[i],theta,shots), y[i])
if (np.round(prediction(X[i],theta,shots),0) == y[i]): acc += 1
return (acc/N_points)
accuracy (20,X_train,y_train,theta,shots)
shots = 1000
n_data = 80
eta = 1
n_epochs = 50
from matplotlib import pyplot as plt
from IPython.display import clear_output
theta = np.zeros(12)
loss_initial = 0
for i in range(n_data):
loss_initial += loss(X_train[i],y_train[i],theta,shots)
mean_loss = [loss_initial/n_data]
acc_list = [accuracy (20,X_test,y_test,theta,shots)]
plt.rcParams["figure.figsize"] = (12, 6)
def graph(mean_loss,acc_list):
clear_output(wait=True)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(range(len(mean_loss)), mean_loss, 'g-')
ax2.plot(range(len(mean_loss)), acc_list, 'b-')
ax1.set_xlabel('Iteraciones sobre los Datos')
ax1.set_ylabel('Función Loss', color='g')
ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b')
plt.show()
for j in range(n_epochs):
if (j>0 and j%5 == 0): eta = eta/2
tot_loss = 0
for i in range(n_data):
grad, L = gradient(X_train[i],y_train[i],theta,shots)
theta = theta - eta * grad
tot_loss += L
mean_loss.append(tot_loss/n_data)
acc_list.append(accuracy (20,X_test,y_test,theta,shots))
graph(mean_loss,acc_list)
shots = 1000
n_data = 80
eta = 1
n_epochs = 50
from matplotlib import pyplot as plt
from IPython.display import clear_output
theta = np.zeros(12)
loss_initial = 0
for i in range(n_data):
loss_initial += loss (X_train[i],y_train[i],theta,shots)
mean_loss = [loss_initial/n_data]
acc_list = [accuracy (20,X_test,y_test,theta,shots)]
plt.rcParams["figure.figsize"] = (12, 6)
def graph(mean_loss,acc_list):
clear_output(wait=True)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(range(len(mean_loss)), mean_loss, 'g-')
ax2.plot(range(len(mean_loss)), acc_list, 'b-')
ax1.set_xlabel('Iteraciones sobre los Datos')
ax1.set_ylabel('Función Loss', color='g')
ax2.set_ylabel('Porcentaje de Aciertos en Test', color='b')
plt.show()
for j in range(n_epochs):
if (j>0 and j%5 == 0): eta = eta/2
grad, L = gradient_epoch(80,X_train,y_train,theta,shots)
theta = theta - eta * grad
mean_loss.append(L)
acc_list.append(accuracy (20,X_test,y_test,theta,shots))
graph(mean_loss,acc_list)
plt.title("Accuracy for X_test against iteration")
plt.xlabel("Iteration")
plt.ylabel("Accuracy")
plt.plot(range(len(acc_list)), acc_list)
plt.grid()
plt.show()
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
X = iris_data.data[0:100]
y = iris_data.target[0:100]
print(X.shape,y.shape)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.preprocessing import MinMaxScaler
import numpy as np
X = MinMaxScaler(feature_range=(0,1)).fit_transform(X)
for i in range(10):
print(X[i,0:4],y[i])
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=0.8, random_state=algorithm_globals.random_seed
)
print(X_train.shape, X_test.shape,y_train.shape,y_test.shape)
from qiskit.circuit.library import ZZFeatureMap,ZFeatureMap
num_features = X.shape[1]
feature_map = ZFeatureMap(feature_dimension=num_features, reps=2)
feature_map.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=num_features, reps=1)
ansatz.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA # Constrained Optimization By Linear Approximation optimizer.
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.COBYLA.html
from qiskit.algorithms.optimizers import SPSA # Simultaneous Perturbation Stochastic Approximation optimizer
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SPSA.html
from qiskit.algorithms.optimizers import SLSQP # Sequential Least SQuares Programming optimizer
# https://qiskit.org/documentation/stubs/qiskit.algorithms.optimizers.SLSQP.html
optimizer = COBYLA(maxiter=100)
from qiskit.primitives import Sampler
sampler = Sampler()
from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.grid()
plt.show()
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(X_train, y_train)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4 = vqc.score(X_train, y_train)
test_score_q4 = vqc.score(X_test, y_test)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
from sklearn.svm import SVC
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
from IPython.display import IFrame
IFrame("https://arxiv.org/pdf/1304.3061.pdf", width=600, height=300)
!pip install pyscf
!pip install --upgrade qiskit-nature
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.mappers import DirectMapper
from qiskit_nature.second_q.problems import HarmonicBasis
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
#from qiskit_nature.drivers import PySCFDriver
from qiskit_nature.second_q.drivers import PySCFDriver
import matplotlib.pyplot as plt
import numpy as np
#driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
n=40 # Numero de puntos +1
d = [0.735*i/10 for i in range(1,n)]
atom_array = [ "H 0 0 0; H 0 0 " + str(0.735*i/10) for i in range(1,n)]
E =[]
for i in range(0,n-1):
driver = PySCFDriver(
#atom="H 0 0 0; H 0 0 0.735",
atom=atom_array[i],
basis="sto3g",
charge=0,
spin=0,
#unit=DistanceUnit.ANGSTROM,
)
#basis = HarmonicBasis([2, 2, 2, 2])
vib_problem = driver.run()
vib_problem.hamiltonian.truncation_order = 2
mapper = DirectMapper()
solver_without_filter = NumPyMinimumEigensolver()
#solver_with_filter = NumPyMinimumEigensolver(
# filter_criterion=vib_problem.get_default_filter_criterion())
gsc_wo = GroundStateEigensolver(mapper, solver_without_filter)
result_wo = gsc_wo.solve(vib_problem)
#gsc_w = GroundStateEigensolver(mapper, solver_with_filter)
#result_w = gsc_w.solve(vib_problem)
#print(result_wo)
#print(f"Total ground state energy = {result_wo.total_energies[0]:.4f}")
#print("\n\n")
#print(result_w)
E.append(result_wo.total_energies[0])
plt.figure(figsize=(10, 6))
#print (E)
plt.plot(d,E, '--bo', label='Energías vs distance')
plt.grid()
print ("Energía mininima =", np.round(min(E),5), " para d =", d[E.index(min(E))])
from IPython.display import YouTubeVideo
YouTubeVideo('_ediOdFUr10', width=800, height=300)
import pennylane as qml
import numpy as np
symbols = ["H", "H"]
#coordinates = np.array([0.0, 0.0, 0, 0.0, 0.0, 0.735])# in Angtrons
coordinates = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 1.3889487])# in au
import pennylane as qml
H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates)
print("Number of qubits = ", qubits)
print("The Hamiltonian is ", H)
dev = qml.device("default.qubit",wires=qubits)
@qml.qnode(dev)
def energy(state):
qml.BasisState(np.array(state),wires=range(qubits))
return qml.expval(H)
energy([1,1,0,0])
hf =qml.qchem.hf_state(electrons = 2, orbitals = 4)
print("Estado de Hartree-Fock:", hf)
print("Energía del estado base=",energy(hf),"Ha")
print("Energía del estado base=",energy(hf)* 27.211386245988,"eV")
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
"""Tests for Storage."""
import os
import shutil
from pathlib import Path
from unittest import TestCase
from qiskit import QuantumCircuit
from testcontainers.compose import DockerCompose
from testcontainers.localstack import LocalStackContainer
from purplecaffeine.core import Trial, LocalStorage, S3Storage, ApiStorage
from purplecaffeine.exception import PurpleCaffeineException
from .test_trial import dummy_trial
class TestStorage(TestCase):
"""TestStorage."""
def setUp(self) -> None:
"""SetUp Storage object."""
self.current_directory = os.path.dirname(os.path.abspath(__file__))
self.save_path = os.path.join(self.current_directory, "test_storage")
if not os.path.exists(self.save_path):
Path(self.save_path).mkdir(parents=True, exist_ok=True)
self.local_storage = LocalStorage(path=self.save_path)
self.my_trial = dummy_trial(name="keep_trial", storage=self.local_storage)
def test_save_get_list_local_storage(self):
"""Test save trial locally."""
# Save
self.local_storage.save(trial=self.my_trial)
self.assertTrue(
os.path.isfile(
os.path.join(self.save_path, f"trial_{self.my_trial.uuid}/trial.json")
)
)
# Get
recovered = self.local_storage.get(trial_id=self.my_trial.uuid)
self.assertTrue(isinstance(recovered, Trial))
self.assertEqual(recovered.parameters, [["test_parameter", "parameter"]])
self.assertEqual(recovered.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(recovered.texts, [["test_text", "text"]])
with self.assertRaises(ValueError):
self.local_storage.get(trial_id="999")
# List
list_trials = self.local_storage.list(query="keep_trial")
self.assertTrue(isinstance(list_trials, list))
self.assertTrue(isinstance(list_trials[0], Trial))
list_trials = self.local_storage.list(query="trial999")
self.assertTrue(isinstance(list_trials, list))
self.assertEqual(len(list_trials), 0)
def test_save_get_api_storage(self):
"""Test save trial in API."""
with DockerCompose(
filepath=os.path.join(self.current_directory, "../.."),
compose_file_name="docker-compose.yml",
build=True,
) as compose:
host = compose.get_service_host("api_server", 8000)
port = compose.get_service_port("api_server", 8000)
compose.wait_for(f"http://{host}:{port}/health_check/")
storage = ApiStorage(
host=f"http://{host}:{port}", username="admin", password="admin"
)
# Save
storage.save(trial=self.my_trial)
# Get
recovered = storage.get(trial_id="1")
self.assertTrue(isinstance(recovered, Trial))
self.assertEqual(recovered.parameters, [["test_parameter", "parameter"]])
with self.assertRaises(ValueError):
storage.get(trial_id="999")
def test_save_get_list_s3_storage(self) -> None:
"""Test of S3Storage object."""
with LocalStackContainer(image="localstack/localstack:2.0.1") as localstack:
localstack.with_services("s3")
s3_storage = S3Storage(
"bucket",
access_key="",
secret_access_key="",
endpoint_url=localstack.get_url(),
)
s3_storage.client_s3.create_bucket(Bucket=s3_storage.bucket_name)
# save
uuid = s3_storage.save(trial=self.my_trial)
# get
recovered = s3_storage.get(trial_id=uuid)
self.assertTrue(isinstance(recovered, Trial))
with self.assertRaises(PurpleCaffeineException):
s3_storage.get(trial_id="999")
# list
list_trials = s3_storage.list()
self.assertTrue(isinstance(list_trials, list))
for trial in list_trials:
self.assertTrue(isinstance(trial, Trial))
def tearDown(self) -> None:
"""TearDown Storage object."""
file_to_remove = os.path.join(self.save_path)
if os.path.exists(file_to_remove):
shutil.rmtree(file_to_remove)
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
"""Tests for Trial."""
import os
import shutil
from pathlib import Path
from typing import Optional
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit, __version__
from qiskit.circuit.library import XGate
from qiskit.quantum_info import Operator
from purplecaffeine import Trial, LocalStorage, BaseStorage as TrialStorage
def dummy_trial(
name: Optional[str] = "test_trial", storage: Optional[TrialStorage] = None
):
"""Returns dummy trial for tests.
Returns:
dummy trial
"""
trial = Trial(name=name, storage=storage)
trial.add_description("Short desc")
trial.add_metric("test_metric", 42)
trial.add_parameter("test_parameter", "parameter")
trial.add_circuit("test_circuit", QuantumCircuit(2))
trial.add_operator("test_operator", Operator(XGate()))
trial.add_text("test_text", "text")
trial.add_array("test_array", np.array([42]))
trial.add_tag("qiskit")
trial.add_tag("test")
trial.add_version("numpy", "1.2.3-4")
return trial
class TestTrial(TestCase):
"""TestTrial."""
def setUp(self) -> None:
"""SetUp Trial object."""
current_directory = os.path.dirname(os.path.abspath(__file__))
self.save_path = os.path.join(current_directory, "resources")
if not os.path.exists(self.save_path):
Path(self.save_path).mkdir(parents=True, exist_ok=True)
self.local_storage = LocalStorage(path=self.save_path)
def test_trial_context(self):
"""Test train context."""
uuid = "some_uuid"
with Trial(name="test_trial", storage=self.local_storage, uuid=uuid) as trial:
trial.add_metric("test_metric", 42)
trial.read(trial_id=uuid)
self.assertTrue(
os.path.isfile(os.path.join(self.save_path, f"trial_{uuid}/trial.json"))
)
self.assertEqual(trial.metrics, [["test_metric", 42]])
self.assertEqual(trial.versions, [["qiskit", __version__]])
def test_add_trial(self):
"""Test adding stuff into Trial."""
trial = dummy_trial()
self.assertEqual(trial.description, "Short desc")
self.assertEqual(trial.metrics, [["test_metric", 42]])
self.assertEqual(trial.parameters, [["test_parameter", "parameter"]])
self.assertEqual(trial.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(trial.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(trial.texts, [["test_text", "text"]])
self.assertEqual(trial.arrays, [["test_array", np.array([42])]])
self.assertEqual(trial.tags, ["qiskit", "test"])
self.assertEqual(trial.versions, [["numpy", "1.2.3-4"]])
def test_save_read_local_trial(self):
"""Test save and read Trial locally."""
trial = dummy_trial(storage=self.local_storage)
trial.save()
self.assertTrue(
os.path.isfile(
os.path.join(self.save_path, f"trial_{trial.uuid}/trial.json")
)
)
recovered = trial.read(trial_id=trial.uuid)
self.assertEqual(recovered.description, "Short desc")
self.assertEqual(recovered.metrics, [["test_metric", 42]])
self.assertEqual(recovered.parameters, [["test_parameter", "parameter"]])
self.assertEqual(recovered.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(recovered.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(recovered.texts, [["test_text", "text"]])
self.assertEqual(recovered.arrays, [["test_array", np.array([42])]])
self.assertEqual(recovered.tags, ["qiskit", "test"])
self.assertEqual(recovered.versions, [["numpy", "1.2.3-4"]])
def test_export_import(self):
"""Test export and import Trial from shared file."""
trial = dummy_trial()
# Export
trial.export_to_shared_file(path=self.save_path)
self.assertTrue(
os.path.isdir(os.path.join(self.save_path, f"trial_{trial.uuid}"))
)
# Import
new_trial = Trial("test_import").import_from_shared_file(
self.save_path, trial.uuid
)
self.assertEqual(new_trial.description, "Short desc")
self.assertEqual(new_trial.metrics, [["test_metric", 42]])
self.assertEqual(new_trial.parameters, [["test_parameter", "parameter"]])
self.assertEqual(new_trial.circuits, [["test_circuit", QuantumCircuit(2)]])
self.assertEqual(new_trial.operators, [["test_operator", Operator(XGate())]])
self.assertEqual(new_trial.texts, [["test_text", "text"]])
self.assertEqual(new_trial.arrays, [["test_array", np.array([42])]])
self.assertEqual(new_trial.tags, ["qiskit", "test"])
self.assertEqual(new_trial.versions, [["numpy", "1.2.3-4"]])
def tearDown(self) -> None:
"""TearDown Trial object."""
file_to_remove = os.path.join(self.save_path)
if os.path.exists(file_to_remove):
shutil.rmtree(file_to_remove)
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
import os
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info.random import random_pauli
from qiskit.primitives import Estimator
from purplecaffeine.core import Trial, LocalStorage
n_qubits = 4
depth = 3
shots = 2000
circuit = random_circuit(n_qubits, depth)
circuit.draw(fold=-1)
obs = random_pauli(n_qubits)
obs
local_storage = LocalStorage("./trials")
#You could also set the API storage or S3 storage by calling :
#api_storage = ApiStorage(host="http://localhost:8000", username="MY_USERNAME", password="MY_PASS")
#s3_storage = S3Storage("bucket", access_key="MY_KEY", secret_access_key="MY_SECRET")
with Trial("Example trial", storage=local_storage) as trial:
# track some parameters
trial.add_parameter("estimator", "qiskit.primitives.Estimator")
trial.add_parameter("depth", depth)
trial.add_parameter("n_qubits", n_qubits)
trial.add_parameter("shots", shots)
# track objects of interest
trial.add_circuit("circuit", circuit)
trial.add_operator("obs", obs)
# run
exp_value = Estimator().run(circuit, obs, shots=shots).result().values.item()
# track results of run
trial.add_metric("exp_value", exp_value)
local_storage.list()
trials = local_storage.list()
random_trial = trials[0]
trial_uuid = random_trial.uuid
local_storage.get(trial_uuid)
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
import numpy as np
import random
from qiskit.circuit.random import random_circuit
from purplecaffeine.core import BaseStorage, LocalStorage, Trial
from purplecaffeine.widget import Widget
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info.random import random_pauli
from qiskit.primitives import Estimator
local_storage = LocalStorage("./trials/")
n_qubits = 4
depth = 10
shots = 2000
for i in range(0, 3):
with Trial("Example trial " + str(i), storage=local_storage) as trial:
# track parameter
trial.add_parameter("estimator", "qiskit.primitives.Estimator")
trial.add_parameter("depth", depth)
trial.add_parameter("n_qubits", n_qubits)
trial.add_parameter("shots", shots)
# track circuits
circuit = random_circuit(n_qubits, depth)
trial.add_circuit("circuit", circuit)
trial.add_circuit("another circuit", random_circuit(n_qubits, depth))
# track operators
obs = random_pauli(n_qubits)
trial.add_operator("obs", obs)
for idx in range(5):
trial.add_operator(f"obs {idx}", random_pauli(n_qubits))
# track tags
trial.add_tag(f"tag {i}")
# track texts
trial.add_text("text one", "This text will be displayed in text tab")
trial.add_text("text two", "This text will be displayed in text tab as well")
# run
exp_value = Estimator().run(circuit, obs, shots=shots).result().values.item()
# track history data as metric
for _ in range(100):
trial.add_metric("history", random.randint(0, 10))
# track results as metric
trial.add_metric("exp_value", exp_value)
Widget(local_storage).show()
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
from qiskit_algorithms import QAOA, SamplingVQE
from qiskit_algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.circuit.library import TwoLocal
from qiskit_optimization import QuadraticProgram
from purplecaffeine import Trial, LocalStorage
qubo = QuadraticProgram(name="qubo_trial")
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
local_storage = LocalStorage("./trials")
with Trial("QAOA trial", storage=local_storage) as trial:
# track some parameters
trial.add_parameter("algo", "qaoa")
trial.add_parameter("sampler", "qiskit.primitives.Sampler")
trial.add_parameter("optimizer", "qiskit.algorithms.optimizers.COBYLA")
# track usefull data
trial.add_text("qubo", qubo.export_as_lp_string())
qaoa_mes = QAOA(
sampler=Sampler(),
optimizer=COBYLA(),
callback=lambda idx, params, mean, std: trial.add_metric("qaoa_history", mean)
)
# run
qaoa = MinimumEigenOptimizer(qaoa_mes)
qaoa_result = qaoa.solve(qubo)
# track results of run
trial.add_text("qaoa_result", qaoa_result.prettyprint())
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
with Trial("VQE trial", storage=local_storage) as trial:
# track some parameters
trial.add_parameter("algo", "vqe")
trial.add_parameter("sampler", "qiskit.primitives.Sampler")
trial.add_parameter("optimizer", "qiskit.algorithms.optimizers.COBYLA")
# track usefull data
trial.add_text("qubo", qubo.export_as_lp_string())
# track some objects
trial.add_circuit("ansatz", ansatz)
vqe_mes = SamplingVQE(
sampler=Sampler(),
ansatz=ansatz,
optimizer=COBYLA(),
callback=lambda idx, params, mean, std: trial.add_metric("vqe_history", mean)
)
# run
vqe = MinimumEigenOptimizer(vqe_mes)
vqe_result = vqe.solve(qubo)
# track results of run
trial.add_text("vqe_result", vqe_result.prettyprint())
local_storage.list()
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/DRA-chaos/Solutions-to-the-Lab-Exercises---IBM-Qiskit-Summer-School-2021
|
DRA-chaos
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit Functions
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.quantum_info as qi
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import warnings
warnings.filterwarnings('ignore')
target = QuantumCircuit(2)
#target = # YOUR CODE HERE
target.h(0)
target.h(1)
target.rx(np.pi/2,0)
target.rx(np.pi/2,1)
target.cx(0,1)
target.p(np.pi,1)
target.cx(0,1)
target_unitary = qi.Operator(target)
target.draw('mpl')
from qc_grader import grade_lab5_ex1
# Note that the grading function is expecting a quantum circuit with no measurements
grade_lab5_ex1(target)
simulator = Aer.get_backend('qasm_simulator')
qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192)
qpt_result = qpt_job.result()
# YOUR CODE HERE
qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs)
Choi_qpt= qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex2
# Note that the grading function is expecting a floating point number
grade_lab5_ex2(fidelity)
# T1 and T2 values for qubits 0-3
T1s = [15000, 19000, 22000, 14000]
T2s = [30000, 25000, 18000, 28000]
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_measure[j],'measure',[j])
noise_thermal.add_quantum_error(errors_reset[j],'reset',[j])
noise_thermal.add_quantum_error(errors_u3[j],'u3',[j])
noise_thermal.add_quantum_error(errors_u2[j],'u2',[j])
noise_thermal.add_quantum_error(errors_u1[j],'u1',[j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k])
# YOUR CODE HERE
from qc_grader import grade_lab5_ex3
# Note that the grading function is expecting a NoiseModel
grade_lab5_ex3(noise_thermal)
np.random.seed(0)
noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
noise_qpt_result = noise_qpt_job.result()
# YOUR CODE HERE
noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs)
noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex4
# Note that the grading function is expecting a floating point number
grade_lab5_ex4(fidelity)
np.random.seed(0)
# YOUR CODE HERE
#qr = QuantumRegister(2)
qubit_list = [0,1]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list)
meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
cal_results = meas_calibs_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list)
Cal_result = meas_fitter.filter.apply(noise_qpt_result)
# YOUR CODE HERE
Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs)
Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex5
# Note that the grading function is expecting a floating point number
grade_lab5_ex5(fidelity)
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 17 15:00:00 2022
@author: Yokohama National University, Kosaka Lab
"""
import warnings
import requests
from qiskit import qobj as qobj_mod
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.library import IGate, XGate, YGate, ZGate, HGate, SGate, SdgGate, SXGate, SXdgGate
from qiskit.circuit.measure import Measure
from qiskit.providers import BackendV2 as Backend
from qiskit.providers import Options
from qiskit.transpiler import Target
from qiskit.providers.models import BackendConfiguration
from qiskit.exceptions import QiskitError
import kosakaq_job
import circuit_to_kosakaq
class KosakaQBackend(Backend):
def __init__(
self,
provider,
name,
url,
version,
n_qubits,
max_shots=4096,
max_experiments=1,
):
super().__init__(provider=provider, name=name)
self.url = url
self.version = version
self.n_qubits = n_qubits
self.max_shots = max_shots
self.max_experiments = max_experiments
self._configuration = BackendConfiguration.from_dict({
'backend_name': name,
'backend_version': version,
'url': self.url,
'simulator': False,
'local': False,
'coupling_map': None,
'description': 'KosakaQ Diamond device',
'basis_gates': ['i', 'x', 'y', 'z', 'h', 's', 'sdg', 'sx', 'sxdg'], #後で修正が必要
'memory': False,
'n_qubits': n_qubits,
'conditional': False,
'max_shots': max_shots,
'max_experiments': max_experiments,
'open_pulse': False,
'gates': [
{
'name': 'TODO',
'parameters': [],
'qasm_def': 'TODO'
}
]
})
self._target = Target(num_qubits=n_qubits)
# theta = Parameter('θ')
# phi = Parameter('ϕ')
# lam = Parameter('λ')
self._target.add_instruction(IGate())
self._target.add_instruction(XGate())
self._target.add_instruction(YGate())
self._target.add_instruction(ZGate())
self._target.add_instruction(HGate())
self._target.add_instruction(SGate())
self._target.add_instruction(SdgGate())
self._target.add_instruction(SXGate())
self._target.add_instruction(SXdgGate())
self._target.add_instruction(Measure())
self.options.set_validator("shots", (1,max_shots))
def configuration(self):
warnings.warn("The configuration() method is deprecated and will be removed in a "
"future release. Instead you should access these attributes directly "
"off the object or via the .target attribute. You can refer to qiskit "
"backend interface transition guide for the exact changes: "
"https://qiskit.org/documentation/apidoc/providers.html#backendv1-backendv2",
DeprecationWarning)
return self._configuration
def properties(self):
warnings.warn("The properties() method is deprecated and will be removed in a "
"future release. Instead you should access these attributes directly "
"off the object or via the .target attribute. You can refer to qiskit "
"backend interface transition guide for the exact changes: "
"https://qiskit.org/documentation/apidoc/providers.html#backendv1-backendv2",
DeprecationWarning)
@property
def max_circuits(self):
return 1
@property
def target(self):
return self._target
@classmethod
def _default_options(cls):
return Options(shots=4096)
def run(self, circuit, **kwargs):
if isinstance(circuit, qobj_mod.PulseQobj):
raise QiskitError("Pulse jobs are not accepted")
for kwarg in kwargs:
if kwarg != 'shots':
warnings.warn(
"Option %s is not used by this backend" % kwarg,
UserWarning, stacklevel=2)
out_shots = kwargs.get('shots', self.options.shots)
if out_shots > self.configuration().max_shots:
raise ValueError('Number of shots is larger than maximum '
'number of shots')
kosakaq_json = circuit_to_kosakaq.circuit_to_KosakaQ(circuit, self._provider.access_token, shots=out_shots, backend=self.name)[0]
header = {
"Authorization": "token " + self._provider.access_token,
"SDK": "qiskit"
}
res = requests.post(self.url+r"/job/", data=kosakaq_json, headers=header)
res.raise_for_status()
response = res.json()
if 'id' not in response:
raise Exception
job = kosakaq_job.KosakaQJob(self, response['id'], access_token=self.provider.access_token, qobj=circuit)
return job
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 17 15:00:00 2022
@author: Yokohama National University, Kosaka Lab
"""
import requests
from qiskit.providers import ProviderV1 as Provider #抽象クラスのインポート
from qiskit.providers.exceptions import QiskitBackendNotFoundError #エラー用のクラスをインポート
from exceptions import KosakaQTokenError, KosakaQBackendJobIdError, KosakaQBackendFilterError #エラー用のクラス(自作)をインポート
from kosakaq_backend import KosakaQBackend
from kosakaq_job import KosakaQJob
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
class KosakaQProvider(Provider): #抽象クラスからの継承としてproviderクラスを作る
def __init__(self, access_token=None):#引数はself(必須)とtoken(認証が必要な場合)、ユーザーに自分でコピペしてもらう
super().__init__() #ソースコードは()空なので真似した
self.access_token = access_token #トークン定義
self.name = 'kosakaq_provider' #nameという変数を右辺に初期化、このproviderクラスの名づけ
self.url = 'http://192.168.1.82' #リンク変更可能
self.wjson = '/api/backends.json' #jsonに何を入れてサーバーに送るか
self.jobson = '/job/'
def backends(self, name=None, **kwargs):#API(サーバー)に今使えるbackendを聞く(Rabiが使えるとかunicornが使えるとかをreturn[使えるもの]で教えてくれる)
"""指定したフィルタリングと合うバックエンドたちを返すメソッド
引数:
name (str): バックエンドの名前(Rabiやunicorn).
**kwargs: フィルタリングに使用される辞書型
戻り値:
list[Backend]: フィルタリング基準に合うバックエンドたちのリスト
"""
self._backend = [] #availableなバックエンドクラスのbkednameを入れていくためのリスト
res = requests.get(self.url + self.wjson, headers={"Authorization": "Token " + self.access_token})
response = res.json() #[{'id': 1, 'bkedid': 0, 'bkedname': 'Rabi', 'bkedstatus': 'unavailable','detail': 'Authentication credentials were not provided',...}, {'id': 2, 'bkedid': 1, 'bkedname': 'Unicorn', 'bkedstatus': 'available'}]
if 'detail' in response[0]: #トークンが違ったらdetailの辞書一つだけがresponseのリストに入っていることになる
raise KosakaQTokenError('access_token was wrong') #トークン間違いを警告
for i in range(len(response)):
if response[i]['bkedstatus'] =='available':
if name == None:
self._backend.append(KosakaQBackend(self, response[i]['bkedname'], self.url, response[i]['bkedversion'], response[i]['bkednqubits'], 4096, 1))
elif name == response[i]['bkedname']:
self._backend.append(KosakaQBackend(self, response[i]['bkedname'], self.url, response[i]['bkedversion'], response[i]['bkednqubits'], 4096, 1))
else:
pass
return self._backend#responseのstatusがavailableかつフィルタリングにあうバックエンドたちのバックエンドクラスのインスタンスリストを返す
def get_backend(self, name=None, **kwargs): #ユーザーに"Rabi"などを引数として入れてもらう、もしbackendsメソッドのreturnにRabiがあればインスタンスを作れる
"""指定されたフィルタリングに合うバックエンドを一つだけ返す(一つ下のメソッドbackendsの一つ目を取り出す)
引数:
name (str): バックエンドの名前
**kwargs: フィルタリングに使用される辞書型
戻り値:
Backend: 指定されたフィルタリングに合うバックエンド
Raises:
QiskitBackendNotFoundError: バックエンドが見つからなかった場合、もしくは複数のバックエンドがフィルタリングに合う場合、もしくは一つもフィルタリング条件に合わない場合
"""
backends = self.backends(name, **kwargs) #backendsという変数にbackendsメソッドのreturnのリストを代入
if len(backends) > 1:
raise QiskitBackendNotFoundError('More than one backend matches criteria')
if not backends:
raise QiskitBackendNotFoundError('No backend matches criteria.')
return backends[0]
def retrieve_job(self, job_id: str):#jobidを文字列として代入してもらう(指定してもらう),対応するJobを返す
"""このバックエンドに投入されたjobを一つだけ返す
引数:
job_id: 取得したいjobのID
戻り値:
与えられたIDのjob
Raises:
KosakaQBackendJobIdError: もしjobの取得に失敗した場合、ID間違いのせいにする
"""
res = requests.get(self.url + self.jobson, headers={"Authorization": "Token " + self.access_token}, params={"jobid": job_id})
response = res.json()#辞書型{bkedlist,jobist,qobjlist}
print(response)
if response['joblist'][0]['jobid'] == job_id:
for i in range(len(response['bkedlist'])):
if response['bkedlist'][i]['bkedid'] == response['joblist'][0]['bkedid']:
bkedname = response['bkedlist'][i]['bkedname']
backend = KosakaQBackend(self, bkedname, self.url, response['bkedlist'][i]['bkedversion'], response['bkedlist'][i]['bkednqubits'], 4096, 1)
#量子レジスタqを生成する。
q = QuantumRegister(1)
#古典レジスタcを生成する
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
string = response['qobjlist'][0][0]['gates']
gateslist = eval(string) #gatelist=["H","X"]
for gate_name in gateslist:
if gate_name == "I":
qc.i(q[0])
elif gate_name == "X":
qc.x(q[0])
elif gate_name == "Y":
qc.y(q[0])
elif gate_name == "Z":
qc.z(q[0])
elif gate_name == "H":
qc.h(q[0])
elif gate_name == "S":
qc.s(q[0])
elif gate_name == "SDG":
qc.sdg(q[0])
elif gate_name == "SX":
qc.sx(q[0])
elif gate_name == "SXDG":
qc.sxdg(q[0])
else:
pass
return KosakaQJob(backend, response['joblist'][0]['jobid'], self.access_token, qc)
else:
raise KosakaQBackendJobIdError('Job_id was wrong')
def jobs(self,
limit: int = 10,
skip: int = 0,
jobstatus = None,
jobid = None,
begtime = None,
bkedid = None,
fintime = None,
job_num = None,
note = None,
posttime = None,
qobjid = None,
userid = None
): #list[KosakaQJob]を返す
"""このバックエンドに送信されたjobのうち指定したフィルタに合うものを取得して、返す
引数:
limit: 取得するjobの上限数
skip: jobを飛ばしながら参照
jobstatus: このステータスを持つjobのみを取得する。
指定方法の例 `status=JobStatus.RUNNING` or `status="RUNNING"`
or `status=["RUNNING", "ERROR"]`
jobid: jobの名前でのフィルタリング用。 job名は部分的にマッチする、そして
`regular expressions(正規表現)
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions>`_
が使われる。
begtime: 指定された開始日(現地時間)でのフィルター用。これは作成日がこの指定した現地時間より後のjobを探すのに使われる。
fintime: 指定された終了日(現地時間)でのフィルター用。 これは作成日がこの指定された現地時間よりも前に作られたjobを見つけるために使われる。
job_num: jobの番号
note: メモ
posttime: 投稿時間
qobjid: qobjのID
userid: ユーザーID
戻り値:
条件に合うjobのリスト
Raises:
KosakaQBackendFilterError: キーワード値が認識されない場合 (でも、メソッド内で使われてない)
"""
jobs_list = [] #返す用のリスト
res = requests.get(self.url + self.jobson, headers={"Authorization": "Token " + self.access_token})
response = res.json()#辞書型{bkedlist(ラビ、ユニコーン),jobist(jobnumがjobの数だけ),qobjlist(qobjnumがqobjの数だけ、ゲートもたくさん)}
print(response)
for i in range(len(response['joblist'])):
if response['joblist'][i]['begtime'] == begtime or response['joblist'][i]['begtime'] == None :
if response['joblist'][i]['bkedid'] == bkedid or response['joblist'][i]['bkedid'] == None:
if response['joblist'][i]['fintime'] == fintime or response['joblist'][i]['fintime'] == None:
if response['joblist'][i]['job_num'] == job_num or response['joblist'][i]['job_num'] == None:
if response['joblist'][i]['jobid'] == jobid or response['joblist'][i]['jobid'] == None:
if response['joblist'][i]['jobstatus'] == jobstatus or response['joblist'][i]['jobstatus'] == None:
if response['joblist'][i]['note'] == note or response['joblist'][i]['note'] == None:
if response['joblist'][i]['posttime'] == posttime or response['joblist'][i]['posttime'] == None:
if response['joblist'][i]['qobjid'] == qobjid or response['joblist'][i]['qobjid'] == None:
if response['joblist'][i]['userid'] == userid or response['joblist'][i]['userid'] == None:
bked_id = response['joblist'][i]['bkedid']#代入用bkedid
bked_posi =bked_id-1 #代入用バックエンド番号
backend = KosakaQBackend(self, response['bkedlist'][bked_posi]['bkedname'], self.url, response['bkedlist'][bked_posi]['bkedversion'], response['bkedlist'][bked_posi]['bkednqubits'], 4096, 1)
#量子レジスタqを生成する。
q = QuantumRegister(1)
#古典レジスタcを生成する
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
string = response['qobjlist'][i]['gates']
gateslist = eval(string) #gatelist=["H","X"]
for gate_name in gateslist:
if gate_name == "I":
qc.i(q[0])
elif gate_name == "X":
qc.x(q[0])
elif gate_name == "Y":
qc.y(q[0])
elif gate_name == "Z":
qc.z(q[0])
elif gate_name == "H":
qc.h(q[0])
elif gate_name == "S":
qc.s(q[0])
elif gate_name == "SDG":
qc.sdg(q[0])
elif gate_name == "SX":
qc.sx(q[0])
elif gate_name == "SXDG":
qc.sxdg(q[0])
else:
pass
jobs_list.insert(i, KosakaQJob(backend, response['joblist'][i]['jobid'], self.access_token, qc))
if len(jobs_list) == 0:
raise KosakaQBackendFilterError('Filter was Error')
return jobs_list
def __eq__(self, other): #等号の定義
"""Equality comparison.
By default, it is assumed that two `Providers` from the same class are
equal. Subclassed providers can override this behavior.
"""
return type(self).__name__ == type(other).__name__
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
"""
Test Script
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qrx = QuantumRegister(1, 'q0')
qry = QuantumRegister(1, 'q1')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 12:38:00 2022
@author: daisu
"""
from kosakaq_experiments.KosakaQ_randomized_benchmarking import randomized_benchmarking
from kosakaq_backend import KosakaQBackend
from qiskit import *
from kosakaq_provider import *
provider = KosakaQProvider("8c8795d3fee73e69271bc8c9fc2e0c12e73e5879")
# print(provider.backends(),"\n")
backend = provider.backends()[0]
# rb = randomized_benchmarking("a",[1, 10, 20, 50, 75, 100, 125, 150, 175, 200],repetition = 1)
# rb = randomized_benchmarking("a",[100],repetition = 1)
rb = randomized_benchmarking(backend,length_vector = [1 ,20, 75, 125, 175], repetition = 5, seed = 5)
# emulator = Aer.get_backend('qasm_simulator')
# life = 10
# while life>0:
# rb.make_sequence()
# for i,j in zip(rb.circuits[0],rb.gate_sequence[0]):
# job = execute( i, emulator, shots=8192 )
# hist = job.result().get_counts()
# # print(hist)
# # print(hist.get("1"))
# if hist.get("1") is not None:
# print(j,hist)
# # print(i)
# # print(hist)
# life -= 1
# # for i in rb.gate_sequence[0]:
# # print(i)
# # 普段使っているのと異なるUser作る
rb.make_sequence()
rb.run()
# print(rb.gate_sequence[29][9])
|
https://github.com/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 09:39:52 2022
@author: Daisuke Ito
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import differential_evolution
from qiskit import QuantumCircuit
import itertools
import requests
import json
import sys
sys.path.append("..")
from kosakaq_job import KosakaQExperimentJob
class randomized_benchmarking:
def __init__(self, backend, length_vector = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200], repetition =30, shots = 4096, seed = None, interleaved = ""):
self.backend = backend
self.length_vector = length_vector
self.rep = repetition
self.shots = shots
self.seed = seed
self.interleaved = interleaved
if not (interleaved == ""):
if interleaved == "X":
self.interleaved_gate = 1
elif interleaved == "Y":
self.interleaved_gate = 2
elif interleaved == "Z":
self.interleaved_gate = 3
else:
raise
self.gate_sequence = []
self.circuits = []
self.result_data = None
self.ops = None
self.Cliford_trans = \
np.array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23.],
[ 1., 0., 3., 2., 6., 7., 4., 5., 11., 10., 9.,
8., 13., 12., 18., 19., 22., 23., 14., 15., 21., 20.,
16., 17.],
[ 2., 3., 0., 1., 7., 6., 5., 4., 10., 11., 8.,
9., 20., 21., 15., 14., 23., 22., 19., 18., 12., 13.,
17., 16.],
[ 3., 2., 1., 0., 5., 4., 7., 6., 9., 8., 11.,
10., 21., 20., 19., 18., 17., 16., 15., 14., 13., 12.,
23., 22.],
[ 4., 7., 5., 6., 11., 8., 9., 10., 2., 3., 1.,
0., 22., 17., 21., 12., 14., 18., 13., 20., 23., 16.,
15., 19.],
[ 5., 6., 4., 7., 10., 9., 8., 11., 1., 0., 2.,
3., 23., 16., 12., 21., 19., 15., 20., 13., 22., 17.,
18., 14.],
[ 6., 5., 7., 4., 8., 11., 10., 9., 3., 2., 0.,
1., 16., 23., 20., 13., 18., 14., 12., 21., 17., 22.,
19., 15.],
[ 7., 4., 6., 5., 9., 10., 11., 8., 0., 1., 3.,
2., 17., 22., 13., 20., 15., 19., 21., 12., 16., 23.,
14., 18.],
[ 8., 9., 11., 10., 1., 3., 2., 0., 7., 4., 5.,
6., 19., 14., 22., 16., 20., 12., 23., 17., 15., 18.,
13., 21.],
[ 9., 8., 10., 11., 2., 0., 1., 3., 6., 5., 4.,
7., 14., 19., 23., 17., 13., 21., 22., 16., 18., 15.,
20., 12.],
[ 10., 11., 9., 8., 3., 1., 0., 2., 4., 7., 6.,
5., 18., 15., 17., 23., 12., 20., 16., 22., 14., 19.,
21., 13.],
[ 11., 10., 8., 9., 0., 2., 3., 1., 5., 6., 7.,
4., 15., 18., 16., 22., 21., 13., 17., 23., 19., 14.,
12., 20.],
[ 12., 13., 21., 20., 18., 19., 14., 15., 22., 17., 23.,
16., 1., 0., 4., 5., 8., 10., 6., 7., 2., 3.,
11., 9.],
[ 13., 12., 20., 21., 14., 15., 18., 19., 16., 23., 17.,
22., 0., 1., 6., 7., 11., 9., 4., 5., 3., 2.,
8., 10.],
[ 14., 19., 15., 18., 22., 16., 23., 17., 20., 21., 12.,
13., 8., 9., 2., 0., 6., 4., 1., 3., 10., 11.,
7., 5.],
[ 15., 18., 14., 19., 17., 23., 16., 22., 12., 13., 20.,
21., 10., 11., 0., 2., 5., 7., 3., 1., 8., 9.,
4., 6.],
[ 16., 23., 22., 17., 12., 21., 20., 13., 19., 14., 15.,
18., 5., 6., 8., 11., 3., 0., 10., 9., 7., 4.,
1., 2.],
[ 17., 22., 23., 16., 21., 12., 13., 20., 14., 19., 18.,
15., 4., 7., 9., 10., 0., 3., 11., 8., 6., 5.,
2., 1.],
[ 18., 15., 19., 14., 16., 22., 17., 23., 21., 20., 13.,
12., 11., 10., 3., 1., 4., 6., 0., 2., 9., 8.,
5., 7.],
[ 19., 14., 18., 15., 23., 17., 22., 16., 13., 12., 21.,
20., 9., 8., 1., 3., 7., 5., 2., 0., 11., 10.,
6., 4.],
[ 20., 21., 13., 12., 19., 18., 15., 14., 17., 22., 16.,
23., 3., 2., 7., 6., 10., 8., 5., 4., 0., 1.,
9., 11.],
[ 21., 20., 12., 13., 15., 14., 19., 18., 23., 16., 22.,
17., 2., 3., 5., 4., 9., 11., 7., 6., 1., 0.,
10., 8.],
[ 22., 17., 16., 23., 13., 20., 21., 12., 15., 18., 19.,
14., 7., 4., 11., 8., 2., 1., 9., 10., 5., 6.,
0., 3.],
[ 23., 16., 17., 22., 20., 13., 12., 21., 18., 15., 14.,
19., 6., 5., 10., 9., 1., 2., 8., 11., 4., 7.,
3., 0.]])
def make_sequence(self):
self.gate_sequence = []
for i in range(self.rep):
self.gate_sequence.append([])
for gate_num in self.length_vector:
if self.seed is not None:
np.random.seed(self.seed)
gate_sequence_fwd = np.random.randint(0,23,gate_num).tolist()
else:
gate_sequence_fwd = np.random.randint(0,23,gate_num).tolist()
if self.interleaved:
temp = [[x,self.interleaved_gate] for x in gate_sequence_fwd]
gate_sequence_fwd = list(itertools.chain.from_iterable(temp))
n_gate = 0
for m in gate_sequence_fwd:
n_gate = int(self.Cliford_trans[m,n_gate])
self.Cliford_last = n_gate
self.Cliford_last_dag = np.where(self.Cliford_trans[:,self.Cliford_last] == 0)[0][0]
self.gate_sequence[i].append(gate_sequence_fwd+[self.Cliford_last_dag.item()])
self._make_circuit()
def run(self):
access_token = self.backend.provider.access_token
data = {
"length_vector":self.length_vector,
"gate_sequence":self.gate_sequence,
"rep":self.rep,
"shots":self.shots,
"seed":self.seed,
"interleaved":self.interleaved
}
data = json.dumps(data)
kosakaq_json ={
'experiment': 'experiment',
'data': data,
'access_token': access_token,
'repetitions': 1,
'backend': self.backend.name,
}
header = {
"Authorization": "token " + access_token,
}
res = requests.post("http://192.168.11.85/job/", data=kosakaq_json, headers=header)
response = res.json()
res.raise_for_status()
self.job = KosakaQExperimentJob(self.backend, response['id'], access_token=self.backend.provider.access_token, qobj=data)
def result(self):
access_token = self.backend.provider.access_token
# get result
header = {
"Authorization": "Token " + access_token
}
result = requests.get(
self.backend.url + ('/job/'),
headers=header,
params={"jobid": self.job._job_id}
).json()
if result["qobjlist"][0][0]["result"] is None:
data = []
else:
data = [d.split() for d in result["qobjlist"][0][0]["result"].split("\n")]
data.pop(-1)
length = len(self.length_vector)
rep = len(data)//length
rem = len(data)%length
if (result['joblist'][0]['jobstatus'] == "ERROR") or (result['joblist'][0]['jobstatus'] == "QUEUED"):
raise
if not (rep == self.rep) and (result['joblist'][0]['jobstatus'] == "RUNNING"):
print("This job is running.")
result_data = []
for i in range(rep):
result_data.append([data[j] for j in range(i*length,(i+1)*length)])
result_data.append([data[j] for j in range(rep*length,rep*length+rem)])
self.result_data = result_data
# fitting
if rep>0:
# data
time = self.length_vector
self.sum_data = []
self.ave_data = []
print(length)
print(rep)
print(result_data)
for i in range(length):
sum_rep = 0
for j in range(rep):
sum_rep += int(result_data[j][i][0])
self.sum_data.append(sum_rep/self.shots)
self.ave_data.append(sum_rep/(self.shots*rep))
# fitting func
def exp_curve(parameter):
a, b, p = parameter
return a * (p**(time)) + b
def fit_func(parameter):
ycal = exp_curve(parameter)
residual = ycal - ave_data
return sum(abs(residual))
# optimize
ave_data = self.ave_data
bound = [(0,1),(0,10),(0.001,50)]
opts = differential_evolution(fit_func, bounds = bound)
self.opt = opts.x
print(f'a = {self.opt[0]}')
print(f'b = {self.opt[1]}')
print(f'p = {self.opt[2]}')
if self.interleaved == "":
print(f'F = {(self.opt[2]+1)/2}')
else:
print("interleavedの場合、フィデリティの計算には、interleavedではない時のデータが必要")
def plot(self):
time = np.linspace(0.01, self.length_vector[-1], 1000)
def exp_curve(parameter):
a, b, p = parameter
return a * (p**(time)) + b
plt.figure(dpi=1000)
plt.plot(time, exp_curve(self.opt), color = 'blue', label='fitting')
for i in range(len(self.result_data)):
for j in range(len(self.result_data[i])):
if i == 0 and j ==0:
pass
else:
plt.plot(self.length_vector[j], int(self.result_data[i][j][0])/self.shots, marker='.', ls='', color = 'gray')
plt.plot(self.length_vector[0], int(self.result_data[0][0][0])/self.shots, marker='.', ls='', color = 'gray', label='data')
plt.plot(self.length_vector, self.ave_data, marker='x', color = 'orange', ls='--', label='average')
plt.legend()
plt.title('randomized benchmarking')
plt.ylabel('Ground State Population')
plt.xlabel('Clifford Length')
plt.ylim(-0.1,1.1)
plt.show()
def set_job(self, job: KosakaQExperimentJob):
self.job = job
self.backend = job.backend()
data = json.loads(job.qobj["data"])
self.length_vector = data["length_vector"]
self.rep = data["rep"]
self.shots = data["shots"]
self.seed = data["seed"]
if not (data["interleaved"] == ""):
if data["interleaved"] == "X":
self.interleaved_gate = 1
elif data["interleaved"] == "Y":
self.interleaved_gate = 2
elif data["interleaved"] == "Z":
self.interleaved_gate = 3
else:
raise
self.gate_sequence = []
self.circuits = []
self.result_data = None
self.ops = None
def _make_circuit(self):
self.circuits = []
for rep, i in zip(self.gate_sequence,range(self.rep)):
self.circuits.append([])
for gates in rep:
qc = QuantumCircuit(1,1)
for gate in gates:
if gate == 0:
qc.i(0)
elif gate == 1:
qc.x(0)
elif gate == 2:
qc.y(0)
elif gate == 3:
qc.z(0)
elif gate == 4:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.z(0)
elif gate == 5:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
elif gate == 6:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.y(0)
elif gate == 7:
qc.h(0)
qc.s(0)
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 8:
qc.h(0)
qc.s(0)
qc.z(0)
elif gate == 9:
qc.h(0)
qc.s(0)
elif gate == 10:
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 11:
qc.h(0)
qc.s(0)
qc.y(0)
elif gate == 12:
qc.s(0)
qc.h(0)
qc.s(0)
qc.x(0)
elif gate == 13:
qc.s(0)
qc.h(0)
qc.s(0)
elif gate == 14:
qc.h(0)
qc.z(0)
elif gate == 15:
qc.h(0)
qc.x(0)
elif gate == 16:
qc.sx(0)
qc.h(0)
qc.z(0)
qc.sxdg(0)
elif gate == 17:
qc.sx(0)
qc.h(0)
qc.x(0)
qc.sxdg(0)
elif gate == 18:
qc.h(0)
qc.z(0)
qc.x(0)
elif gate == 19:
qc.h(0)
qc.x(0)
qc.x(0)
elif gate == 20:
qc.sx(0)
qc.y(0)
elif gate == 21:
qc.sxdg(0)
qc.y(0)
elif gate == 22:
qc.s(0)
qc.x(0)
elif gate == 23:
qc.sxdg(0)
qc.h(0)
qc.z(0)
qc.sxdg(0)
qc.barrier(0)
qc.measure(0,0)
self.circuits[i].append(qc)
|
https://github.com/matheusmtta/Quantum-Machine-Learning
|
matheusmtta
|
import numpy as np
import networkx as nx
import timeit
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut
from qiskit.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals, QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 6 nodes
n = 6 # 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), (1, 3, 1.0), (2, 4, 1.0), (3, 5, 1.0), (4, 5, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["y" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.6, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, 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)
def brute():
max_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if cost > max_cost_brute:
max_cost_brute = cost
xmax_brute = x
max_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] # create reverse of binary combinations from 0 to 2**n to create every possible set
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if cost > max_cost_brute:
max_cost_brute = cost
xmax_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["m" if xmax_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xmax_brute) + " with cost = " + str(max_cost_brute))
time = timeit.timeit(brute, number = 1)
print(f"\nTime taken for brute force: {time}")
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.export_as_lp_string())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
def classical_eigen():
result = exact.solve(qp)
result = exact.solve(qp)
print(result)
time = timeit.timeit(classical_eigen, number = 1)
print(f"\nTime taken for exact classical eigensolver force: {time}")
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["m" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 99
seed = 1010
backend = Aer.get_backend("aer_simulator_statevector")
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
# construct VQE
spsa = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = VQE(ry, optimizer=spsa, quantum_instance=quantum_instance)
# run VQE
# def vqe_solve():
# result = vqe.compute_minimum_eigenvalue(qubitOp)
# time = timeit.timeit(vqe_solve, number = 1)
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# print(f"\nTime taken for VQE: {time}")
# plot results
colors = ["m" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on VQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result)
colors = ["m" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
|
https://github.com/matheusmtta/Quantum-Machine-Learning
|
matheusmtta
|
import numpy as np
import pennylane as qml
from pennylane.optimize import NesterovMomentumOptimizer
n = 6
backend = qml.device("default.qubit", wires = n)
def layerBlock(wgt):
for q_i in range(n):
qml.Rot(wgt[q_i, 0], wgt[q_i, 1], wgt[q_i, 2], wires = q_i)
for q_i in range(n):
qml.CNOT(wires = [q_i, (q_i+1)%n])
def preparation(x_n):
qb = [i for i in range(n)]
qml.BasisState(x_n, wires=qb)
@qml.qnode(backend)
def circuit(weights, x_n = None):
preparation(x_n)
for w in weights:
layerBlock(w)
return qml.expval(qml.PauliZ(0))
def variationalCircuit(param, x_n = None):
weights = param[0]
bias = param[1]
return circuit(weights, x_n = x_n) + bias
def squareLoss(target, predictions):
loss = 0
for l, p in zip(target, predictions):
loss += (l - p) ** 2
loss /= len(target)
return loss
def accuracy(target, predictions):
loss = 0
for l, p in zip(target, predictions):
if abs(l - p) < 1e-5:
loss += 1
loss /= len(target)
return loss
def cost(param, x_n, y_n):
predictions = [variationalCircuit(param, x_n = x) for x in x_n]
return squareLoss(y_n, predictions)
data = np.loadtxt("data/dataset1.txt")
dataset = data[:, :n]
target = data[:, n]
#maps {0, 1} -> {-1, 1}
target = target * 2 - np.ones(len(target))
np.random.seed(0)
blocks = 3
m = 4
initialParams = (0.01 * np.random.randn(blocks, n, m), 0.0)
optimizer = NesterovMomentumOptimizer(0.5)
batchSize = 5
params = initialParams
steps = 15
for i in range(steps):
batchIdx = np.random.randint(0, len(dataset), (batchSize,))
batchX = dataset[batchIdx]
batchY = target[batchIdx]
params = optimizer.step(lambda f :cost(f, batchX, batchY), params)
predictions = [np.sign(variationalCircuit(params, x)) for x in dataset]
acc = accuracy(target, predictions)
print(
"Step: {:5d} | Cost: {:0.7f} | Accuracy: {:0.7f} ".format(
i + 1, cost(params, dataset, target), acc
)
)
|
https://github.com/matheusmtta/Quantum-Machine-Learning
|
matheusmtta
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=4
max_qubits=15 #reference files are upto 12 Qubits only
skip_qubits=2
max_circuits=3
num_shots=4092
gate_counts_plots = 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
#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
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
from qiskit.opflow import PauliTrotterEvolution, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
import time,os,json
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 = "VQE 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)
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 for display
QC_ = None
Hf_ = None
CO_ = None
################### Circuit Definition #######################################
# Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
# param: n_spin_orbs - The number of spin orbitals.
# return: return a Qiskit circuit for this VQE ansatz
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name=f"vqe-ansatz({method})-{num_qubits}-{circuit_id}")
# initialize the HF state
Hf = HartreeFock(num_qubits, na, nb)
qc.append(Hf, qr)
# form the list of single and double excitations
excitationList = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
excitationList.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
excitationList.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp, excitationList[index])
# add to ansatz
qc.append(cluster_qc, [i for i in range(cluster_qc.num_qubits)])
# method 1, only compute the last term in the Hamiltonian
if method == 1:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
global normalization
normalization = 0.0
# add the first non-identity term
identity_qc = qc.copy()
identity_qc.measure_all()
qc_list.append(identity_qc) # add to circuit list
diag.append(qubit_op[1])
normalization += abs(qubit_op[1].coeffs[0]) # add to normalization factor
diag_coeff = abs(qubit_op[1].coeffs[0]) # add to coefficients of diagonal terms
# loop over rest of terms
for index, p in enumerate(qubit_op[2:]):
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# accumulate normalization
normalization += abs(p.coeffs[0])
# add to circuit list if non-diagonal
if not is_diag:
qc_list.append(qc_with_mea)
else:
diag_coeff += abs(p.coeffs[0])
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
# modify the name of diagonal circuit
qc_list[0].name = qubit_op[1].primitive.to_list()[0][0] + " " + str(np.real(diag_coeff))
normalization /= len(qc_list)
return qc_list
# Function that constructs the circuit for a given cluster operator
def ClusterOperatorCircuit(pauli_op, excitationIndex):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit(); qc.name = f'Cluster Op {excitationIndex}'
global CO_
if CO_ == None or qc.num_qubits <= 4:
if qc.num_qubits < 7: CO_ = qc
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=2):
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
# save circuit
global QC_
if QC_ == None or nqubit <= 4:
if nqubit < 7: QC_ = raw_qc
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb, name="Hf")
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# Save smaller circuit
global Hf_
if Hf_ == None or norb <= 4:
if norb < 7: Hf_ = qc
# return the circuit
return qc
################ Helper Functions
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(f'ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(f'Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
# 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(qc,references,num_qubits):
# total circuit name (pauli string + coefficient)
total_name = qc.name
# pauli string
pauli_string = total_name.split()[0]
# get the correct measurement
if (len(total_name.split()) == 2):
correct_dist = references[pauli_string]
else:
circuit_id = int(total_name.split()[2])
correct_dist = references[f"Qubits - {num_qubits} - {circuit_id}"]
return correct_dist,total_name
# Max qubits must be 12 since the referenced files only go to 12 qubits
MAX_QUBITS = 12
method = 1
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=2,
max_circuits=max_circuits, num_shots=num_shots):
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()
max_qubits = max(max_qubits, min_qubits) # max must be >= min
# validate parameters (smallest circuit is 4 qubits and largest is 10 qubits)
max_qubits = min(max_qubits, MAX_QUBITS)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
if method == 2: max_circuits = 1
if max_qubits < 4:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of VQE algorithm")
return
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 input_size in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# determine the number of circuits to execute for this group
num_circuits = min(3, max_circuits)
num_qubits = input_size
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# random seed
np.random.seed(0)
numckts.append(num_circuits)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# Method 1 (default)
if method == 1:
# loop over circuits
for circuit_id in range(num_circuits):
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
# method 2
elif method == 2:
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
print(qc_list)
print(f"************\nExecuting [{len(qc_list)}] circuits with num_qubits = {num_qubits}")
for qc in qc_list:
print("*********************************************")
#print(f"qc of {qc} qubits for qc_list value: {qc_list}")
# get circuit id
if method == 1:
circuit_id = qc.name.split()[2]
else:
circuit_id = qc.name.split()[0]
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
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
print("operations: ",operations)
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()
# load pre-computed data
if len(qc.name.split()) == 2:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit.json')
with open(filename) as f:
references = json.load(f)
else:
filename = os.path.join(f'_common/precalculated_data_{num_qubits}_qubit_method2.json')
with open(filename) as f:
references = json.load(f)
#Correct distribution to compare with counts
correct_dist,total_name = analyzer(qc,references,num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
print(fidelity_dict)
# modify fidelity based on the coefficient
if (len(total_name.split()) == 2):
fidelity_dict *= ( abs(float(total_name.split()[1])) / normalization )
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!")
print("\nHartree Fock Generator 'Hf' ="); print(Hf_ if Hf_ != None else " ... too large!")
print("\nCluster Operator Example 'Cluster Op' ="); print(CO_ if CO_ != None else " ... too large!")
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/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
import os
from flask import Flask, jsonify, request
import json
import requests
# New QISKit libraries
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
from qiskit import BasicAer
from qiskit.providers.aer import noise
from noisedev import setup_noise,emo_noise
def generateCircuit():
#collect params
req_data = request.get_json()
sim=req_data['set']
if sim:
json_output = {"emo":emo_noise(),"shots":400}
print(json_output)
#return jsonify(json_output)
return json_output #jsonify put in main welcome.py file due to errors
else:
rawEmoticon = req_data['emo']
operation = req_data['operation']
print(rawEmoticon)
emoticon = []
# split each emoticon in a list of 1s and 0s
for string in rawEmoticon:
print(string)
print(list(string))
emoticon.append(list(string))
print(" ")
print(emoticon)
# ======= MICHELE =============
A = emoticon[0]
B = emoticon[1]
qasm = []
posizione = []
for i in range(len(A)):
print(len(A)-i-1, A[i], B[i])
if A[i] == '0' and B[i] == '0' :
print("ok 0")
if A[i] == '1' and B[i] == '1' :
print("ok 1")
qasm.append("qc.x(qr["+str(len(A)-i-1)+"])")
print("QASM", qasm, i)
if A[i] != B[i] :
posizione.append(i)
print("posizione",(len(A)-i-1))
print("pos, A, B")
for j in range(len(posizione)):
if j == 0 :
qasm.append("qc.h(qr["+str(len(A) - posizione[j] -1)+"])")
else:
if A[posizione[0]] == A[posizione[j]] :
qasm.append("qc.cx(qr["+str(len(A) - posizione[0] -1)+"],qr["+str(len(A) - posizione[j] -1)+"])")
else:
qasm.append("qc.cx(qr["+str(len(A) - posizione[0] -1)+"],qr["+str(len(A) - posizione[j] -1)+"])")
qasm.append("qc.x(qr["+str(len(A) - posizione[j] -1)+"])")
print("======== qasm ==========")
print(qasm)
print("============= ==========")
# ========= END ===============
r = sendQuantum(qasm,len(A),sim)
print("collecting execution results")
print(r)
array_output = []
shots = 0
for key in r.keys():
array_output.append({"value": key,"shots": r[key]})
shots += r[key]
json_output = {"emo": array_output,"shots":shots}
print(json_output)
#return jsonify(json_output)
return json_output #jsonify put in main welcome.py file due to errors
def sendQuantum(commandList,qubitNr,operation):
qr = QuantumRegister(qubitNr)
cr = ClassicalRegister(qubitNr)
qc = QuantumCircuit(qr, cr)
for command in commandList:
print(command)
# insert check on command received
exec(command)
for j in range(qubitNr):
qc.measure(qr[j], cr[j])
# check if request is for simulator or real hardware
#b = "ibmq_qasm_simulator"
#back=IBMQ.get_backend(b)
#backend=Aer.backends()[0].name() ## deprecated way to call backand
backend = Aer.get_backend('qasm_simulator')
shots_sim = 400
print("executing algorithm")
job_exp = execute(qc, backend, shots=shots_sim)
stats_sim = job_exp.result().get_counts()
print(stats_sim)
return stats_sim
# show available backends
# IBMQ.backends()
# # find least busy backend
# backend = least_busy(IBMQ.backends(simulator=False))
# print("The least busy backend is " + backend.name())
# # execute on hardware
# job_exp = execute(qc, backend=backend, shots=1024, max_credits=3)
#backend = "ibmq_qasm_simulator"
#backend = "ibmqx5"
#shots_sim = 256
#print("executing algorithm")
# job_sim = execute(qc, backend, shots=shots_sim)
#job_exp = execute(qc, backend=IBMQ.get_backend(backend), shots=shots_sim)
#stats_sim = job_exp.result().get_counts()
#print(stats_sim)
#return stats_sim
def executeCircuit():
#collect params
commandList =[]
qubitNr = 0
print("collecting params")
req_data = request.get_json()
commandList = req_data['command']
qubitNr = req_data['qubitNr']
# set up registers and program
qr = QuantumRegister(qubitNr)
cr = ClassicalRegister(qubitNr)
qc = QuantumCircuit(qr, cr)
return json.dumps({"results": sendQuantum(commandList,qubitNr)})
|
https://github.com/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import Aer, IBMQ, execute
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
#IBMQ.enable_account(token, url='https://quantumexperience.ng.bluemix.net/api')
#IBMQ.active_accounts()
#IBMQ.backends()
def setup_noise(circuit,shots):
"""
This fucntion run a circuit on a simulated ibmq_16_melbourne device with noise
"""
# Basic device noise model
# List of gate times
# Note that the None parameter for u1, u2, u3 is because gate
# times are the same for all qubits
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)
]
device = IBMQ.get_backend('ibmq_16_melbourne')
properties = device.properties()
coupling_map = device.configuration().coupling_map
# 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
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute noisy simulation and get counts
result_noise = execute(circuit, simulator,shots=shots,noise_model=noise_model,
coupling_map=coupling_map, basis_gates=basis_gates).result().get_counts(circuit)
# print(result_noise)
#counts_noise = result_noise.get_counts(circ)
return result_noise
def emo_noise():
"""
This function simulate the emoticon function with noise, to perform noise we are limited to use
just a streactly set of emoticon because of constraints coming from the real device.
"""
# set up registers and program
qr = QuantumRegister(14)
cr = ClassicalRegister(14)
qc = QuantumCircuit(qr, cr)
# rightmost seven (qu)bits have ')' = 0101001
qc.x(qr[0])
qc.x(qr[3])
qc.x(qr[5])
# second seven (qu)bits have superposition of
# '8' = 0111000
# ';' = 0111011
# these differ only on the rightmost two bits
qc.h(qr[8]) # create superposition on 9
qc.cx(qr[8],qr[7]) # spread it to 8 with a CNOT
qc.x(qr[10])
qc.x(qr[11])
qc.x(qr[12])
# measure
for j in range(14):
qc.measure(qr[j], cr[j])
shots=400
## RUN THE SIMULATION
return synt_chr(setup_noise(qc,shots))
def synt_chr(stats, shots=None):
"""
This function transforms the binary the string of bits into ascii character
"""
n_list=[]
for bitString in stats:
char = chr(int( bitString[0:7] ,2)) # get string of the leftmost 7 bits and convert to an ASCII character
char += chr(int( bitString[7:14] ,2)) # do the same for string of rightmost 7 bits, and add it to the previous character
#prob = stats[bitString] / shots # fraction of shots for which this result occurred
n_list.append({"shots":stats[bitString],"value":char})
return n_list
def setup_noise_s(circuit,shots):
"""
This fucntion run a circuit on a simulated ibmq_16_melbourne device with noise
"""
# Basic device noise model
# List of gate times
# Note that the None parameter for u1, u2, u3 is because gate
# times are the same for all qubits
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)
]
device = IBMQ.get_backend('ibmq_16_melbourne')
properties = device.properties()
coupling_map = device.configuration().coupling_map
# 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
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute noisy simulation and get counts
result_noise = execute(circuit, simulator,shots=shots,noise_model=noise_model,
coupling_map=coupling_map, basis_gates=basis_gates).result()
# print(result_noise)
#counts_noise = result_noise.get_counts(circ)
return result_noise
|
https://github.com/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
import os
from flask import Flask, jsonify, request
import json
import requests
# New QISKit libraries
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
#from qiskit.backends.ibmq import least_busy
from qiskit import Aer
backend = Aer.get_backend('qasm_simulator')
# Visualization libraries
from qiskit.tools.visualization import plot_bloch_vector
from qutip import Bloch,basis
import qutip as qq
import numpy as np
import math as m
from IPython.core.pylabtools import print_figure
# Import noise function
from noisedev import setup_noise
def applyOperators(): ### TEST THE ENANCHEMENTS: requirements (enlarge the JSON comprending the base choice)
"""
This function is activated by the "makeReq" in the JS file. It works perfoming the gate action on the qubit in the defined basis.
INCOME:
Json: {gate:"string",base:"string"}
OUTCOME:
Json:{op:"string",img1:"svg",img2:"svg"}
NB:The image is given in sgv format because in this way we can send it by json.
"""
print('start function applyOperators')
data = request.get_json()
print('=== input data ===')
print(data)
print('==========')
gate= data['f1']
base= data['base']
sett= data['set']
#base="z"
print('invoke function for images creation')
images = func(gate,base,sett) # call the function that returns the bloch-spheres images
if "h" == gate:
op = "Hadarmand Gate"
elif "x" == gate:
op = "Bit Flip Gate"
elif "s" == gate:
op = "S operator"
elif "sdg" == gate:
op = "Sc operator"
elif "z" == gate:
op = "Z operator"
elif "t" == gate:
op = "T operator"
elif "tdg" == gate:
op = "Tc operator"
# res = json.dumps({"op": op, "img":images[0], "img2": images[1]})
res = {"op": op, "img":images[0], "img2": images[1]}
return res
# test
def func(f1,b,set):
"""
This function Perform the gate application on the initial state of qubit and then the state tomography,
at the same time compute the analytical bloch state.
INCOME:
f1="string", b="string"
fig_data="svg",fig_data2="svg"
"""
#### Create the bloch-sphere on qutip
b1=Bloch()
b2=Bloch()
## create the analyical quantum state and perform tranformation
## Add states to the bloch sphere and plot it
b1.add_states(analytic(f1,b))
if not set:
states=qtomography(f1,b)
b2.add_vectors(states)
else:
### implements for
states=qtomography_s(f1,b)
for i in states: b2.add_points(i)
b2.add_vectors(np.average(states,axis=0))
###
b2.render()
fig_data = print_figure(b2.fig, 'svg')
b1.render()
fig_data2 = print_figure(b1.fig, 'svg')
#b1.show()
#b2.show()
b1.clear()
b2.clear()
return fig_data, fig_data2
def qtomography(f1,b):
"""
This function perform the tomography on the quantum state and starting from the operator and the basis
returs the recontruction of the quantum state.
See the reference:
https://quantumexperience.ng.bluemix.net/proxy/tutorial/full-user-guide/002-The_Weird_and_Wonderful_World_of_the_Qubit/005-The_Bloch_Sphere.html
INCOME:
f1="char" -> operator acting on the initial state
b="char" -> basis on which is expressed the initial state
OUTCOME:
blo="3d vector" -> resulting vector expressed as 3d vector
"""
# let's define the Registers
q=QuantumRegister(1)
c=ClassicalRegister(1)
# Build the circuits
pre = QuantumCircuit(q, c)
### TEST IF CONTROLS, the values (x,y,z) have to be the same trasmetted from the json
if b == "x":
pre.h(q)
elif b == "y":
print(b)
pre.h(q)
pre.s(q)
#elif b == "z":
#pre.h(q)
pre.barrier()
#measuerement circuits
# X
meas_x = QuantumCircuit(q, c)
meas_x.barrier()
meas_x.h(q)
meas_x.measure(q, c)
# Y
meas_y = QuantumCircuit(q, c)
meas_y.barrier()
meas_y.s(q).inverse()
meas_y.h(q)
meas_y.measure(q, c)
# Z
meas_z = QuantumCircuit(q, c)
meas_z.barrier()
meas_z.measure(q, c)
bloch_vector = ['x', 'y', 'z']
circuits = []
for exp_index in range(3):
# Circuit where it's applied the operator that we want to plot
middle = QuantumCircuit(q, c)
# let's put here the operator of which we want know the action on the bloch-sphere #### F1
method_to_call = getattr(middle, f1)
method_to_call(q)
####
circuits.append(pre + middle + meas_x)
circuits.append(pre + middle + meas_y)
circuits.append(pre + middle + meas_z)
# Execute the circuit
job = execute(circuits, backend , shots=1024)
result = job.result()
num=1
# Plot the result
blo=[]
for exp_index in range(num):
bloch = [0, 0, 0]
for bloch_index in range(len(bloch_vector)):
data = result.get_counts(circuits[exp_index+bloch_index])
try:
p0 = data['0']/1024.0
except KeyError:
p0 = 0
try:
p1 = data['1']/1024.0
except KeyError:
p1 = 0
bloch[bloch_index] = p0-p1
blo.append(bloch)
return(blo)
def analytic(f1,b):
print('start function analytic')
"""
This function compute the analytical calculation of the gate application on the zero qubit
INCOME:
f1="char" -> argument that defines the operator
b="char" -> argument that defines the choosen basis
OUTCOME:
st="qutip-Bloch().state_vector" -> Bloch() is an element from the quitip library
"""
#find the right base
vec=np.array([1,0]) # vector expressed in the z base
h=np.array([[1,1],[1,-1]])*1/m.sqrt(2)
s=np.array([[1,0],[0,1j]])
if b=="x":
vec=h@vec
if b=="y":
vec=s@h@vec
# find the operator
if f1=='h':
opp=h
elif f1=='x':
opp=np.array([[0,1],[1,0]])
elif f1=='z':
opp=np.array([[1,0],[0,-1]])
elif f1=='s':
opp=s
elif f1=='sdg':
opp=np.matrix.conjugate(s)
elif f1=='t':
opp=np.array([[1,0],[0,np.exp(1j*m.pi/4)]])
elif f1=='tdg':
opp=np.array([[1,0],[0,np.exp(-1j*m.pi/4)]])
ar=opp@vec
st=(ar[0]*basis(2,0)+ar[1]*basis(2,1)).unit()
return(st)
def qtomography_s(f1,b):
shots_sim=128
points=25
list_vec=[]
# Define register
q=QuantumRegister(1)
c=ClassicalRegister(1)
# Build the circuits
pre = QuantumCircuit(q, c)
### TEST IF CONTROLS, the values (x,y,z) have to be the same trasmetted from the json
if b == "x":
pre.h(q)
elif b == "y":
print(b)
pre.h(q)
pre.s(q)
#elif b == "z":
#pre.h(q)
pre.barrier()
#measuerement circuits
# X
meas_x = QuantumCircuit(q, c)
meas_x.barrier()
meas_x.h(q)
meas_x.measure(q, c)
# Y
meas_y = QuantumCircuit(q, c)
meas_y.barrier()
meas_y.s(q).inverse()
meas_y.h(q)
meas_y.measure(q, c)
# Z
meas_z = QuantumCircuit(q, c)
meas_z.barrier()
meas_z.measure(q, c)
bloch_vector = ['x', 'y', 'z']
circuits = []
for exp_index in range(3):
# Circuit where it's applied the operator that we want to plot
middle = QuantumCircuit(q, c)
# let's put here the operator of which we want know the action on the bloch-sphere #### F1
method_to_call = getattr(middle, f1)
method_to_call(q)
####
circuits.append(pre + middle + meas_x)
circuits.append(pre + middle + meas_y)
circuits.append(pre + middle + meas_z)
for i in range(points):
#### CLASSICAL SIMULATION
job = execute(circuits, backend = Aer.get_backend('qasm_simulator'), shots=shots_sim)
####
result = job.result()
bloch = [0, 0, 0]
nums=[]
noise_vec=[]
for bloch_index in range(len(bloch_vector)):
data = result.get_counts(circuits[bloch_index])
try:
p0 = data['0']/shots_sim
except KeyError:
p0 = 0
try:
p1 = data['1']/shots_sim
except KeyError:
p1 = 0
bloch[bloch_index] = p0-p1
list_vec.append(bloch)
return list_vec
|
https://github.com/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
# Copyright 2015 IBM Corp. All Rights Reserved.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import flask
import flask_login
import json
import requests
# New QISKit libraries
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
#from qiskit.backends.ibmq import least_busy
# Visualization libraries
import numpy as np
from spheres import applyOperators
# Custom libraries
from emoticons import generateCircuit, executeCircuit
# Read config.json file
with open('config.json') as f:
credentials_file = json.load(f)
# QISKit authentication
print('loading credentials')
# IBMQ.load_accounts()
IBMQ.enable_account(credentials_file['IBMQ']['apikey'])
print('printing backends')
backends = IBMQ.backends()
print("========")
print(backends)
print('finished printing')
app = flask.Flask(__name__)
jsonify = flask.jsonify
# # === Start Login ====
# app.secret_key = 'italy ibm q application pythonQ'
# login_manager = flask_login.LoginManager()
# login_manager.init_app(app)
# # Mock database
# users = {credentials_file['user']['mail']: {'password': credentials_file['user']['password']}}
# class User(flask_login.UserMixin):
# pass
#
# @login_manager.user_loader
# def user_loader(email):
# if email not in users:
# return
#
# user = User()
# user.id = email
# return user
#
# @login_manager.request_loader
# def request_loader(request):
# email = request.form.get('email')
# if email not in users:
# return
#
# user = User()
# user.id = email
#
# # DO NOT ever store passwords in plaintext and always compare password
# # hashes using constant-time comparison!
# user.is_authenticated = request.form['password'] == users[email]['password']
#
# return user
#
# @app.route('/login', methods=['GET', 'POST'])
# def login():
# if flask.request.method == 'GET':
# return app.send_static_file('login.html')
#
# email = flask.request.form['email']
# if email in users.keys():
# if flask.request.form['password'] == users[email]['password']:
# user = User()
# user.id = email
# flask_login.login_user(user)
# return app.send_static_file('dashboard.html') # Redirect to landing page
#
# return '''<p>Invalid login, try again</p>'''
#
# @login_manager.unauthorized_handler
# def unauthorized_handler():
# return app.send_static_file('login.html')
#
# # === End Login ===
# @app.route('/', methods=['GET', 'POST'])
# @flask_login.login_required
# def Welcome():
# return app.send_static_file('login.html')
@app.route('/', methods=['GET', 'POST'])
# @flask_login.login_required
def Welcome():
return app.send_static_file('dashboard.html')
@app.route('/dashboard',methods=['GET', 'POST'])
# @flask_login.login_required
def Dashboard():
return app.send_static_file('dashboard.html')
@app.route('/spheres', methods=['GET', 'POST'])
# @flask_login.login_required
def Spheres():
return app.send_static_file('spheres.html')
@app.route('/docs', methods=['GET', 'POST'])
# @flask_login.login_required
def Docs():
return app.send_static_file('docs.html')
@app.route('/team', methods=['GET', 'POST'])
# @flask_login.login_required
def Team():
return app.send_static_file('team.html')
@app.route('/publications', methods=['GET', 'POST'])
# @flask_login.login_required
def Publications():
return app.send_static_file('publications.html')
@app.route('/emoticons', methods=['GET', 'POST'])
# @flask_login.login_required
def Emoticons():
return app.send_static_file('emoticons.html')
@app.route('/generateCircuit', methods=['POST'])
def genCirc():
return jsonify(generateCircuit())
#@app.route('/executeCircuit', methods=['POST'])
#def exeCirc():
@app.route('/applyOperators', methods=["POST"])
def appOper():
print('received POST applyOp')
res = applyOperators()
return jsonify(res)
@app.route('/visualize3d', methods=['GET','POST'])
def sphere():
return app.send_static_file('visualize3d.html')
port = os.getenv('PORT', '5000')
if __name__ == "__main__":
# app.debug = True
app.run(host='0.0.0.0', port=int(port),threaded=True)
|
https://github.com/kevinab107/QiskitPulseRL
|
kevinab107
|
# Install the dependencies
!pip install tensorflow
!pip install -q tf-agents
!pip install qiskit
!pip install numpy
!pip3 uninstall protobuf --yes
!pip3 uninstall python-protobuf --yes
!pip install protobuf
from pulseRL.environment import QiskitEnv
import numpy as np
from tf_agents.environments import tf_py_environment
from pulseRL.agent import Agent
from qiskit.visualization import plot_bloch_multivector
import matplotlib as plt
# Learning Parameters
num_iterations = 1000
#In an iteration multiple episodes are collected together and a trajectory is built out of it.
#Later these trajectory is used for learning. Trajectory is added to a replay buffer and analysed together.
collect_episodes_per_iteration = 250 #
replay_buffer_capacity = 2000
learning_rate = 1e-3
num_eval_episodes = 2
eval_interval = 50
num_intervals = 10
interval_length = 60
"""Enviroment which make use of Qiskit Pulse Simulator and pulse builder to simulate
the dynamics of a qubit under the influence of a pulse. The RL agent interact with this
environment through action defined as pulse lenght. Here a constant pulse of amplitude 1
is used and applied for a time "pulse width". "pulse width" is the action that the agent
takes here. The agent observes the state obtained with the action along with the Fidelity
to the expected final state. Here initial state is fixed to |0> and target state is |1>
The pulse is designed as follows
The process time is divided into "num_intervals" of length "interval_length".
For each interval a constant amplitude of range(0,1) is defined by the agent
delay the mesearement channel for num_intervals*interval_length + 10 time and make mesurement.
TODO: Make the environement more gernect to handle different operators and initial states"""
environment = QiskitEnv(np.array([1,0]), num_intervals, interval_length)
#convert the python environment to tensorflow compactible format for training.
tf_dumm = tf_py_environment.TFPyEnvironment(environment)
"""Get the reinfoce agent. Reward is the fielily to target state. Observation is the state"""
agent = Agent(num_iterations, collect_episodes_per_iteration, replay_buffer_capacity, learning_rate, num_eval_episodes, eval_interval, num_intervals, interval_length)
agent_reinforce = agent.get_agent(environment, 'reinforce', "without_noise_trained")
train_results = agent.train(tf_dumm, agent_reinforce)
# useful to save the policy for later usage:
from tf_agents.policies import policy_saver
policy_dir = "policy"
tf_policy_saver = policy_saver.PolicySaver(agent_reinforce.policy)
tf_policy_saver.save(policy_dir)
env_test = QiskitEnv(np.array([0,1]),5,100)
vector, fid, action, pulse_prog = agent.evaluate(agent_reinforce, env_test)
print("Fidelity : ", fid)
control_pulse = [act.numpy()[0][0] for act in action]
print("Control pulse", control_pulse)
env_test.get_state(control_pulse)
#plot_bloch_multivector(vector)
pulse_prog.draw()
import tensorflow as tf
import numpy as np
from tensorflow.saved_model import load
from tf_agents import policies
from pulseRL.environment import QiskitEnv
import warnings
import logging, sys
def evaluate(policy, eval_py_env):
eval_env = tf_py_environment.TFPyEnvironment(eval_py_env)
num_episodes = 1
fidelity = []
actions = []
for _ in range(num_episodes):
time_step = eval_env.reset()
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = eval_env.step(action_step.action)
actions.append(action_step.action)
fidelity,state, pulse_prog = eval_py_env.get_state(actions)
return state, fidelity, actions,pulse_prog
env_test = QiskitEnv(np.array([0,1]),5,100)
policy_dir = "best_policy"
saved_policy = load(policy_dir)
state, fidelity, actions, pulse_prog = evaluate(saved_policy,env_test)
print("Showing the results of the best policy")
print("Fidelity : ",fidelity)
print("Initial State: ", [1,0])
print("Final State: ", state)
print("\n\n")
pulse_prog.draw()
plt.pyplot.plot(train_results[2])
|
https://github.com/kevinab107/QiskitPulseRL
|
kevinab107
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import numpy as np
import math
from qiskit.quantum_info import state_fidelity
from qiskit.pulse import DriveChannel
from qiskit.compiler import assemble
from qiskit.qobj.utils import MeasLevel, MeasReturnType
# The pulse simulator
from qiskit.providers.aer import PulseSimulator
from qiskit import pulse
# Object for representing physical models
from qiskit.providers.aer.pulse import PulseSystemModel
# Mock Armonk backend
from qiskit.test.mock.backends.armonk.fake_armonk import FakeArmonk
import tensorflow as tf
from tf_agents.environments import py_environment
from tf_agents.environments import tf_environment
from tf_agents.environments import tf_py_environment
from tf_agents.environments import utils
from tf_agents.specs import array_spec
from tf_agents.environments import wrappers
from tf_agents.environments import suite_gym
from tf_agents.trajectories import time_step as ts
from tf_agents.environments import validate_py_environment
class QiskitEnv(py_environment.PyEnvironment):
"""Environment which make use of Qiskit Pulse Simulator and pulse builder to simulate
the dynamics of a qubit under the influence of a pulse. The RL agent interact with this
environment through action defined as pulse length. Here a constant pulse of amplitude 1
is used and applied for a time "pulse width". "pulse width" is the action that the agent
takes here. The agent observes the state obtained with the action along with the Fidelity
to the expected final state"""
def __init__(self, initial_state, max_time_steps, interval_width):
# action spec which is the shape of the action. Here it is (1,) ie the pulse length
self._action_spec = array_spec.BoundedArraySpec(
shape=(1,), dtype=np.float32, minimum=0, maximum=1, name="action"
)
# Observation spec which is the shape of the observation. It is of the form [real part of |0>, imag part of |0>, real part of |1>, imag part of |1>]
self._observation_spec = array_spec.BoundedArraySpec(
shape=(4,), dtype=np.float32, minimum=0, maximum=1, name="observation"
)
self._state = np.array([1, 0]) # | 0 >
self._episode_ended = False
# Closeness to the final state defined for this program as [0,1]
self.fidelity = 0
# Time stamp
self.time_stamp = 0
self.max_fidelity = 0
# initial state is [1,0]
self.initial_state = initial_state
# Maximum time steps
self.max_stamp = max_time_steps
self.interval_width = interval_width
self.actions_list = []
def action_spec(self):
return self._action_spec
def observation_spec(self):
return self._observation_spec
def render(self):
return self.fidelity
def _reset(self):
"""
reset the state. tensorflow provides the state restart()
"""
self._episode_ended = False
self.fidelity = 0
self.time_stamp = 0
self.max_fidelity = 0
self.actions_list = []
# self.gamma = [random.uniform(0, 1), random.uniform(0, 1)]
return ts.restart(np.array([0, 0, 1, 0], dtype=np.float32))
def _step(self, action):
"""
Result of interaction by agent with the environment.
action is the pulse length
Returns one of the tensorflow state which has the observation and
reward information corresponding to the action
- termination (If the interaction has stopped due to max timesteps)
- transition (Transition from one state to another)
"""
# Set episode ended to True if max time steps has exceeded
# Terminate with reset in that case
self.time_stamp += 1
if self.time_stamp > self.max_stamp:
self._episode_ended = True
else:
self._episode_ended = False
if self._episode_ended:
self.max_fidelity = 0
self.actions_list = []
return ts.termination(np.array([0, 0, 1, 0], dtype=np.float32), 0)
# Get the new state and fidelity
new_fidelity, state = self.get_transition_fidelity(action)
# reward = 2*new_fidelity - self.fidelity - self.max_fidelity
# reward = reward if reward > 0 else 0
# reward = new_fidelity
reward = new_fidelity
self.fidelity = new_fidelity
self.max_fidelity = (
new_fidelity if new_fidelity > self.max_fidelity else self.max_fidelity
)
observation = [state[0].real, state[0].imag, state[1].real, state[1].imag]
# Set the rewards and state. Reward is only for the final state (of last time interval) achieved and not for the intermediate
# states. ies if its a transition from final state and the process has not terminated, then reward is zero.
# The neural network will learn to adjust the amplitudes by just looking at the final time step reward
if self.time_stamp == self.max_stamp:
self.max_fidelity = 0
self.fidelity = 0
# self.gamma = [random.uniform(0, 1), random.uniform(0, 1)]
return ts.termination(
np.array(observation, dtype=np.float32), reward=reward
)
else:
return ts.transition(
np.array(observation, dtype=np.float32), reward=reward / 10
)
def get_transition_fidelity(self, amplitude):
"""
Build the pulse based on the action and invoke a IBM Q backend and run the experiment.Simulator is used
here.
1. Divide the pulse schedule into discrete intervals of constant length. (Piecewise Constants)
2. Build a pulse schedule with qiskit pulse with amplitude for each interval of the pulse as an input.
The schedule is then a function of amplitude of the pulse, followed by a measurement at the end of the drive.
3. At each time step all the all the pulse amplitudes derived till the time step is used. This is contained in the
actions_list. actions_list is reset after a single episode
"""
armonk_backend = FakeArmonk()
freq_est = 4.97e9
drive_est = 6.35e7
armonk_backend.defaults().qubit_freq_est = [freq_est]
# Define the hamiltonian to avoid randomness
armonk_backend.configuration().hamiltonian["h_str"] = [
"wq0*0.5*(I0-Z0)",
"omegad0*X0||D0",
]
armonk_backend.configuration().hamiltonian["vars"] = {
"wq0": 2 * np.pi * freq_est,
"omegad0": drive_est,
}
armonk_backend.configuration().hamiltonian["qub"] = {"0": 2}
armonk_backend.configuration().dt = 2.2222222222222221e-10
armonk_model = PulseSystemModel.from_backend(armonk_backend)
self.actions_list += [amplitude]
# build the pulse
with pulse.build(
name="pulse_programming_in", backend=armonk_backend
) as pulse_prog:
dc = pulse.DriveChannel(0)
ac = pulse.acquire_channel(0)
for action in self.actions_list:
pulse.play([action] * self.interval_width, dc)
pulse.delay(self.interval_width * len(self.actions_list) + 10, ac)
mem_slot = pulse.measure(0)
# Simulate the pulse
backend_sim = PulseSimulator(system_model=armonk_model)
qobj = assemble(pulse_prog, backend=backend_sim, meas_return="avg", shots=512)
sim_result = backend_sim.run(qobj).result()
vector = sim_result.get_statevector()
fid = state_fidelity(np.array([0, 1]), vector)
return fid, vector
# if __name__ == "__main__":
# environment = QiskitEnv(np.array([0,1]),100)
# validate_py_environment(environment, episodes=5)
def get_state(self, actions):
"""
Build the pulse based on the action and invoke a IBM Q backend and run the experiment.Simulator is used
here.
"""
armonk_backend = FakeArmonk()
freq_est = 4.97e9
drive_est = 6.35e7
armonk_backend.defaults().qubit_freq_est = [freq_est]
# Define the hamiltonian to avoid randomness
armonk_backend.configuration().hamiltonian["h_str"] = [
"wq0*0.5*(I0-Z0)",
"omegad0*X0||D0",
]
armonk_backend.configuration().hamiltonian["vars"] = {
"wq0": 2 * np.pi * freq_est,
"omegad0": drive_est,
}
armonk_backend.configuration().hamiltonian["qub"] = {"0": 2}
armonk_backend.configuration().dt = 2.2222222222222221e-10
armonk_model = PulseSystemModel.from_backend(armonk_backend)
# build the pulse
with pulse.build(
name="pulse_programming_in", backend=armonk_backend
) as pulse_prog:
dc = pulse.DriveChannel(0)
ac = pulse.acquire_channel(0)
for action in actions:
pulse.play([action] * self.interval_width, dc)
pulse.delay(self.interval_width * len(self.actions_list) + 10, ac)
mem_slot = pulse.measure(0)
# Simulate the pulse
backend_sim = PulseSimulator(system_model=armonk_model)
qobj = assemble(pulse_prog, backend=backend_sim, meas_return="avg", shots=512)
sim_result = backend_sim.run(qobj).result()
vector = sim_result.get_statevector()
fid = state_fidelity(np.array([0, 1]), vector)
pulse_prog.draw()
return fid, vector, pulse_prog
@staticmethod
def get_tf_environment(max_step, interval_width):
"""Return the tensorflow environment of the python environment"""
py_env = QiskitEnv(np.array([1, 0]), max_step, interval_width)
tf_env = tf_py_environment.TFPyEnvironment(py_env)
return tf_env
|
https://github.com/andrewwack/Qiskit-primtives-bell-state
|
andrewwack
|
from qiskit import QuantumCircuit
from qiskit.primitives import Sampler, BackendSampler
from qiskit.circuit.library import *
from qiskit.circuit.random import random_circuit
from qiskit.visualization import plot_histogram, array_to_latex, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit_ibm_runtime import Sampler, QiskitRuntimeService, Options, Session
from qiskit.providers.fake_provider import FakeManila
from qiskit_aer.noise import NoiseModel
import numpy as np
print('X (1q gate)')
xgate = XGate()
array_to_latex(xgate.to_matrix())
qc_x = QuantumCircuit(1)
qc_x.x(0)
qc_x.draw('mpl', scale=1.5)
state = Statevector(qc_x)
plot_bloch_multivector(state)
qc_x = QuantumCircuit(1,1)
qc_x.x(0)
qc_x.measure([0],[0])
qc_x.draw('mpl', scale=1.5)
# load the service and set the backend to the simulator
service = QiskitRuntimeService(channel="ibm_quantum")
backend = "ibmq_qasm_simulator"
# Make a noise model
fake_backend = FakeManila()
noise_model = NoiseModel.from_backend(fake_backend)
# Set options to include the noise model
options = Options()
options.simulator = {
"noise_model": noise_model,
"basis_gates": fake_backend.configuration().basis_gates,
"coupling_map": fake_backend.configuration().coupling_map,
"seed_simulator": 42
}
# Set number of shots, optimization_level and resilience_level
options.execution.shots = 1000
options.optimization_level = 0
options.resilience_level = 0
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc_x)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
print('H (1q gate)')
hgate = HGate()
array_to_latex(hgate.to_matrix())
qc_h = QuantumCircuit(1,1)
qc_h.h(0)
qc_h.draw('mpl', scale=1.5)
state = Statevector(qc_h)
plot_bloch_multivector(state)
qc_h.measure([0],[0])
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc_h)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
options.resilience_level = 1 # add in M3 measurement mitigation
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc_h)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
qc_cx = QuantumCircuit(2)
qc_cx.cx(0,1)
qc_cx.draw('mpl')
print('CX (2q gate)')
cxgate = CXGate()
array_to_latex(cxgate.to_matrix())
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
qc2.h(1)
qc2.draw('mpl', scale=1.5)
state = Statevector(qc2)
plot_bloch_multivector(state)
qc2.measure([0,1],[0,1])
options.resilience_level = 0 # no error mitigation
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc2)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
options.resilience_level = 1 # add in M3 measurement mitigation
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc2)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
qc_bell = QuantumCircuit(2, 2)
qc_bell.h(0)
qc_bell.cx(0,1)
qc_bell.draw('mpl')
state = Statevector(qc_bell)
plot_bloch_multivector(state)
qc_bell.measure([0,1],[0,1]) # add the measurement
options.resilience_level = 0 # no mitigation
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc_bell)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
options.resilience_level = 1 # add in M3 measurement mitigation
with Session(service=service, backend=backend):
sampler = Sampler(options=options)
job = sampler.run(qc_bell)
result_prob = job.result().quasi_dists[0].binary_probabilities()
plot_histogram(result_prob)
print(result_prob)
least_busy_device = service.least_busy(filters=lambda b: b.configuration().simulator==False)
least_busy_device
hw_result = None
with Session(service, backend=least_busy_device) as session:
options = Options(resilience_level=0)
sampler0 = Sampler(options=options)
options = Options(resilience_level=1)
sampler1 = Sampler(options=options)
job0 = sampler0.run(circuits=[qc_bell], shots=8000)
job1 = sampler1.run(circuits=[qc_bell], shots=8000)
# You can see that the results are quasi probabilities, not counts
hw_results = [job0.result().quasi_dists[0].binary_probabilities(),
job1.result().quasi_dists[0].binary_probabilities()]
print('Results resilience level 0 ', hw_results[0])
print('Results resilience level 1 ', hw_results[1])
plot_histogram(hw_results, legend=['resilience 0', 'resilience 1'])
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import QuantumCircuit
alice_key = '11100100010001001001001000001111111110100100100100010010010001010100010100100100101011111110001010100010010001001010010010110010'
alice_bases = '11000110011000100001100101110000111010011001111111110100010111010100000100011001101010100001010010101011010001011001110011111111'
def alice_prepare_qubit(qubit_index):
## WRITE YOUR CODE HERE
qc = QuantumCircuit(1, 1)
if alice_key[qubit_index] == '1':
qc.x(0)
if alice_bases[qubit_index] == '1':
qc.h(0)
return qc
## WRITE YOUR CODE HERE
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
import matplotlib.pyplot as plt
from channel_class import Channel
#Bob Part
circ_bob = QuantumCircuit(3)
bob_channel = Channel(myport = 5001, remote_port = 5000)
#circ_bob.h(0)
#circ_bob.draw(output='mpl','test.png')
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
# Add new gates to circ2
circ_bob.x(0+offset)
#circ_bob.cx(0+offset, 1+offset)
#psi2 = Statevector.from_instruction(circ_bob)
import time
time.sleep(2)
to_tpc = bob_channel.send(circ_bob,[1])
circ_bob.draw()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
from qiskit.quantum_info import Statevector
#From Marc
import parser
#From Luca
import socket
from SocketChannel2 import SocketChannel
class Channel:
def __init__(self,slave_offset=0, myport=000, remote_port=000):
self._state_vector = None
self._arr_qubits = None
self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z']
self._master = True
self._offset = 0
self._slave_offset = slave_offset
self.realchannel = SocketChannel(myport, False)
TCP_IP = '127.0.0.1'
self.realchannel.connect(TCP_IP, remote_port)
self._circuit = None
def close(self):
try:
self.realchannel.kill()
except:
print("Exception: Thread still busy")
def send(self,circuit,arr_qubits):
self._state_vector = Statevector.from_instruction(circuit)
self._arr_qubits = arr_qubits
self._circuit = circuit
#From Marc
ser = parser.QSerializer()
ser.add_element('state_vector', self._state_vector)#self)
ser.add_element('is_master', self._master)#self)
ser.add_element('slave_offset', self._slave_offset)#self)
ser.add_element('is_master', self._master)#self)
ser.add_element('circuit', self._circuit)#self)
str_to_send = ser.encode()
#print(str_to_send.type())
#From Luca
message = str_to_send
channel = self.realchannel #SocketChannel()
channel.send(message)
channel.close()
## TODO: TCP THINGS
return self
def receive(self,circuit):#,recieve_channel): ## TODO: remove recieve as an input
#TODO: TCP things
#recieve_channel = TCP_STUFF
#From Luca
print('Wait to receive')
channel = self.realchannel #SocketChannel(port=5005, listen=True)
data = channel.receive()
# print("received stuff \o/")
#print("received data:", data)
channel.close()
#From Marc
ser2 = parser.QSerializer()
ser2.decode(data)
#recieve_channel = ser2.get_element('channel_class')
self._slave_offset = ser2.get_element('slave_offset')
if(ser2.get_element('is_master')):
self._master = False
self._offset = self._slave_offset
recieved_state_vector = ser2.get_element('state_vector')
new_circuit = QuantumCircuit(len(recieved_state_vector.dims()))
new_circuit.initialize(recieved_state_vector.data, range(len(recieved_state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
new_circuit = new_circuit + circuit
return ser2.get_element('circuit'), self._offset
return new_circuit, self._offset
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
import Protocols
ALICE_ADDR = 'localhost'
OSCAR_ADDR = 'localhost'
ALICE_PORT = 5008
OSCAR_PORT = 5009
def main():
# prepare message
Protocols.multiparty_2grover_local( ALICE_PORT, OSCAR_PORT )
pass
if __name__ == "__main__":
main()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
import Protocols
ALICE_ADDR = 'localhost'
OSCAR_ADDR = 'localhost'
ALICE_PORT = 5008
OSCAR_PORT = 5009
def main():
Protocols.oscar_sends('01', OSCAR_PORT, ALICE_PORT)
if __name__ == "__main__":
main()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
import Protocols
ALICE_ADDR = 'localhost'
BOB_ADDR = 'localhost'
ALICE_PORT = 5005
BOB_PORT = 5006
def main():
# prepare message
message = "Hello Qiskit!"
Protocols.send_a_qmail(message, ALICE_PORT, BOB_ADDR, BOB_PORT)
pass
if __name__ == "__main__":
main()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
import Protocols
ALICE_ADDR = 'localhost'
BOB_ADDR = 'localhost'
ALICE_PORT = 5005
BOB_PORT = 5006
def main():
Protocols.receive_a_qmail(BOB_PORT, ALICE_ADDR, ALICE_PORT, adversary=False)
pass
if __name__ == "__main__":
main()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
#!/usr/bin/env python3
from qiskit import *
from qiskit.quantum_info import Statevector
from textwrap import wrap
from random import randrange
from SocketChannel2 import SocketChannel
import pickle
from channel_class import Channel
import time
import numpy as np
# Quantum One-Time pad related methods
def str_to_lbin(message, bin_size=4):
"""
String to 8 bit binary per character
:message:str, the message
"""
clist = [ord(x) for x in message]
bins = ''.join([format(x,'08b') for x in clist])
return wrap(bins,bin_size)
def bins_to_str(lbin):
"""
Return a list of unicode characters into a message
:lbin:list(bin), a list of characters
"""
sbin = ''.join(lbin)
lbin8 = wrap(sbin, 8)
message = chr(int(lbin8[0],2))
for c in lbin8[1:]:
message+=chr(int(c,2))
return message
def encode_cinfo_to_qstate(cinfo_bin):
"""
Return the quantum state that encodes the binary
:cinfo_bin:str, string of binary contains the classical information
return :QuantumCircuit:
"""
nreg = len(cinfo_bin)
qcirc = QuantumCircuit(nreg, nreg)
for i,bit_i in enumerate(cinfo_bin[::-1]):
if int(bit_i):
qcirc.x(i)
return qcirc
def generate_otp_key(key_length):
"""
Generate key_length random key for one-time pad
"""
x_key=bin(randrange(2**key_length))[2:]
z_key=bin(randrange(2**key_length))[2:]
return {'x': x_key, 'z': z_key}
def otp_enc_dec(qcirc, otpkey):
"""
:qcirc:QuantumCircuit instance
:key:dict={x:, z:}
"""
r_x , r_z = otpkey['x'], otpkey['z']
for i,k in enumerate(zip(r_x,r_z)):
if k[0]:
qcirc.x(i)
if k[1]:
qcirc.z(i)
def qotp_send(qcirc, otpkey, qChannel=None):
"""
Quantum one-time pad
:qmessage:qiksit.QuantumCircuit
:otpkey: dict{x:int y:int}
:qChannel: quantum channel
"""
#Alice's part: encrypting
otp_enc_dec(qcirc, otpkey)
#Alice send the qubits
#TODO:Channel stuff
# send over Qchannel
qChannel.send(qcirc, [0,1,2,3])
time.sleep(1)
# #Bob receives qubits, and decrypt them
# otp_enc_dec(qcirc, otpkey)
#Bob measure the states, single shot
# simulator = Aer.get_backend('qasm_simulator')
# nqubit = len(otpkey['x'])
# for i in range(nqubit):
# qcirc.measure(range(nqubit), range(nqubit))
# counts = execute(qcirc, backend=simulator, shots = 1).result()
# output = list(counts.get_counts().keys())[0]
# return output
def send_a_qmail(message, port, destAddr, destPort, batch_size=4):
""" Alice sends to Bob a quantum email
:nqubit:int, the number of qubits
:message:str, the secret message that wants to be sent
"""
nqubit = batch_size
print('Alice wants to send %s'%message)
# Initialize with Bob
classicC = SocketChannel(port+10, False)
# connect to Bob
classicC.connect(destAddr, destPort+10)
#send message per batch bits
Lbins = str_to_lbin(message, batch_size)
#generate key
print('generating key...')
otpkey = generate_otp_key(len(Lbins)*batch_size)
print('X-encryption key %s'%otpkey['x'], 'Z-encryption key %s'%otpkey['z'])
# send key to Bob
classicC.send(pickle.dumps(otpkey))
print("I am Alice I sent:", otpkey)
# close the classic channel as we don't need it anymore
classicC.close()
time.sleep(2)
key_per_batch = [{'x':x,'z':z} for x,z in zip(wrap(otpkey['x'],batch_size),wrap(otpkey['z'],batch_size))]
# TODO: setup quantum channel
n_master = batch_size
n_slave = batch_size
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=destPort)
# bob_meas_results = [] # Bob
for bin_batch,k in zip(Lbins, key_per_batch):
print('Performing QOTP for string', bin_batch)
qcirc = encode_cinfo_to_qstate(bin_batch) # Alice
qotp_send(qcirc, k, channel)
# print('Bob measures',bob_meas_results[-1]) # Bob
print("Transmission complete.")
# print('Bobs message %s'%bins_to_str(bob_meas_results)) #Bob
# return bins_to_str(bob_meas_results)
def receive_a_qmail(port, srcAddr, srcPort, batch_size=4, adversary=False):
# Initialize with Bob
classicC = SocketChannel(port+10, True)
# connect to Bob
classicC.connect(srcAddr, srcPort+10)
# receive otpkey from alice
otpkey = classicC.receive()
otpkey = pickle.loads(otpkey)
print("I am Bob I received: ", otpkey)
classicC.close()
time.sleep(1)
key_per_batch = [{'x':x,'z':z} for x,z in zip(wrap(otpkey['x'],batch_size),wrap(otpkey['z'],batch_size))]
# TODO: setup quantum channel
n_master = batch_size
n_slave = batch_size
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=srcPort)
qcirc = None
# TODO: decrypt and measure
# Eve siVmulation
recv = "Eve" if adversary else "Bob"
bob_meas_results = []
for k in key_per_batch:
circ_bob = QuantumCircuit(batch_size, batch_size)
circ_bob, offset = channel.receive(circ_bob)
# circ_bob.draw(output='mpl',filename="teleport_alice%s.png".format(k))
#Bob receives qubits, and decrypt them
if not adversary:
otp_enc_dec(circ_bob, k)
#Bob measure the states, single shot
simulator = Aer.get_backend('qasm_simulator')
nqubit = len(otpkey['x'])
# for i in range(nqubit):
circ_bob.measure(np.arange(batch_size)+offset, range(batch_size))
counts = execute(circ_bob, backend=simulator, shots = 1).result()
output = list(counts.get_counts().keys())[0]
bob_meas_results.append(output)
print('%s measures'%recv, bob_meas_results[-1])
print('%ss message %s'%(recv, bins_to_str(bob_meas_results)))
return bins_to_str(bob_meas_results)
# Grover-related methods
def apply_grover_oracle2(qcirc, dquery):
"""
grover oracle for query database:
:qcirc:QuantumCircuit, the qubits to apply
:query:str, 00 01 10 11
"""
qcirc.cz(1,0)
if dquery == '11':
qcirc.z(0)
qcirc.z(1)
elif dquery == '01':
qcirc.z(1)
elif dquery == '10':
qcirc.z(0)
else : pass
def multiparty_2grover_local(port, destPort):
"""
multiparties 2-qubit grover algorithm with separated oracle
as the database owner (Oscar). Oscar has a confiedential database,
and will help Alice to reveal her data.
:dquery:str, 00 01 10 11
"""
print("Alice creates state |00>")
qcirc = QuantumCircuit(2,2)
qcirc.h(0)
qcirc.h(1) #at this point qcirc is in the equal superposition of all quantum states
# TODO: setup quantum channel
n_master = 2
n_slave = 2
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=destPort)
print("Alice send qubits to Oscar, quering the database")
# send ... Channel stuff......
channel.send(qcirc, [0,1])
# print("Oscar receives qubits, and apply oracles")
# apply_grover_oracle2(qcirc, dquery)
# print("Oscar sends the qubits back to Alice")
# # send ... Channel stuff......
print("Alice receives qubits, apply diffusion operator, and measure")
qcirc, offset = channel.receive(qcirc)
qcirc.h(0)
qcirc.h(1)
qcirc.cz(0,1)
qcirc.h(0)
qcirc.h(1)
qcirc.measure([0,1],[0,1])
simulator = Aer.get_backend('qasm_simulator')
counts = execute(qcirc, backend=simulator, shots = 1).result()
print("Alice measurement outcome", list(counts.get_counts().keys())[0])
def oscar_sends(dquery, port, srcPort):
# Init circuit
qcirc = QuantumCircuit(2,2)
# TODO: setup quantum channel
n_master = 2
n_slave = 2
slave_offset = 0
channel = Channel(slave_offset, port, remote_port=srcPort)
print("Oscar receives qubits, and apply oracles")
qcirc, offset = channel.receive(qcirc)
apply_grover_oracle2(qcirc, dquery)
print("Oscar sends the qubits back to Alice")
# send ... Channel stuff......
channel.send(qcirc, [0,1])
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from qiskit import *
from qiskit.quantum_info import Statevector
#From Marc
from parser import QSerializer
#From Luca
import socket
from SocketChannel import SocketChannel
# In[33]:
class Channel:
def __init__(self,slave_offset=0):
self._state_vector = None
self._arr_qubits = None
self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z']
self._master = True
self._offset = 0
self._slave_offset = slave_offset
def send(self,circuit,arr_qubits):
self._state_vector = Statevector.from_instruction(circuit)
self._arr_qubits = arr_qubits
#From Marc
ser = parser.QSerializer()
ser.add_element('channel_class', self)
str_to_send = ser.encode()
#From Luca
message = str_to_send
TCP_IP = '127.0.0.1'
channel = SocketChannel()
channel.connect(TCP_IP, 5005)
channel.send(message)
#channel.close()
## TODO: TCP THINGS
return self
def receive(self,circuit)#,recieve_channel): ## TODO: remove recieve as an input
#TODO: TCP things
#recieve_channel = TCP_STUFF
#From Luca
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
#channel.close()
#From Marc
ser2 = parser.QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
# In[34]:
n_master = 2
n_slave = 1
master_offset = 0
slave_offset = n_master
circ = QuantumCircuit(n_master + n_slave)
channel = Channel(slave_offset)
## Master
circ.h(0 + channel._offset)
#circ.cx(0 + channel._offset, 1 + channel._offset)
#irc.h(1 + channel._offset)
to_tpc = channel.send(circ,[1]) ## TODO: remove
circ.draw()
# In[35]:
#Bob Part
circ_bob = QuantumCircuit(3)
bob_channel = Channel()
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
circ_bob.draw()
# In[11]:
# Initialize circ-2 in state psi (using transpile to remove reset)
#circ2 = QuantumCircuit(2)
#circ2.initialize(psi1.data, [0, 1])
#circ2 = transpile(circ2, basis_gates=basis_gates)
#circ2.draw()
# In[6]:
# Add new gates to circ2
circ_bob.h(0+offset)
#circ_bob.cx(0+offset, 1+offset)
#psi2 = Statevector.from_instruction(circ_bob)
to_tpc = bob_channel.send(circ_bob,[1])
circ_bob.draw()
# In[7]:
#Alice Part
circ_alice = QuantumCircuit(3)
alice_channel = Channel()
circ_alice , offset = alice_channel.receive(circ_alice,to_tpc)
circ_alice.draw()
# In[8]:
_
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
from channel_class import Channel
n_master = 2 # two qubits, the one on alice side
n_slave = 1 # two quantum channels and one qubit on bobs side
master_offset = 0
slave_offset = n_master
circ = QuantumCircuit(n_master + n_slave)
channel = Channel(slave_offset, 5000, remote_port = 5001)
## Master, Oracle
circ.rx(0.234,0 + channel._offset)
circ.rz(0.54,0 + channel._offset)
circ.ry(0.94,0 + channel._offset)
circ.rx(0.1,0 + channel._offset)
##Creating Entaglement
circ.h(1+channel._offset)
circ.cx(1+channel._offset,2+channel._offset)
## Master, teleportation protocol
circ.cx(0 + channel._offset, 1 + channel._offset)
circ.h(0 + channel._offset)
# this should be done with classical communication ...
#circ.cx(0 + channel._offset, 2 + channel._offset)
#circ.cx(1 + channel._offset, 3 + channel._offset)
channel.send(circ,[1]) ## TODO: remove
circ.draw(output='mpl',filename='teleport_alice.png')
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
from channel_class import Channel
n_master = 2 # two qubits, the one on alice side
n_channel = 2
n_slave = 1 # two quantum channels and one qubit on bobs side
slave_offset = n_master
channel = Channel(slave_offset, 5000, remote_port = 5001)
#create a Quantum circuit
circ = QuantumCircuit(n_master + n_channel + n_slave)
## Master, Oracle
circ.rx(0.234,0 + channel._offset)
circ.rz(0.54,0 + channel._offset)
circ.ry(0.94,0 + channel._offset)
circ.rx(0.1,0 + channel._offset)
## Creating Entaglement now on Bobs side
circ.h(1+channel._offset)
circ.cx(1+channel._offset,4+channel._offset)
## Master, teleportation protocol
circ.cx(0 + channel._offset, 1 + channel._offset)
circ.h(0 + channel._offset)
## Write the result on the communication qubits, this should be done with classical communication at some point
circ.cx(0 + channel._offset, 2 + channel._offset)
circ.cx(1 + channel._offset, 3 + channel._offset)
## Alice sends here qubits to Bob
channel.send(circ,[1]) ## TODO: remove
## The circuit how it looks on Alice side
circ.draw()
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
import matplotlib.pyplot as plt
from channel_class import Channel
#Bob Part
circ_bob = QuantumCircuit(3)
#circ_bob.h(0)
#circ_bob.draw(output='mpl','test.png')
bob_channel = Channel(myport = 5001, remote_port = 5000)
circ_bob, offset = bob_channel.receive(circ_bob)#,to_tpc)
# Add new gates to circ2
circ_bob.cx(-1+offset,0+offset)
circ_bob.cz(-2+offset,0+offset)
circ_bob.rx(-0.1,0 + offset)
circ_bob.ry(-0.94,0 + offset)
circ_bob.rz(-0.54,0 + offset)
circ_bob.rx(-0.234,0 + offset)
circ_bob.draw(output='mpl',filename='teleport_bob.png')
#check the teleported state:
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
job = execute(circ_bob,backend)
result = job.result()
outputstate = result.get_statevector(circ_bob,decimals=3)
print(outputstate)
meas = QuantumCircuit(3,1)
meas.barrier(range(3))
meas.measure([2],range(1))
qc = circ_bob + meas
#channel.send(qc)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend_sim,shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
# needed qiskit library
from qiskit import *
%matplotlib inline
# the channel library providing the class Channel handling the communication
from channel_class import Channel
#Bob needs to know the number of qubits, n_master: number of Alice qubits, n_slave: number of Bobs qubits
n_master = 2
n_channel = 2
n_slave = 1
#initialise the Quantum Channel, Bobs port is 5001, Alice port is 5000
bob_channel = Channel(myport = 5001, remote_port = 5000)
#initialise Bobs circuit
circ_bob = QuantumCircuit(n_master + n_channel + n_slave)
#Bob recieves the qubits from Alice and needs to give his computations up to then into the function
#the function returns the circuit on which Bob continues to operate and an offset he has to add all the time
circ_bob, offset = bob_channel.receive(circ_bob)
# Bob does the controlled operations on his qubit (which is 0+offset)
circ_bob.cx(1+offset,2+offset)
circ_bob.cz(0+offset,2+offset)
# Bob undoes the rotations Alice did to check, whether the states are indeed the same
circ_bob.rx(-0.1,2 + offset)
circ_bob.ry(-0.94,2 + offset)
circ_bob.rz(-0.54,2 + offset)
circ_bob.rx(-0.234,2 + offset)
# The complete Circuit
circ_bob.draw(output='mpl',filename='teleport_bob.png')
# Bob measure his qubit, if the teleportation worked, he undoes exactly what Alice did
meas = QuantumCircuit(5,1)
meas.barrier(range(5))
meas.measure([4],range(1))
qc = circ_bob + meas
# The whole teleportation protocol is simulated
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend_sim,shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
# if Bob undid all of Alice's steps correctly, the final state of his qubit is |0>
print(counts)
|
https://github.com/kerenavnery/qmail
|
kerenavnery
|
from qiskit import *
from qiskit.quantum_info import Statevector
from parser import QSerializer
from SocketChannel import SocketChannel
class Channel:
def __init__(self):
#self._is_master = is_master
self._master_qargs_list = None
self._master_cargs_list = None
self._slave_qargs_list = None
self._slave_cargs_list = None
self._circuit = None
def receive(self,circuit):
print('Wait to receive')
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
channel.close()
#From Marc
ser2 = parser.QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
def append(self, is_master instruction, qargs=None, cargs=None):
if is_master:
for restricted_qarg in self._slave_qargs_list:
if restricted_qarg is in qargs:
print("Master is trying to access Slave's qarg: %d".format(restricted_qarg))
return -1
for restricted_carg in self._slave_cargs_list:
if restricted_carg is in cargs:
print("Master is trying to access Slave's carg: %d".format(restricted_carg))
return -1
else: ## is_slave
for restricted_qarg in self._master_qargs_list:
if restricted_qarg is in qargs:
print("Slave is trying to access Master's qarg: %d".format(restricted_qarg))
return -1
for restricted_carg in self._master_cargs_list:
if restricted_carg is in cargs:
print("Slave is trying to access Master's carg: %d".format(restricted_carg))
return -1
## Allowed access
return self._circuit.append(instruction, qargs, cargs)
def
# self._state_vector = None
# self._arr_qubits = None
# self._basis_gates = ['u1', 'u2', 'u3', 'cx','x','y','H','z']
# self._master = True
# self._offset = 0
# self._slave_offset = slave_offset
def send(self,circuit,arr_qubits):
self._state_vector = Statevector.from_instruction(circuit)
self._arr_qubits = arr_qubits
#From Marc
ser = QSerializer()
ser.add_element('channel_class', self)
str_to_send = ser.encode()
#print(str_to_send.type())
#From Luca
message = str_to_send
TCP_IP = '127.0.0.1'
channel = SocketChannel()
channel.connect(TCP_IP, 5005)
channel.send(message)
channel.close()
## TODO: TCP THINGS
return self
def receive(self,circuit):#,recieve_channel): ## TODO: remove recieve as an input
#TODO: TCP things
#recieve_channel = TCP_STUFF
#From Luca
print('Wait to receive')
channel = SocketChannel(port=5005, listen=True)
data = channel.receive()
print("received data:", data)
channel.close()
#From Marc
ser2 = QSerializer()
ser2.decode(data)
recieve_channel = ser2.get_element('channel_class')
self._slave_offset = recieve_channel._slave_offset
if(recieve_channel._master):
self._master = False
self._offset = self._slave_offset
new_circuit = QuantumCircuit(len(recieve_channel._state_vector.dims()))
new_circuit.initialize(recieve_channel._state_vector.data, range(len(recieve_channel._state_vector.dims())))
new_circuit = transpile(new_circuit, basis_gates=self._basis_gates)
return new_circuit, self._offset
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
|
Innanov
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/PabloAMC/Qiskit_meetup_2021
|
PabloAMC
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
#from iqx import *
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.chemistry.core import Hamiltonian
from qiskit.circuit.library import PhaseEstimation
from qiskit import QuantumCircuit, execute, Aer
from qiskit.circuit import QuantumRegister, Qubit, Gate, ClassicalRegister
from qiskit.quantum_info import Statevector
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule, PSI4Driver
molecule = Molecule(geometry=[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1)
driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
qmol = driver.run()
print(qmol.one_body_integrals)
print(qmol.two_body_integrals)
from qiskit.chemistry.transformations import (FermionicTransformation,
FermionicTransformationType,
FermionicQubitMappingType)
fermionic_transformation = FermionicTransformation(
transformation=FermionicTransformationType.FULL,
qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
two_qubit_reduction=False,
freeze_core=False)
qubit_op, _ = fermionic_transformation.transform(driver)
print('Qubit operator is', qubit_op)
num_orbitals = fermionic_transformation.molecule_info['num_orbitals']
num_particles = fermionic_transformation.molecule_info['num_particles']
qubit_mapping = fermionic_transformation.qubit_mapping
two_qubit_reduction = fermionic_transformation.molecule_info['two_qubit_reduction']
z2_symmetries = fermionic_transformation.molecule_info['z2_symmetries']
initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
two_qubit_reduction, z2_symmetries.sq_list)
initial_circ = initial_state.construct_circuit()
print(initial_state.bitstr)
initial_circ.draw()
qubit_op, _ = fermionic_transformation.transform(driver)
print(qubit_op)
num_evaluation_qubits = 5
normalization_factor = 1/2 # Since the min energy will be -1.8... we need to normalize it so that it is smaller than 1
unitary = (normalization_factor*qubit_op).exp_i().to_circuit()
phase_estimation = PhaseEstimation(num_evaluation_qubits = num_evaluation_qubits, unitary = unitary)
type(qubit_op.exp_i().to_circuit())
print(phase_estimation.qubits)
dir(phase_estimation)
phase_estimation.draw()
circ = initial_circ.combine(phase_estimation)
classical_eval = ClassicalRegister(num_evaluation_qubits, name = 'class_eval')
circ = circ + QuantumCircuit(classical_eval)
#circ.measure_all()
print(circ.qregs)
circ.measure(circ.qregs[1], classical_eval)
circ.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.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(circ, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
maxkey = '0'*num_evaluation_qubits
maxvalue = 0
for key, value in counts.items():
if value > maxvalue:
maxvalue = value
maxkey = key
energy = 0
for i,s in zip(range(num_evaluation_qubits), maxkey[::-1]):
energy -= (int(s)/2**(i))/normalization_factor
print('The energy is', energy, 'Hartrees')
36/32
26/16
|
https://github.com/PabloAMC/Qiskit_meetup_2021
|
PabloAMC
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
#from iqx import *
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.chemistry.core import Hamiltonian
from qiskit.circuit.library import PhaseEstimation
from qiskit import QuantumCircuit, execute, Aer
from qiskit.circuit import QuantumRegister, Qubit, Gate, ClassicalRegister
from qiskit.quantum_info import Statevector
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule, PSI4Driver
molecule = Molecule(geometry=[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1)
driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
qmol = driver.run()
print(qmol.one_body_integrals)
print(qmol.two_body_integrals)
from qiskit.chemistry.transformations import (FermionicTransformation,
FermionicTransformationType,
FermionicQubitMappingType)
fermionic_transformation = FermionicTransformation(
transformation=FermionicTransformationType.FULL,
qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
two_qubit_reduction=False,
freeze_core=False)
qubit_op, _ = fermionic_transformation.transform(driver)
print('Qubit operator is', qubit_op)
# Complete here! Perhaps you will find some information in the VQE tutorial
num_orbitals = # To complete
num_particles = # To complete
qubit_mapping = # To complete
two_qubit_reduction = # To complete
z2_symmetries = # To complete
# Use the previous variables to create a Hartree Fock state
initial_state = # To complete
initial_circ = initial_state.construct_circuit()
print(initial_state.bitstr)
initial_circ.draw()
qubit_op, _ = fermionic_transformation.transform(driver)
print(qubit_op)
num_evaluation_qubits = 5
normalization_factor = 1/2 # Since the min energy will be approx -1.8 we need to normalize it so that it is smaller in absolute value than 1
### Complete here! Perhaps look for how to exponentiate an operator and create a circuit
unitary = (normalization_factor*#something).#something
### Look for Phase Estimation in the Qiskit documentation!
phase_estimation = #something
print(phase_estimation.qubits)
dir(phase_estimation)
phase_estimation.draw()
circ = initial_circ.combine(phase_estimation)
classical_eval = ClassicalRegister(num_evaluation_qubits, name = 'class_eval')
circ = circ + QuantumCircuit(classical_eval)
print(circ.qregs)
circ.measure(circ.qregs[1], classical_eval)
circ.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.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(circ, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
maxkey = '0'*num_evaluation_qubits
maxvalue = 0
for key, value in counts.items():
if value > maxvalue:
maxvalue = value
maxkey = key
energy = 0
for i,s in zip(range(num_evaluation_qubits), maxkey[::-1]):
energy -= (int(s)/2**(i))/normalization_factor
print('The energy is', energy, 'Hartrees')
|
https://github.com/krishphys/LiH_Variational_quantum_eigensolver
|
krishphys
|
from qiskit import BasicAer, Aer, IBMQ
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError
from qiskit.providers.aer.noise.errors import pauli_error
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit.providers.aer.noise.errors import thermal_relaxation_error
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer import noise
provider = IBMQ.load_account()
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Classically solve for the lowest eigenvalue
# This is used just to compare how well you VQE approximation is performing
def exact_solver(qubitOp,shift):
ee = ExactEigensolver(qubitOp)
result = ee.run()
ref = result['energy']+shift
print('Reference value: {}'.format(ref))
return ref
# Define your function for computing the qubit operations of LiH
def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'):
# Specify details of our molecule
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis)
# Compute relevant 1 and 2 body integrals.
molecule = driver.run()
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
# Please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
# Prepare full idx of freeze_list and remove_list
# Convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
#Overall energy shift:
shift = energy_shift + nuclear_repulsion_energy
return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
def get_ground_State(map_type,inter_dist,init_state,ansatz,optimizer_select):
qubitOp, num_spin_orbitals, num_particles, \
qubit_reduction,shift = compute_LiH_qubitOp(map_type,inter_dist=inter_dist)
#Initial State
if init_state == "Zero":
initState = Zero(qubitOp.num_qubits)
elif init_state == "HartreeFock":
initState = HartreeFock(
num_spin_orbitals,
num_particles,
qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction
)
#Ansatz
depth = 10
if ansatz == "RY":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['ry'],reps = 1,\
initial_state=initState)
elif ansatz == "RYRZ":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['ry','rz'],reps = 1,\
initial_state=initState)
elif ansatz == "SwapRZ":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['swap','rz'],reps = 1,\
initial_state=initState)
elif ansatz == "UCCSD":
var_form = UCCSD(
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initState,
qubit_mapping=map_type
)
#Optimizer
if optimizer_select == "COBYLA":
optimizer = COBYLA(maxiter = 1000)
elif optimizer_select == "SPSA":
optimizer = SPSA(max_trials = 1000)
#Noise model
backend_ = "qasm_simulator"
shots = 1000
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend(backend_)
device = provider.get_backend("ibmq_vigo")
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device.properties())
quantum_instance = QuantumInstance(backend=backend,
shots=shots,
noise_model=noise_model,
coupling_map=coupling_map,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30)
#Running VQE
vqe = VQE(qubitOp, var_form, optimizer, callback = store_intermediate_result)
vqe_result = np.real(vqe.run(quantum_instance)['eigenvalue'] + shift)
callbackDict = {"counts":counts,"values":values,"params":params,"deviation":deviation}
return vqe_result,callbackDict,qubitOp,shift
map_type = "parity"
inter_dist = 1.6
initialStateList = ["Zero","HartreeFock"]
ansatzList = ["UCCSD","RY","RYRZ","SwapRZ"]
optimizerList = ["COBYLA","SPSA"]
import itertools
choices = list(itertools.product(initialStateList,ansatzList,optimizerList))
choices[8:]
selected_choices = choices[8:]
len(selected_choices)
selected_choices[0]
map_type = "parity"
inter_dist = 1.6
for i in selected_choices:
counts = []
values =[]
params =[]
deviation = []
init_state = i[0]
ansatz = i[1]
optimizer_select = i[2]
chosen = str({"Optimizer ":optimizer_select,"Ansatz ":ansatz,"Initial State ":init_state})
vqe_result,callbackDict,qubitOp,shift = get_ground_State(map_type,inter_dist,init_state,ansatz,optimizer_select)
ref = exact_solver(qubitOp , shift)
energy_error = np.abs(np.real(ref) - vqe_result)
print("Energy Error :",energy_error)
# Calculating energy error
vqe_energies = np.real(callbackDict["values"]) + shift
energy_errors = np.abs(np.real(ref) - vqe_energies)
plt.plot(callbackDict["counts"] , energy_errors)
plt.xlabel('Counts')
plt.ylabel('Energy Error/ Hartree')
plt.title("Choices : "+chosen)
plt.show()
print("--------------------------------")
|
https://github.com/krishphys/LiH_Variational_quantum_eigensolver
|
krishphys
|
from qiskit import BasicAer, Aer, IBMQ
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, NumPyEigensolver
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError
from qiskit.providers.aer.noise.errors import pauli_error
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit.providers.aer.noise.errors import thermal_relaxation_error
from qiskit.providers.aer import noise
provider = IBMQ.load_account()
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Classically solve for the lowest eigenvalue
# This is used just to compare how well you VQE approximation is performing
def exact_solver(qubitOp, shift):
ee = NumPyEigensolver(qubitOp)
result = ee.run()
ref = result['eigenvalues']
ref+= shift
print('Reference value: {}'.format(ref))
return ref
# Define your function for computing the qubit operations of LiH
def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'):
# Specify details of our molecule
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis)
# Compute relevant 1 and 2 body integrals.
molecule = driver.run()
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
#print("# of electrons: {}".format(num_particles))
#print("# of spin orbitals: {}".format(num_spin_orbitals))
# Please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
# Prepare full idx of freeze_list and remove_list
# Convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
#Overall energy shift:
shift = energy_shift + nuclear_repulsion_energy
return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift
map_type = 'parity'
inter_dist = 1.6
qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , inter_dist)
# Classically solve for the exact solution and use that as your reference value
ref = exact_solver(qubitOp , shift)
# Specify your initial state
init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type)
# Select a state preparation ansatz
# Equivalently, choose a parameterization for our trial wave function.
var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type)
# Choose where to run/simulate our circuit
quantum_instance = Aer.get_backend('statevector_simulator')
# Choose the classical optimizer
optimizer = SPSA(max_trials = 1000)
# Run your VQE instance
vqe = VQE(qubitOp, var_form, optimizer)
vqe_results = vqe.run(quantum_instance)
# Calculating ground ststae energy from vqe results:
ground_state_energy = vqe_results['eigenvalue'] + shift
print(ground_state_energy)
distances = np.arange(0.2 , 5 , 0.1)
energies = []
for interdist in distances:
qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist)
# Classically solve for the exact solution and use that as your reference value
ref = exact_solver(qubitOp , shift)
# Specify your initial state
init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type)
# Select a state preparation ansatz
# Equivalently, choose a parameterization for our trial wave function.
var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type)
# Choose where to run/simulate our circuit
quantum_instance = Aer.get_backend('statevector_simulator')
# Choose the classical optimizer
optimizer = SPSA(max_trials = 1000)
# Run your VQE instance
vqe = VQE(qubitOp, var_form, optimizer)
vqe_results = vqe.run(quantum_instance)
# Calculating ground state energy from vqe results:
ground_state_energy = vqe_results['eigenvalue'] + shift
energies.append(ground_state_energy)
plt.plot(distances , energies)
plt.title('Bond energy v. interatomic distance')
plt.xlabel('Interatomic distance/ Angstroms')
plt.ylabel('Energy / Hartrees')
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
map_type = 'parity'
inter_dist = 1.6
# Dictionary of optimizers:
opt_dict = {'SPSA' , 'SLSQP' , 'COBYLA' , 'L_BFGS_B'}
for opt in opt_dict:
print('Testing', str(opt) , 'optimizer')
qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist)
# Classically solve for the exact solution and use that as your reference value
ref = exact_solver(qubitOp , shift)
# Specify your initial state
init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type)
# Select a state preparation ansatz
# Equivalently, choose a parameterization for our trial wave function.
var_form = UCCSD(num_orbitals=num_spin_orbitals, num_particles=num_particles, qubit_mapping=map_type)
# Choose where to run/simulate our circuit
quantum_instance = Aer.get_backend('statevector_simulator')
# Choose the classical optimizer
if opt == 'SPSA':
optimizer = SPSA(max_trials = 500)
elif opt == 'SLSQP':
optimizer = SLSQP(maxiter = 1000)
elif opt == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun = 1000 , maxiter = 1000)
elif opt == 'COBYLA':
optimizer = COBYLA(maxiter = 1000)
counts =[]
values =[]
params =[]
deviation =[]
# Run your VQE instance
vqe = VQE(qubitOp, var_form, optimizer , callback = store_intermediate_result)
vqe_results = vqe.run(quantum_instance)
#Printing error in final value:
ground_state_energy = vqe_results['eigenvalue'] + shift
energy_error_ground = np.abs(np.real(ref) - ground_state_energy)
print('Error:', str(energy_error_ground))
# Calculating energy error
vqe_energies = np.real(values) + shift
energy_error = np.abs(np.real(ref) - vqe_energies)
plt.plot(counts , energy_error , label=str(opt))
plt.legend()
plt.xlabel('Counts')
plt.ylabel('Energy Error/ Hartree')
plt.title('Energy Convergence of VQE: UCCSD Ansatz')
map_type = 'parity'
inter_dist = 1.6
# Dictionary of optimizers:
opt_dict = {'SPSA' , 'SLSQP' , 'COBYLA' , 'L_BFGS_B'}
for opt in opt_dict:
print('Testing', str(opt) , 'optimizer')
qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift = compute_LiH_qubitOp(map_type , interdist)
# Classically solve for the exact solution and use that as your reference value
ref = exact_solver(qubitOp , shift)
# Specify your initial state
init_state = HartreeFock(num_spin_orbitals,num_particles, qubit_mapping=map_type)
# Select a state preparation ansatz
# Equivalently, choose a parameterization for our trial wave function.
var_form = EfficientSU2(qubitOp.num_qubits , entanglement='full')
# Choose where to run/simulate our circuit
quantum_instance = Aer.get_backend('statevector_simulator')
# Choose the classical optimizer
if opt == 'SPSA':
optimizer = SPSA(max_trials = 1000)
elif opt == 'SLSQP':
optimizer = SLSQP(maxiter = 1000)
elif opt == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun = 1000 , maxiter = 1000)
elif opt == 'COBYLA':
optimizer = COBYLA(maxiter = 1000)
counts =[]
values =[]
params =[]
deviation =[]
# Run your VQE instance
vqe = VQE(qubitOp, var_form, optimizer , callback = store_intermediate_result)
vqe_results = vqe.run(quantum_instance)
#Printing error in final value:
ground_state_energy = vqe_results['eigenvalue'] + shift
energy_error_ground = np.abs(np.real(ref) - ground_state_energy)
print('Error:', str(energy_error_ground))
# Calculating energy error
vqe_energies = np.real(values) + shift
energy_error = np.abs(np.real(ref) - vqe_energies)
plt.plot(counts , energy_error , label=str(opt))
plt.legend()
plt.xlabel('Counts')
plt.ylabel('Energy Error/ Hartree')
plt.title('Energy Convergence of VQE: RyRz Ansatz')
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
qc.x(0)
qc.y(0)
qc.draw('mpl')
from qiskit.visualization import visualize_transition
visualize_transition(qc)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Creat a Quantum Circuit with Single Qubit
# With default Initial State as [1,0] or |0>
qc=QuantumCircuit(1)
#Declare the Initial State as [0,1] or |1>
initial_state=[0,1]
qc.initialize(initial_state,0)
# Apply the Pauli x-Gate on the qubit
qc.x(0)
# Draw the Circuit
# qc.draw()
qc.draw()
#Get the backend for the circuit(simulator or realtime system)
backend=Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out=execute(qc,backend).result().get_statevector()
#plot the result as a Bloch Sphere visualization
plot_bloch_multivector(out)
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
qc.x(0)
qc.draw('mpl')
#Visualize the output as an animation
from qiskit.visualization import visualize_transition
visualize_transition(qc)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import numpy as np
a = np.array([1, 0])
b = np.array([0, 1])
print("Vectors :")
print("a = ", a)
print("\nb = ", b)
print("\nCross product of vectors a and b =")
print(np.cross(a, b))
print("------------------------------------")
x = np.array([[2, 6, 9], [2, 7, 3]])
y = np.array([[7, 5, 6], [3, 12, 3]])
print("\nMatrices :")
print("x =", x)
print("\ny =", y)
print("\nCross product of matrices x and y =")
print(np.cross(x, y))
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import numpy as np
a = np.array([2, 6])
b = np.array([3, 10])
print("Vectors :")
print("a = ", a)
print("\nb = ", b)
print("\nInner product of vectors a and b =")
print(np.inner(a, b))
print("---------------------------------------")
x = np.array([[2, 3, 4], [3, 2, 9]])
y = np.array([[1, 5, 0], [5, 10, 3]])
print("\nMatrices :")
print("x =", x)
print("\ny =", y)
print("\nInner product of matrices x and y =")
print(np.inner(x, y))
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import numpy as np
a = np.array([2, 6])
b = np.array([3, 10])
print("Vectors :")
print("a = ", a)
print("\nb = ", b)
print("\nOuter product of vectors a and b =")
print(np.outer(a, b))
print("------------------------------------")
x = np.array([[3, 6, 4], [9, 4, 6]])
y = np.array([[1, 15, 7], [3, 10, 8]])
print("\nMatrices :")
print("x =", x)
print("\ny =", y)
print("\nOuter product of matrices x and y =")
print(np.outer(x, y))
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from sympy import Matrix
from sympy.physics.quantum import TensorProduct
ket0 = Matrix([1,0])
ket0 = Matrix([1,0])
TensorProduct(ket0, ket0)
ket0 = Matrix([1,0])
ket1 = Matrix([0,1])
TensorProduct(ket0, ket1)
ket1 = Matrix([0,1])
ket0 = Matrix([1,0])
TensorProduct(ket1, ket0)
ket1 = Matrix([0,1])
ket0 = Matrix([1,0])
TensorProduct(ket1, ket1)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control and target qubits
qc.x(0)
qc.h(0)
qc.h(1)
#Applying the CNOT gate
#qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control qubit
qc.h(0)
# apply pauli x gate to the target qubit
qc.x(1)
# Apply h gate to the target qubit
qc.h(1)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src
conda install git
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the CNOT gate
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply X gate to change the input or target
qc.x(0)
qc.x(1)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control qubit
qc.h(0)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control qubit
qc.x(1)
qc.h(0)
#Applying the CNOT gate
qc.cx(0,1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
# Apply h gate to the control and target qubits
qc.h(0)
qc.h(1)
#Applying the CNOT gate
qc.cx(0,1)
# Once again apply h gate to the control and target qubits
qc.h(0)
qc.h(1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the CNOT gate
qc.cx(1,0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
qc = QuantumCircuit(3)
qc.x(0)
qc.x(1)
qc.cswap(0,1,2)
qc.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
out = execute(qc,backend).result().get_unitary()
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
array_to_latex(out, pretext = "\\text{Statevector} = ")
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
a = 0
b = 1
#Applying the x gate to change a to |1>, b will be |0> itself
qc.x(a)
#apply the swap gate to both qubits
qc.swap(0,1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
qc = QuantumCircuit(3)
c1 = 0
c2 = 1
t=2
qc.x(c1)
qc.x(c2)
qc.x(t)
qc.ccx(c1,c2,t)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(3)
c1 = 0
c2 = 1
t=2
#Applying the x gate to change a to |1>, b will be |0> itself
qc.x(c1)
qc.x(c2)
qc.x(t)
qc.ch(c1,t)
qc.cz(c2,t)
qc.ch(c1,t)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B1 = QuantumCircuit(2)
# Apply h gate to the control qubit
B1.h(0)
#Applying the CNOT gate
B1.cx(0,1)
#Draw the circuit
# qc.draw()
B1.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B1,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B1,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(B1,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B2 = QuantumCircuit(2)
B2.x(0)
B2.h(0)
B2.x(1)
B2.cx(0,1)
B2.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B2,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B2,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(B2,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B3 = QuantumCircuit(2)
B3.h(0)
B3.x(1)
B3.cx(0,1)
B3.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B3,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B3,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(B3,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B4 = QuantumCircuit(2)
B4.x(0)
B4.h(0)
B4.cx(0,1)
B4.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B4,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B4,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(B4,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
BS1 = QuantumCircuit(2)
#Applying the CNOT gate
BS1.h(0)
BS1.cx(0,1)
#Draw the circuit
# qc.draw()
BS1.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(BS1,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(BS1,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(BS1,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
BS2 = QuantumCircuit(2)
BS2.x(0)
BS2.h(0)
BS2.cx(0,1)
#Draw the circuit
# qc.draw()
BS2.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(BS2,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(BS2,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(BS2,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
BS3=QuantumCircuit(2)
BS3.h(0)
BS3.x(1)
BS3.cx(0,1)
BS3.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(BS3,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
out = execute(BS3,backend).result().get_statevector()
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(BS3,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
BS4=QuantumCircuit(2)
BS4.h(0)
BS4.z(0)
BS4.x(1)
BS4.z(1)
BS4.cx(0,1)
BS4.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(BS4,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(BS4,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(BS4,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute
from qiskit.visualization import plot_histogram
# Create a quantum circuit with two qubits
bell_circuit = QuantumCircuit(2, 2)
# Apply a Hadamard gate to the first qubit
bell_circuit.h(0)
# Apply a CNOT gate with the first qubit as the control and the second qubit as the target
bell_circuit.cx(0, 1)
# The resulting state is a Bell state
bell_circuit.measure([0, 1], [0, 1])
# Simulate the circuit using the Aer simulator
simulator = Aer.get_backend('qasm_simulator')
# Transpile the circuit for the simulator
transpiled_bell_circuit = transpile(bell_circuit, simulator)
# Run the simulation
result = execute(transpiled_bell_circuit, simulator).result()
# Display the measurement results
counts = result.get_counts(bell_circuit)
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
# creating a constant oracle, input has no effect on the ouput
# Create a quantum circuit with 2 qubits. One as input and other as output
constant_oracle = QuantumCircuit(2)
# get a random number from 0 or 1
output = np.random.randint(2)
# what ever get in input, its having no effect.
# the output will be the random value 0 or 1
if output == 1:
constant_oracle.x(1)
# draw the circuit
constant_oracle.draw('mpl')
# creating a balanced oracle,
# perform CNOTs with first qubit input as a control and the second qubit output as the target.
balanced_oracle = QuantumCircuit(2)
# Place X-gate for input qubit
balanced_oracle.x(0)
# Use barrier as divider
balanced_oracle.barrier()
# Place Controlled-NOT gates
balanced_oracle.cx(0, 1)
# using barrier as a divider and avoid cancelling gates by the transpiler
balanced_oracle.barrier()
# Place X-gates
balanced_oracle.x(0)
# Show oracle
balanced_oracle.draw('mpl')
#initialise the input qubits in the state |+⟩
# and the output qubit in the state |−⟩
dj_circuit = QuantumCircuit(2, 1)
# Apply H-gates
dj_circuit.h(0)
# Put qubit in state |->
dj_circuit.x(1)
dj_circuit.h(1)
dj_circuit.draw('mpl')
# define the oracle function to use
#oracle_fn = constant_oracle
oracle_fn = balanced_oracle
# Add oracle function
dj_circuit &= oracle_fn
dj_circuit.draw('mpl')
# perform H-gates on qubit and measure input register
dj_circuit.h(0)
dj_circuit.barrier()
# Measure
dj_circuit.measure(0, 0)
# Display circuit
dj_circuit.draw('mpl')
# check the output
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import qiskit as q
%matplotlib inline
from qiskit.visualization import plot_histogram
from qiskit.tools.visualization import plot_bloch_multivector
#secretnum = '10100'
# convert decimal num to binary
a = int(input("Enter Secret Number:"))
secretnum = "{0:b}".format(a)
circuit = q.QuantumCircuit(len(secretnum)+1, len(secretnum))
# circuit.h([0,1,2,3,4,5])
circuit.h(range(len(secretnum)))
# circuit.x(6)
# circuit.h(6)
circuit.x(len(secretnum))
circuit.h(len(secretnum))
circuit.barrier()
for i, j in enumerate(reversed(secretnum)):
if j == '1':
circuit.cx(i, len(secretnum))
# circuit.cx(5, 6)
# circuit.cx(3, 6)
# circuit.cx(0, 6)
circuit.barrier()
# circuit.h([0,1,2,3,4,5])
circuit.h(range(len(secretnum)))
circuit.barrier()
# circuit.measure([0,1,2,3,4,5],[0,1,2,3,4,5])
circuit.measure(range(len(secretnum)),range(len(secretnum)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = q.Aer.get_backend('qasm_simulator')
result = q.execute(circuit, backend=simulator, shots=1).result()
counts = result.get_counts()
print(counts)
counts = str(counts)
counts = (counts[2:len(secretnum)+2])
print(counts)
# convert binary num to decimal
num = int(counts, 2)
print("Your Secret Number is :", num)
# convert decimal num to binary
a = "{0:b}".format(50)
print(a)
# convert binary num to decimal
# Convert a to base 2
s = int(a, 2)
print(s)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
b = '110'
n = len(b)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit = simon_circuit.compose(simon_oracle(b))
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw("mpl")
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(simon_circuit).result()
counts = results.get_counts()
print(f"Measured output: {counts}")
plot_histogram(counts)
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
# Function to create Simon's oracle for a given hidden string 's'
def simon_oracle(s):
n = len(s)
oracle_circuit = QuantumCircuit(n*2, n)
# Apply CNOT gates according to the hidden string 's'
for qubit in range(n):
if s[qubit] == '1':
oracle_circuit.cx(qubit, n + qubit)
return oracle_circuit
# Hidden string 'b'
b = '1101'
# Number of qubits
n = len(b)
# Create a quantum circuit
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates to the first n qubits
simon_circuit.h(range(n))
# Apply a barrier for visual separation
simon_circuit.barrier()
# Compose the circuit with the Simon oracle for the given hidden string 'b'
simon_circuit = simon_circuit.compose(simon_oracle(b))
# Apply a barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the first n qubits
simon_circuit.h(range(n))
# Measure the qubits
simon_circuit.measure(range(n), range(n))
# Visualize the circuit
simon_circuit.draw("mpl")
# Transpile the circuit for the simulator
simon_circuit = transpile(simon_circuit, Aer.get_backend('qasm_simulator'))
# Run the simulation
simulator = Aer.get_backend('qasm_simulator')
result = simulator.run(simon_circuit).result()
# Display the measured output
counts = result.get_counts(simon_circuit)
print(f"Measured output: {counts}")
# Plot the results
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import qiskit as q
%matplotlib inline
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
Msg = "QuantumComputing"
secretnum = ''.join(format(ord(i), 'b') for i in Msg)
# printing result
print("The string after binary conversion : " + str(secretnum))
print("Your Quantum Algorithm is Running!")
circuit = q.QuantumCircuit(len(secretnum)+1, len(secretnum))
circuit.h(range(len(secretnum)))
circuit.x(len(secretnum))
circuit.h(len(secretnum))
circuit.barrier()
for i, j in enumerate(reversed(secretnum)):
if j == '1':
circuit.cx(i, len(secretnum))
circuit.barrier()
circuit.h(range(len(secretnum)))
circuit.barrier()
circuit.measure(range(len(secretnum)),range(len(secretnum)))
circuit.barrier()
simulator = q.Aer.get_backend('qasm_simulator')
result = q.execute(circuit, backend=simulator, shots=1).result()
counts = result.get_counts()
counts = str(counts)
counts = (counts[2:len(secretnum)+2])
print("the binary of ur String is", counts)
def BinaryToDecimal(binary):
string = int(binary, 2)
return string
bin_data = str(counts)
str_data =' '
for i in range(0, len(bin_data), 7):
temp_data = bin_data[i:i + 7]
decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)
# printing the result
print("The Binary value after string conversion is:", str_data)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import sys
print(sys.executable)
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('fb335ef56b1d6d43894ad997ae54daf329de8050cda1e2e7a795f9bcae2da2e84ad903bd320d6e1354214371bcf9af7a80c1ccc1e0a546947469913805528928')
IBMQ.load_account()
import qiskit as q
%matplotlib inline
circuit=q.QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
circuit.draw()
circuit.draw(output="mpl")
from qiskit import IBMQ
provider=IBMQ.get_provider("ibm-q")
for backend in provider.backends():
try:
qubit_count=len(backend.properties().qubits)
except:
qubit_count="simulated"
print(f"{backend.name()}has{backend.status().pending_jobs}queued and␣{qubit_count}qubits")
from qiskit.tools.monitor import job_monitor
backend=provider.get_backend("ibmq_lima")
job=q.execute(circuit,backend=backend,shots=1024)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use("dark_background")
result=job.result()
count=result.get_counts(circuit)
plot_histogram([count])
backend=provider.get_backend("ibmq_qasm_simulator")
circuit=q.QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
circuit.draw()
job=q.execute(circuit,backend=backend,shots=1024)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use("dark_background")
result=job.result()
count=result.get_counts(circuit)
plot_histogram([count])
from qiskit import Aer
sim_backend=Aer.get_backend("qasm_simulator")
for backend in Aer.backends():
print(backend)
job=q.execute(circuit,backend=sim_backend,shots=1024)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use("dark_background")
result=job.result()
count=result.get_counts(circuit)
plot_histogram([count])
from qiskit import *
circuit=QuantumCircuit(3,3)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit.tools.visualization import plot_state_qsphere
# QFT
# Initialize the 3-qubit quantum circuit
# Set the state '110'
s = '110'
num_qubits = len(s)
qc = QuantumCircuit(num_qubits)
# Set reverse ordering
s = s[::-1]
# Construct the state 110
for idx in range(num_qubits):
if s[idx] == '1':
qc.x(idx)
qc.barrier()
qc.draw()
circuit.draw(output='mpl')
# Import the value pi for our rotations
from numpy import pi
# Always start from the most significant qubit,
# in this case it's q2.
# Step 1, add a Hadamard gate
qc.h(2)
# Step 2, add CROT gates from most significant qubit
qc.cu1(pi/2,1,2)
# Step 3, add another CROT from 2 to the next qubit down,
# while doubling the phase denominator
qc.cu1(pi/4, 0, 2)
# Draw the circuit
qc.draw()
# Now that we finished from 2 down to 0
# We'll drop to the next least significant qubit and
# start again,
# Step 1, add a Hadamard gate
qc.h(1)
# Step 2, add Control Rotation (CROT) gates from most
# significant towards
# least significant starting a pi/2, and doubling the
# denominator
# as you go down each qubit.
qc.cu1(pi/2, 0, 1)
# Draw the circuit
qc.draw()
# Now that we finished from 1 down to 0
# We'll drop to the next least significant qubit and
# Start again
# Step 1, add a Hadamard gate
qc.h(0)
# Since we are at the least significant qubit, we are
# done!
# Draw the circuit
qc.draw()
# Define a function which will add the swap gates to the
# outer
# pair of qubits
def add_swap_gates(qc_swaps,qubits):
for qubit in range(qubits//2):
qc-swaps.swap(qubit, qubit-qubit-1)
return qc_swaps
qft_circuit=add_swap_gates(qc, num, qubits)
qft_circuit.draw()
# Get the state vector simulator to view our final QFT
# state
backend = Aer.get_backend("statevector_simulator")
# Execute the QFT circuit and visualize the results
statevector = execute(qft_circuit,backend=backend).result().get_statevector()
plot_bloch_multivector(statevector)
plot_state_qsphere(statevector)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
import qiskit as q
import math # for Pi and other math functions
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qasm_sim= q.Aer.get_backend("qasm_simulator") #Choose to run the code on a simulator or a real quantum computer
statevec_sim = q.Aer.get_backend("statevector_simulator")
print("done setup")
# This circuit to practice Qiskit (gives hints to HW5)
c = q.QuantumCircuit(4,3) # create a circuit with 4 qubits and 3 cbits. The cbits are needed to store the measerued qubits values.
c.rx(math.pi/2, 0) # Rotate qbit-0 90 degrees on X
c.ry(math.pi/4, 1) # Rorate qbit-1 45 degrees on Y
c.h(2) # apply H gate on qbit-2
c.cnot(0,3) # apply CNot gate on qubits (0 and 1)
c.cnot(1,3) # apply CNot gate on qubits (1 and 3)
c.cnot(2,3) # apply CNot gate on qubits (2 and 3)
c.rz(math.pi/4, 2) # Rotate qbit-2 45 degrees on Z
c.h(2) # Apply H gate again on qbit-2
c.measure([0,1,2], [0,1,2]) # measure qubits [0,1,2] and store the results in cbit [0,1,2]
psi0 = q.execute(c,backend=statevec_sim).result().get_statevector()
print("Done.. Draw circuit:")
c.draw()
plot_bloch_multivector(psi0)
count1 = q.execute(c,backend=qasm_sim, shots=1024).result().get_counts()
plot_histogram([count1], legend=['counts'] )
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
#Comando para que las graficas se vean en el notebook
%matplotlib inline
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.draw()
circuit.draw(output='mpl')
qr = QuantumRegister(2, 'quantum')
cr = ClassicalRegister(2, 'classical')
circuit.draw()
circuit.draw(output='mpl')
circuit.h(qr[0])
circuit.draw(output='mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=backend).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
'''
El IMB_TOKEN se puede obtener en: https://quantum-computing.ibm.com/account
'''
#IBMQ.save_account('IMB_TOKEN', overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
provider.backends()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmqx2')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
from math import sqrt
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
# declare the intial sate as [0,1] or |1>
initial_state = [1/sqrt(2),1j/sqrt(2)]
qc.initialize(initial_state,0)
qc.x(0)
qc.measure_all()
#Draw the circuit
# qc.draw()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
plot_bloch_multivector(out)
# visualize the output as an animation
# visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
counts = out.get_counts()
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the hadarmad gate to target
qc.sdg(1)
#apply the cx gate to both qubits
qc.cx(0,1)
#Applying the hadarmad gate to target
qc.s(1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
counts = out.get_counts()
plot_histogram(counts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.