repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTrainingData.csv"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTestData.csv"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
n = 2 # dimension of each data point
sample_Total, training_input, test_input, class_labels = Currency(
training_size=80,
test_size=20, n=n, PLOT_DATA=True
)
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)
aqua_dict = {
'problem': {'name': 'classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM'
},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]},
'multiclass_extension': {'name': 'AllPairs'},
'backend': {'shots': 1024}
}
backend = BasicAer.get_backend('qasm_simulator')
algo_input = ClassificationInput(training_input, test_input, total_array)
result = run_algorithm(aqua_dict, algo_input, backend=backend)
for k,v in result.items():
print("'{}' : {}".format(k, v))
|
https://github.com/IceKhan13/QiskitFlow
|
IceKhan13
|
import math
import datetime
import qiskitflow
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def my_quantum_program(experiment_name: str = "Awesome experiment",
seed: int = 42):
"""
Awesome docs here
"""
qf = qiskitflow.Experiment(experiment_name)
start = datetime.datetime.now()
# do some quantum coding here
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.u3(3.141592653589793, 1.5707963267948966, 4.71238898038469, qreg_q[0])
quantum_circuit_execution_result = circuit.measure(qreg_q[0], creg_c[0])
end = datetime.datetime.now()
execution_time = end - start
qf.write_metric("execution time", execution_time)
qf.write_parameter("somehting important", "YEAH!")
qf.write_parameter("t1", 42)
qf.write_parameter("version of calbiration of almaden backend", 0.0.1)
qf.write_measurement("intermediate measurement", quantum_circuit_execution_result)
qf.write_result({
"something here to write as results": "great!"
})
if __name__ == "__main__":
my_quantum_program()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, QuantumRegister
qrx = QuantumRegister(3, 'x')
qry = QuantumRegister(1, 'y')
qc = QuantumCircuit(qrx, qry)
qc.x(qry)
qc.draw("mpl")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 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.
"""VectorStateFn Class"""
from typing import Dict, List, Optional, Set, Union, cast
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterExpression
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.list_ops.summed_op import SummedOp
from qiskit.opflow.list_ops.tensored_op import TensoredOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.quantum_info import Statevector
from qiskit.utils import algorithm_globals, arithmetic
from qiskit.utils.deprecation import deprecate_func
class VectorStateFn(StateFn):
"""Deprecated: A class for state functions and measurements which are defined in vector
representation, and stored using Terra's ``Statevector`` class.
"""
primitive: Statevector
# TODO allow normalization somehow?
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
primitive: Union[list, np.ndarray, Statevector] = None,
coeff: Union[complex, ParameterExpression] = 1.0,
is_measurement: bool = False,
) -> None:
"""
Args:
primitive: The ``Statevector``, NumPy array, or list, which defines the behavior of
the underlying function.
coeff: A coefficient multiplying the state function.
is_measurement: Whether the StateFn is a measurement operator
"""
# Lists and Numpy arrays representing statevectors are stored
# in Statevector objects for easier handling.
if isinstance(primitive, (np.ndarray, list)):
primitive = Statevector(primitive)
super().__init__(primitive, coeff=coeff, is_measurement=is_measurement)
def primitive_strings(self) -> Set[str]:
return {"Vector"}
@property
def num_qubits(self) -> int:
return len(self.primitive.dims())
def add(self, other: OperatorBase) -> OperatorBase:
if not self.num_qubits == other.num_qubits:
raise ValueError(
"Sum over statefns with different numbers of qubits, {} and {}, is not well "
"defined".format(self.num_qubits, other.num_qubits)
)
# Right now doesn't make sense to add a StateFn to a Measurement
if isinstance(other, VectorStateFn) and self.is_measurement == other.is_measurement:
# Covers Statevector and custom.
return VectorStateFn(
(self.coeff * self.primitive) + (other.primitive * other.coeff),
is_measurement=self._is_measurement,
)
return SummedOp([self, other])
def adjoint(self) -> "VectorStateFn":
return VectorStateFn(
self.primitive.conjugate(),
coeff=self.coeff.conjugate(),
is_measurement=(not self.is_measurement),
)
def permute(self, permutation: List[int]) -> "VectorStateFn":
new_self = self
new_num_qubits = max(permutation) + 1
if self.num_qubits != len(permutation):
# raise OpflowError("New index must be defined for each qubit of the operator.")
pass
if self.num_qubits < new_num_qubits:
# pad the operator with identities
new_self = self._expand_dim(new_num_qubits - self.num_qubits)
qc = QuantumCircuit(new_num_qubits)
# extend the permutation indices to match the size of the new matrix
permutation = (
list(filter(lambda x: x not in permutation, range(new_num_qubits))) + permutation
)
# decompose permutation into sequence of transpositions
transpositions = arithmetic.transpositions(permutation)
for trans in transpositions:
qc.swap(trans[0], trans[1])
from ..primitive_ops.circuit_op import CircuitOp
matrix = CircuitOp(qc).to_matrix()
vector = new_self.primitive.data
new_vector = cast(np.ndarray, matrix.dot(vector))
return VectorStateFn(
primitive=new_vector, coeff=self.coeff, is_measurement=self.is_measurement
)
def to_dict_fn(self) -> StateFn:
"""Creates the equivalent state function of type DictStateFn.
Returns:
A new DictStateFn equivalent to ``self``.
"""
from .dict_state_fn import DictStateFn
num_qubits = self.num_qubits
new_dict = {format(i, "b").zfill(num_qubits): v for i, v in enumerate(self.primitive.data)}
return DictStateFn(new_dict, coeff=self.coeff, is_measurement=self.is_measurement)
def _expand_dim(self, num_qubits: int) -> "VectorStateFn":
primitive = np.zeros(2**num_qubits, dtype=complex)
return VectorStateFn(
self.primitive.tensor(primitive), coeff=self.coeff, is_measurement=self.is_measurement
)
def tensor(self, other: OperatorBase) -> OperatorBase:
if isinstance(other, VectorStateFn):
return StateFn(
self.primitive.tensor(other.primitive),
coeff=self.coeff * other.coeff,
is_measurement=self.is_measurement,
)
return TensoredOp([self, other])
def to_density_matrix(self, massive: bool = False) -> np.ndarray:
OperatorBase._check_massive("to_density_matrix", True, self.num_qubits, massive)
return self.primitive.to_operator().data * self.coeff
def to_matrix(self, massive: bool = False) -> np.ndarray:
OperatorBase._check_massive("to_matrix", False, self.num_qubits, massive)
vec = self.primitive.data * self.coeff
return vec if not self.is_measurement else vec.reshape(1, -1)
def to_matrix_op(self, massive: bool = False) -> OperatorBase:
return self
def to_circuit_op(self) -> OperatorBase:
"""Return ``StateFnCircuit`` corresponding to this StateFn."""
# pylint: disable=cyclic-import
from .circuit_state_fn import CircuitStateFn
csfn = CircuitStateFn.from_vector(self.primitive.data) * self.coeff
return csfn.adjoint() if self.is_measurement else csfn
def __str__(self) -> str:
prim_str = str(self.primitive)
if self.coeff == 1.0:
return "{}({})".format(
"VectorStateFn" if not self.is_measurement else "MeasurementVector", prim_str
)
else:
return "{}({}) * {}".format(
"VectorStateFn" if not self.is_measurement else "MeasurementVector",
prim_str,
self.coeff,
)
# pylint: disable=too-many-return-statements
def eval(
self,
front: Optional[
Union[str, Dict[str, complex], np.ndarray, Statevector, OperatorBase]
] = None,
) -> Union[OperatorBase, complex]:
if front is None: # this object is already a VectorStateFn
return self
if not self.is_measurement and isinstance(front, OperatorBase):
raise ValueError(
"Cannot compute overlap with StateFn or Operator if not Measurement. Try taking "
"sf.adjoint() first to convert to measurement."
)
if isinstance(front, ListOp) and front.distributive:
return front.combo_fn(
[self.eval(front.coeff * front_elem) for front_elem in front.oplist]
)
if not isinstance(front, OperatorBase):
front = StateFn(front)
# pylint: disable=cyclic-import
from ..operator_globals import EVAL_SIG_DIGITS
from .operator_state_fn import OperatorStateFn
from .circuit_state_fn import CircuitStateFn
from .dict_state_fn import DictStateFn
if isinstance(front, DictStateFn):
return np.round(
sum(
v * self.primitive.data[int(b, 2)] * front.coeff
for (b, v) in front.primitive.items()
)
* self.coeff,
decimals=EVAL_SIG_DIGITS,
)
if isinstance(front, VectorStateFn):
# Need to extract the element or np.array([1]) is returned.
return np.round(
np.dot(self.to_matrix(), front.to_matrix())[0], decimals=EVAL_SIG_DIGITS
)
if isinstance(front, CircuitStateFn):
# Don't reimplement logic from CircuitStateFn
return np.conj(front.adjoint().eval(self.adjoint().primitive)) * self.coeff
if isinstance(front, OperatorStateFn):
return front.adjoint().eval(self.primitive) * self.coeff
return front.adjoint().eval(self.adjoint().primitive).adjoint() * self.coeff # type: ignore
def sample(
self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False
) -> dict:
deterministic_counts = self.primitive.probabilities_dict()
# Don't need to square because probabilities_dict already does.
probs = np.array(list(deterministic_counts.values()))
unique, counts = np.unique(
algorithm_globals.random.choice(
list(deterministic_counts.keys()), size=shots, p=(probs / sum(probs))
),
return_counts=True,
)
counts = dict(zip(unique, counts))
if reverse_endianness:
scaled_dict = {bstr[::-1]: (prob / shots) for (bstr, prob) in counts.items()}
else:
scaled_dict = {bstr: (prob / shots) for (bstr, prob) in counts.items()}
return dict(sorted(scaled_dict.items(), key=lambda x: x[1], reverse=True))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import (
MinimumEigenOptimizer,
RecursiveMinimumEigenOptimizer,
SolutionSample,
OptimizationResultStatus,
)
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from typing import List, Tuple
import numpy as np
# create a QUBO
qubo = QuadraticProgram()
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())
op, offset = qubo.to_ising()
print("offset: {}".format(offset))
print("operator:")
print(op)
qp = QuadraticProgram()
qp.from_ising(op, offset, linear=True)
print(qp.prettyprint())
algorithm_globals.random_seed = 10598
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA
exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver
exact_result = exact.solve(qubo)
print(exact_result.prettyprint())
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
print("variable order:", [var.name for var in qaoa_result.variables])
for s in qaoa_result.samples:
print(s)
def get_filtered_samples(
samples: List[SolutionSample],
threshold: float = 0,
allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,),
):
res = []
for s in samples:
if s.status in allowed_status and s.probability > threshold:
res.append(s)
return res
filtered_samples = get_filtered_samples(
qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
for s in filtered_samples:
print(s)
fvals = [s.fval for s in qaoa_result.samples]
probabilities = [s.probability for s in qaoa_result.samples]
np.mean(fvals)
np.std(fvals)
samples_for_plot = {
" ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact)
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result.prettyprint())
filtered_samples = get_filtered_samples(
rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
samples_for_plot = {
" ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qgss-2023
|
qiskit-community
|
# required imports:
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, CXGate
import numpy as np
ket0 = [[1],[0]]
array_to_latex(ket0)
bra0 = [1,0]
array_to_latex(bra0)
ket1 = [[0], [1]]
bra1 = [0, 1]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
grade_lab1_ex1([ket1, bra1])
sv_bra0 = Statevector(bra0)
sv_bra0
sv_bra0.draw('latex')
sv_eq = Statevector([1/2, 3/4, 4/5, 6/8])
sv_eq.draw('latex')
sv_eq.is_valid()
sv_valid = Statevector([1/2, 1/2, 1/2, 1/2])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
grade_lab1_ex2(sv_valid)
op_bra0 = Operator(bra0)
op_bra0
op_ket0 = Operator(ket0)
op_bra0.tensor(op_ket0)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
ketbra = np.outer(ket0,bra0)
array_to_latex(ketbra)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
bra1ket0 = [0]
bra0ket1 = [0]
bra1ket1 = [1]
ket1bra0 = [[0, 0], [1, 0]]
ket0bra1 = [[0, 1], [0, 0]]
ket1bra1 = [[0, 0], [0, 1]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1])
answer = ['a']
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
grade_lab1_ex4(answer)
m1 = Operator([[1,1],[0,0]])
array_to_latex(m1)
m3 = Operator([[0,1],[1,0]])
array_to_latex(m3)
array_to_latex(m1@ket0)
m2 = Operator([[1, 0], [0, 1]])
m4 = Operator([[0, 0], [1, 1]])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
grade_lab1_ex5([m2, m4])
cnot = CXGate()
array_to_latex(cnot)
m3.is_unitary()
random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j,
-0.14128434-0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j,
-0.38038841+0.55868196j],
[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j,
0.14128434+0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j,
0.38038841-0.55868196j]]))
random.is_unitary()
non_unitary_op = Operator(np.array([0,1,2,3]))
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
grade_lab1_ex6(non_unitary_op)
pauli_x = Pauli('X')
array_to_latex(pauli_x)
pauli_y = Pauli('Y')
array_to_latex(pauli_y)
pauli_z = Pauli('Z')
array_to_latex(pauli_z)
op_x = Operator(pauli_x)
op_x
op_new = np.dot(op_x,ket0)
array_to_latex(op_new)
result = [[0.+0.j], [-1.+0.j]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
grade_lab1_ex7(result)
hadamard = HGate()
array_to_latex(hadamard)
hop = Operator(hadamard)
hop.is_unitary()
bell = QuantumCircuit(2)
bell.h(0) # apply an H gate to the circuit
bell.cx(0,1) # apply a CNOT gate to the circuit
bell.draw(output="mpl")
bell_op = Operator(bell)
array_to_latex(bell_op)
ghz = QuantumCircuit(3)
##############################
# add gates to your circuit here
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(1, 2)
##############################
ghz.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
grade_lab1_ex8(ghz)
plus_state = Statevector.from_label("+")
plus_state.draw('latex')
plus_state
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing into one state or the other
res = plus_state.measure()
res
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure(0, 0)
qc.draw(output="mpl")
sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)])
sv_bell.draw('latex')
sv_bell.probabilities_dict()
sv_psi_plus = Statevector([0, np.sqrt(1/2), np.sqrt(1/2), 0])
prob_psi_plus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_psi_minus = Statevector([0, np.sqrt(1/2), -np.sqrt(1/2), 0])
prob_psi_minus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_phi_minus = Statevector([np.sqrt(1/2), 0, 0, -np.sqrt(1/2)])
prob_phi_minus = {'00': 0.5000000000000001, '11': 0.5000000000000001}
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
qft = QuantumCircuit(2)
##############################
# add gates to your circuit here
qft.h(1)
qft.cp(np.pi/2, 0, 1)
qft.h(0)
qft.swap(0, 1)
##############################
qft.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
grade_lab1_ex10(qft)
U = Operator(qft)
array_to_latex(U)
|
https://github.com/wrlee7609/hybrid_quantum_gap_estimation
|
wrlee7609
|
# Ignore warning message
import warnings
warnings.filterwarnings("ignore")
# Import python libraries
import math, json
import numpy as np
from numpy import pi
from numpy.linalg import eigvals
from numpy.fft import fft, rfft
from scipy.interpolate import CubicSpline
from scipy.optimize import curve_fit, minimize
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import colors
# Import Qiskit libraries
import qiskit
import qiskit_aer.noise as noise
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, Aer, transpile, execute
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, depolarizing_error
from qiskit.result import marginal_counts
# Load IBMQ account
provider = IBMQ.load_account()
# Problem: Max-cut problem
import networkx as nx
from scipy.optimize import minimize
def maxcut_obj(x, G):
obj = 0
for i, j in G.edges():
if x[i] != x[j]:
obj -= 1
return obj
def compute_expectation(counts, G):
avg = 0
sum_count = 0
for bitstring, count in counts.items():
obj = maxcut_obj(bitstring[::-1], G)
avg += obj * count
sum_count += count
return avg/sum_count
def create_qaoa_circ(G, theta):
nqubits = len(G.nodes())
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
# problem unitary
for pair in list(G.edges()):
qc.rzz(2 * gamma[irep], pair[0], pair[1])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure_all()
return qc
def get_expectation(G, shots=512):
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(G, theta)
counts = backend.run(qc, seed_simulator=10, nshots=512).result().get_counts()
return compute_expectation(counts, G)
return execute_circ
G = nx.Graph()
G.add_nodes_from([0, 1, 2, 3])
G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0)])
expectation = get_expectation(G)
result = minimize(expectation, [1.0, 1.0], method='Nelder-Mead', tol=1e-3)
result
# Problem: Rosenberg function
from numpy import atleast_1d, eye, argmin, zeros, shape, squeeze, asarray, sqrt, Inf, asfarray
import numpy as np
from scipy.optimize import minimize
def rosen(x):
x = np.array(x)
r = np.sum(100.0 * a * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0, axis=0)
return r
def callback(x):
global Nfeval
print(' {0:4d} {1:3.6f} {2:3.6f} {3:3.6f} {4:3.6f} {5:3.6f}'.format(Nfeval, x[0], x[1], x[2], x[3], rosen(x)))
Nfeval += 1
print('{0:4s} {1:9s} {2:9s} {3:9s} {4:9s} {5:9s}'.format('Iteration', ' X1', ' X2', ' X3', ' X4', 'f(X)'))
Nfeval = 1
a = 1
x0 = [1.3, 0.7, 0.9, 1.1]
result = minimize(rosen, x0, method='Nelder-Mead', tol=1e-3, callback=callback)
result
# Problem: Transverse-field Ising model
# Set up parameters
Nc = 5 # number of spins: N (= 2, 3, 4, 5)
g = 0.4 # dimensionless Ising coupling: J/h (= 0.2, 0.4, 0.6, 0.8)
eta = 0.3 # dimensionless broadening: \eta/h (= 0.02, 0.1, 0.2, 0.3)
dw = 0.25*eta # dimensionless unit of discrete frequency: \delta\omega / h
L = 2*math.ceil(7.0/dw) # count of Fourier components: L
Le = 100
dt = 2*pi/L/dw # dimensionless unit of discrete time: h \delta t
M = 35 # Trotter depth cutoff: M
shots = 1024 # count of measurement shots
# Define the identity and Pauli matrices
s0 = np.matrix([[1,0],[0,1]])
s1 = np.matrix([[0,1],[1,0]])
s2 = np.matrix([[0,-1j],[1j,0]])
s3 = np.matrix([[1,0],[0,-1]])
# Define the model Hamitonian
Ham = np.kron(s1,s0) + np.kron(s0,s1) + g * np.kron(s3,s3)
if Nc >= 3:
for j in range(3,Nc+1):
Ide = s0
for k in range(j-3):
Ide = np.kron(Ide,s0)
Ham = np.kron(Ham,s0) + np.kron(np.kron(Ide,s0),s1) + g * np.kron(np.kron(Ide,s3),s3)
# Calculate the exact energy gap
evals = eigvals(Ham)
idx = evals.argsort()[::1]
evals = evals[idx]
ExactGap = evals[1] - evals[0]
# set the initial guess of energy gap
IniGap = 2*(1-(1-1/Nc)*g)
# Define the bit string (00...0) as a reference for thr initial state
s = []
for j in range (Nc):
s.append('0')
str1 = ""
InQ = str1.join(s)
# Define discrete frequencies
frequency = [(j-L/2)*dw for j in range(L+1)]
with open('data_frequency', 'w') as f:
f.write(json.dumps(frequency))
# Define the objective function for curve fitting of the Lorentzian function
def objective (x, a0, a1, a2):
return a0 + a1 / ((x - a2)**2 + eta**2)
# Print preliminary data
print("N = %s, J/h = %.2f, M = %s" % (Nc,g,M))
print("Initial gap = %.6f" % IniGap)
print("Exact gap = %.6f" % ExactGap)
# Simulation type: ideal (noiseless)
def InvPeak_Ideal(theta):
global ExactGap, IniGap
# number of alternating unitaries
P = len(theta)//2
beta = theta[:P]
gamma = theta[P:]
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc, 'c')
qc = QuantumCircuit(qreg, creg)
# Set up the unitary for trial state
for p in range (P):
for n in range (Nc-1):
qc.rzz(gamma[p]*pi, qreg[n], qreg[n+1])
for n in range (Nc):
qc.ry(beta[p]*pi, qreg[n])
# Time evolution: Iterate Trotter steps
for m in range (M):
# Apply a sequence of unitary gates for time evolution
for n in range (Nc):
qc.rx(-2*j*(-1)**i*dt/M, qreg[n])
for n in range (Nc-1):
qc.rzz(-2*g*j*(-1)**i*dt/M, qreg[n], qreg[n+1])
# Set up the inverse unitary for trial state
for p in range (P):
for n in range (Nc):
qc.ry(-beta[P-p-1]*pi, qreg[n])
for n in range (Nc-1):
qc.rzz(-gamma[P-p-1]*pi, qreg[n], qreg[n+1])
# Measure qubits
qc.measure(qreg, creg)
# Perform quantum simulation on the IBMQ Aer simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots = shots).result()
counts = result.get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
if (i==1) and (j>L-10):
print(L-1-j,end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-2*eta/dw),math.ceil(L/2+1+2*eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-2*eta/dw),math.ceil(L/2+1+2*eta/dw))]
# Curve fitting for the Lorentzian function
a2 = 0
popt, _ = curve_fit(lambda x, a0, a1: objective(x, a0, a1, a2), frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Truncate the lists in the range [IniGap-\eta,IniGap+\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2+(IniGap-2*eta)/dw),math.ceil(L/2+1+(IniGap+2*eta)/dw))]
spectral_function_truncated = [spectral_function[j] for j in range(math.ceil(L/2+(IniGap-2*eta)/dw),math.ceil(L/2+1+(IniGap+2*eta)/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1, a2 = popt
return -a1/eta**2, a2, abs(a2 - ExactGap)/ExactGap, spectral_function
# Define wrapper functions
def InvPeak_Ideal_1(theta):
obj1, obj2, obj3, obj4 = InvPeak_Ideal(theta)
return obj1
def InvPeak_Ideal_2(theta):
obj1, obj2, obj3, obj4 = InvPeak_Ideal(theta)
return obj2
def InvPeak_Ideal_3(theta):
obj1, obj2, obj3, obj4 = InvPeak_Ideal(theta)
return obj3
def InvPeak_Ideal_4(theta):
obj1, obj2, obj3, obj4 = InvPeak_Ideal(theta)
return obj4
# Define callback function
def callback (theta):
global data, Nfeval, theta0
Nfeval += 1
P0 = len(theta0)//2
beta0 = theta0[:P0]
gamma0 = theta0[P0:]
P = len(theta)//2
beta = theta[:P]
gamma = theta[P:]
peak = -InvPeak_Ideal_1(theta)
gap_est = InvPeak_Ideal_2(theta)
gap_err = InvPeak_Ideal_3(theta)
spectral_function = InvPeak_Ideal_4(theta)
# Print/save data
print(' {0:4d} {1:3.6f} {2:3.6f} {3:3.6f} {4:3.6f} {5:3.6f}'\
.format(Nfeval, beta[0], gamma[0], peak, gap_est, gap_err))
data.append([Nfeval, beta[0], gamma[0], peak, gap_est, gap_err])
with open('data_spectral_ideal_N%s_g%.2f_eta%.2f_M%s_beta%.2f_gamma%.2f_NM%s' %
(int(Nc),g,eta,int(M),beta0[0],gamma0[0],int(Nfeval)), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the start message
print("Simulation type: Ideal")
print("Optimization method: Nelder-Mead")
# Set parameters
data = []
Nfeval = 0
theta0 = [0.5, 0.1]
P0 = len(theta0)//2
beta0 = theta0[:P0]
gamma0 = theta0[P0:]
bounds = ((0,2),(0,2))
# Save data
print('{0:4s} {1:9s} {2:9s} {3:9s} {4:9s} {5:9s}'\
.format('Iteration',' beta/pi','gamma/pi','height','gap_est','gap_error'))
# Estimate energy gap
result = minimize(InvPeak_Ideal_1, theta0, method='Nelder-Mead', tol=1e-2, bounds=bounds, callback=callback)
# Save data
with open('data_iteration_ideal_N%s_g%.2f_eta%.2f_M%s_beta%.2f_gamma%.2f_NM' %
(int(Nc),g,eta,int(M),beta0[0],gamma0[0]), 'w') as f:
f.write(json.dumps(data))
# Print the end message
print(result)
# Build noise model from backend calibration data
backend = provider.get_backend("ibmq_manila")
noise_model = NoiseModel.from_backend(backend)
coupling_map = backend.configuration().coupling_map
basis_gates = noise_model.basis_gates
# Simulation type: Device noise model
def InvPeak_Noisy(theta):
global ExactGap, IniGap
# number of alternating unitaries
P = len(theta)//2
beta = theta[:P]
gamma = theta[P:]
# Loop for causal (i=0) and anti-causal (i=1) processes
for i in range (2):
# Print the message
#print("...running")
# Initialize array
propagator = []
# Loop for Fourier components
for j in range (L):
# Initialize a set of quantum/classical registers
qreg = QuantumRegister(Nc, 'q')
creg = ClassicalRegister(Nc, 'c')
qc = QuantumCircuit(qreg, creg)
# Set up input state in QAOA
for p in range (P):
for n in range (Nc-1):
qc.rzz(gamma[p]*pi, qreg[n], qreg[n+1])
for n in range (Nc):
qc.ry(beta[p]*pi, qreg[n])
# Time evolution: Iterate Trotter steps
for m in range (M):
# Apply a sequence of unitary gates for time evolution
for n in range (Nc):
qc.rx(-2*j*(-1)**i*dt/M, qreg[n])
for n in range (Nc-1):
qc.rzz(-2*g*j*(-1)**i*dt/M, qreg[n], qreg[n+1])
# Set up the state to compenstate input in QAOA
for p in range (P):
for n in range (Nc):
qc.ry(-beta[P-p-1]*pi, qreg[n])
for n in range (Nc-1):
qc.rzz(-gamma[P-p-1]*pi, qreg[n], qreg[n+1])
# Measure qubits
qc.measure(qreg, creg)
# Perform quantum simulation on the IBMQ Aer simulator
simulator = Aer.get_backend('qasm_simulator')
qc_trans = transpile(qc, backend, optimization_level = 1, initial_layout = [k for k in range(Nc)])
result = execute(qc_trans, simulator, noise_model = noise_model, coupling_map = coupling_map,\
basis_gates = basis_gates, shots = shots).result()
counts = result.get_counts()
# Construct a time series of propagators with each component being the probability for (00...0)
if InQ in counts:
propagator.append(dt*np.exp(-eta*j*dt)*counts[InQ]/shots)
else:
propagator.append(0)
# Print the end message for each step
print(j+1, end="\r")
# Flatten array
propagator = np.ravel(propagator)
# Find the many-body spectral function via discreate fast Fourier transform
if i == 0:
spectral_function_0r = np.real(np.fft.ifft(propagator))*L/2.0/pi
spectral_function_1r = np.append(spectral_function_0r[int(L/2):L], spectral_function_0r[0:int(L/2)+1])
else:
spectral_function_0a = np.real(np.fft.fft(propagator))/2.0/pi
spectral_function_1a = np.append(spectral_function_0a[int(L/2):L], spectral_function_0a[0:int(L/2)+1])
# Find the many-body spectral function via discreate fast Fourier transform
spectral_function_2 = [spectral_function_1r[j] + spectral_function_1a[j] for j in range(L+1)]
# Truncate the lists in the range [-\eta,\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2-2*eta/dw),math.ceil(L/2+1+2*eta/dw))]
spectral_function_truncated = [spectral_function_2[j] for j in range(math.ceil(L/2-2*eta/dw),math.ceil(L/2+1+2*eta/dw))]
# Curve fitting for the Lorentzian function
a2 = 0
popt, _ = curve_fit(lambda x, a0, a1: objective(x, a0, a1, a2), frequency_truncated, spectral_function_truncated)
a0, a1 = popt
# Subtract the zeto peak from the manu-body spectral function
spectral_function = [spectral_function_2[j] - a1 / (frequency[j]**2 + eta**2) for j in range(L+1)]
# Truncate the lists in the range [IniGap-\eta,IniGap+\eta]
frequency_truncated = [frequency[j] for j in range(math.ceil(L/2+(IniGap-2*eta)/dw),math.ceil(L/2+1+(IniGap+2*eta)/dw))]
spectral_function_truncated = [spectral_function[j] for j in range(math.ceil(L/2+(IniGap-2*eta)/dw),math.ceil(L/2+1+(IniGap+2*eta)/dw))]
# Curve fitting for the Lorentzian function
popt, _ = curve_fit(objective, frequency_truncated, spectral_function_truncated)
a0, a1, a2 = popt
return -a1/eta**2, a2, abs(a2 - ExactGap)/ExactGap, spectral_function
# Define wrapper functions
def InvPeak_Noisy_1(theta):
obj1, obj2, obj3, obj4 = InvPeak_Noisy(theta)
return obj1
def InvPeak_Noisy_2(theta):
obj1, obj2, obj3, obj4 = InvPeak_Noisy(theta)
return obj2
def InvPeak_Noisy_3(theta):
obj1, obj2, obj3, obj4 = InvPeak_Noisy(theta)
return obj3
def InvPeak_Noisy_4(theta):
obj1, obj2, obj3, obj4 = InvPeak_Noisy(theta)
return obj4
# Define callback function
def callback (theta):
global data, Nfeval, theta0
Nfeval += 1
P0 = len(theta0)//2
beta0 = theta0[:P0]
gamma0 = theta0[P0:]
P = len(theta)//2
beta = theta[:P]
gamma = theta[P:]
peak = -InvPeak_Noisy_1(theta)
gap_est = InvPeak_Noisy_2(theta)
gap_err = InvPeak_Noisy_3(theta)
spectral_function = InvPeak_Noisy_4(theta)
# Print/save data
print(' {0:4d} {1:3.6f} {2:3.6f} {3:3.6f} {4:3.6f} {5:3.6f}'\
.format(Nfeval, beta[0], gamma[0], peak, gap_est, gap_err))
data.append([Nfeval, beta[0], gamma[0], peak, gap_est, gap_err])
with open('data_spectral_noisy_N%s_g%.2f_eta%.2f_M%s_beta%.2f_gamma%.2f_NM%s' %
(int(Nc),g,eta,int(M),beta0[0],gamma0[0],int(Nfeval)), 'w') as f:
f.write(json.dumps(spectral_function))
# Print the start message
print("Simulation type: Device noise model")
print("Optimization method: Nelder-Mead")
# Set parameters
data = []
Nfeval = 0
theta0 = [0.5, 0.1]
P0 = len(theta0)//2
beta0 = theta0[:P0]
gamma0 = theta0[P0:]
bounds = ((0,2),(0,2))
# Save data
print('{0:4s} {1:9s} {2:9s} {3:9s} {4:9s} {5:9s}'\
.format('Iteration',' beta/pi','gamma/pi','height','gap_est','gap_error'))
# Estimate energy gap
result = minimize(InvPeak_Noisy_1, theta0, method='Nelder-Mead', tol=1e-2, bounds=bounds, callback=callback)
# Save data
with open('data_iteration_noisy_N%s_g%.2f_eta%.2f_M%s_beta%.2f_gamma%.2f_NM' %
(int(Nc),g,eta,int(M),beta0[0],gamma0[0]), 'w') as f:
f.write(json.dumps(data))
# Print the end message
print(result)
|
https://github.com/ionq-samples/getting-started
|
ionq-samples
|
import json, os, requests, time
from getpass import getpass
# Before you begin, get your API key from https://cloud.ionq.com/settings/keys
# If your API key is stored as "IONQ_API_KEY" in your local environment, this
# should find it. Otherwise you'll be prompted to enter your API key manually.
api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ')
def submit_job(headers, data):
url = "https://api.ionq.co/v0.3/jobs"
response = requests.post(url, headers=headers, data=data)
response_json = response.json()
assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
return response_json["id"]
def query_job(job_id, headers):
url = f"https://api.ionq.co/v0.3/jobs/{job_id}"
response = requests.get(url, headers=headers)
response_json = response.json()
assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
return response_json["status"]
def get_job_results(job_id, headers):
url = f"https://api.ionq.co/v0.3/jobs/{job_id}/results"
response = requests.get(url, headers=headers)
response_json = response.json()
assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}"
return response_json
headers = {
"Authorization": f"apiKey {api_key}",
"Content-Type": "application/json",
}
data = {
"name": "API Example Circuit",
"shots": 100,
"target": "simulator",
"input": {
"format": "ionq.circuit.v0",
"gateset": "qis",
"qubits": 2,
"circuit": [
{
"gate": "h",
"target": 0
},
{
"gate": "cnot",
"control": 0,
"target": 1
}
]
}
}
# Now we'll send the job to our backend for processing.
job_id = submit_job(headers, json.dumps(data))
# And wait for the job to be run.
status = "ready"
while status != "completed":
time.sleep(1) # wait for 1 second before querying again
status = query_job(job_id, headers)
# And once the job has run, we can plot the results.
results = get_job_results(job_id, headers)
print(results)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as pp
from sklearn.datasets import load_wine
%matplotlib inline
# Constants
DATA_PATH = "../../Data/Raw/data.csv"
CLEAN_DATA_PATH = "../../Data/Processed/winedata.csv"
raw_data = load_wine()
features = pd.DataFrame(data=raw_data['data'],columns=raw_data['feature_names'])
data = features
data['target']=raw_data['target']
data['class']=data['target'].map(lambda ind: raw_data['target_names'][ind])
data.head()
data.shape
data.columns
print(raw_data['DESCR'])
data.info()
data.describe()
def check_unique(df):
""""
Checks the unique value in each column
:param df: The dataframe
"""
for col in df.columns:
unique = df[col].unique()
print("Column: {} has {} unique values\n".format(col, unique))
check_unique(data)
fig = plt.figure()
sns.countplot(x="target", data=data, palette="gist_rainbow_r")
plt.xlabel("Heart disease (0 = have, 1 = don't)")
plt.title("Target distribution")
plt.show()
fig.savefig("../../Output/Figures/targetdist.png", )
data = data[data['class'] != 'class_2']
data.duplicated().sum()
data.drop_duplicates(inplace=True)
data.drop('target', axis=1).corrwith(data['target']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target")
pp.ProfileReport(df=data, dark_mode=True, explorative=True)
data = data[['alcohol', 'flavanoids', 'color_intensity', 'proline', 'target']]
data.to_csv(CLEAN_DATA_PATH, index=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
theta = Parameter('$\\theta$')
chsh_circuits_no_meas = QuantumCircuit(2)
chsh_circuits_no_meas.h(0)
chsh_circuits_no_meas.cx(0, 1)
chsh_circuits_no_meas.ry(theta, 0)
chsh_circuits_no_meas.draw('mpl')
import numpy as np
number_of_phases = 21
phases = np.linspace(0, 2*np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Estimator, Session
from qiskit.quantum_info import SparsePauliOp
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
chsh_est_sim = []
# Simulator
with Session(service=service, backend=backend):
estimator = Estimator()
for op in ops:
job = estimator.run(
circuits=[chsh_circuits_no_meas]*len(individual_phases),
observables=[op]*len(individual_phases),
parameter_values=individual_phases)
est_result = job.result()
chsh_est_sim.append(est_result)
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est_sim = chsh_est_sim[0].values - chsh_est_sim[1].values + chsh_est_sim[2].values + chsh_est_sim[3].values
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est_sim = chsh_est_sim[0].values + chsh_est_sim[1].values - chsh_est_sim[2].values + chsh_est_sim[3].values
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig, ax = plt.subplots(figsize=(10, 6))
# results from a simulator
ax.plot(phases/np.pi, chsh1_est_sim, 'o-', label='CHSH1 Simulation')
ax.plot(phases/np.pi, chsh2_est_sim, 'o-', label='CHSH2 Simulation')
# classical bound +-2
ax.axhline(y=2, color='r', linestyle='--')
ax.axhline(y=-2, color='r', linestyle='--')
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2)*2, color='b', linestyle='-.')
ax.axhline(y=-np.sqrt(2)*2, color='b', linestyle='-.')
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $\pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title('Violation of CHSH Inequality')
plt.xlabel('Theta')
plt.ylabel('CHSH witness')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(3, 3)
qc.draw(output='mpl')
# we will teleport the state q_0 to q_2 with using q_1
qc.x(0)
qc.barrier()
qc.draw(output='mpl')
# barrier decide that after barrier q_0 has state |1> than of |0>
qc.h(1)
qc.cx(1, 2)
qc.draw(output='mpl')
# It created an entangled state means same qubit exits on q_1 and q_2 at the same time also
qc.cx(0, 1)
qc.h(0)
qc.draw(output='mpl')
qc.barrier()
qc.measure([0,1],[0,1])
qc.draw(output='mpl')
# before measure all the states are entangled but to complete the teleportation process
qc.barrier()
qc.cx(1,2)
qc.cz(0,2)
qc.draw(output='mpl')
# the qubit at q_0 teleported to the state q_2
# let's measure q_2 states
qc.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
# It is used to transfer quantum information over long distances
"""
Question : Build a Quantum Teleportation circuit to teleport the qubit |+> or |->
"""
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.barrier()
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""Dynamical Decoupling insertion pass."""
import itertools
import numpy as np
from qiskit.circuit import Gate, Delay, Reset
from qiskit.circuit.library.standard_gates import IGate, UGate, U3Gate
from qiskit.dagcircuit import DAGOpNode, DAGInNode
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.synthesis.one_qubit import OneQubitEulerDecomposer
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.passes.optimization import Optimize1qGates
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.utils.deprecation import deprecate_func
class DynamicalDecoupling(TransformationPass):
"""Dynamical decoupling insertion pass.
This pass works on a scheduled, physical circuit. It scans the circuit for
idle periods of time (i.e. those containing delay instructions) and inserts
a DD sequence of gates in those spots. These gates amount to the identity,
so do not alter the logical action of the circuit, but have the effect of
mitigating decoherence in those idle periods.
As a special case, the pass allows a length-1 sequence (e.g. [XGate()]).
In this case the DD insertion happens only when the gate inverse can be
absorbed into a neighboring gate in the circuit (so we would still be
replacing Delay with something that is equivalent to the identity).
This can be used, for instance, as a Hahn echo.
This pass ensures that the inserted sequence preserves the circuit exactly
(including global phase).
.. plot::
:include-source:
import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import XGate
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ALAPSchedule, DynamicalDecoupling
from qiskit.visualization import timeline_drawer
# Because the legacy passes do not propagate the scheduling information correctly, it is
# necessary to run a no-op "re-schedule" before the output circuits can be drawn.
def draw(circuit):
from qiskit import transpile
scheduled = transpile(
circuit,
optimization_level=0,
instruction_durations=InstructionDurations(),
scheduling_method="alap",
)
return timeline_drawer(scheduled)
circ = QuantumCircuit(4)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.cx(2, 3)
circ.measure_all()
durations = InstructionDurations(
[("h", 0, 50), ("cx", [0, 1], 700), ("reset", None, 10),
("cx", [1, 2], 200), ("cx", [2, 3], 300),
("x", None, 50), ("measure", None, 1000)]
)
# balanced X-X sequence on all qubits
dd_sequence = [XGate(), XGate()]
pm = PassManager([ALAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)])
circ_dd = pm.run(circ)
draw(circ_dd)
# Uhrig sequence on qubit 0
n = 8
dd_sequence = [XGate()] * n
def uhrig_pulse_location(k):
return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
spacing = []
for k in range(n):
spacing.append(uhrig_pulse_location(k) - sum(spacing))
spacing.append(1 - sum(spacing))
pm = PassManager(
[
ALAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing),
]
)
circ_dd = pm.run(circ)
draw(circ_dd)
"""
@deprecate_func(
additional_msg=(
"Instead, use :class:`~.PadDynamicalDecoupling`, which performs the same "
"function but requires scheduling and alignment analysis passes to run prior to it."
),
since="1.1.0",
)
def __init__(
self, durations, dd_sequence, qubits=None, spacing=None, skip_reset_qubits=True, target=None
):
"""Dynamical decoupling initializer.
Args:
durations (InstructionDurations): Durations of instructions to be
used in scheduling.
dd_sequence (list[Gate]): sequence of gates to apply in idle spots.
qubits (list[int]): physical qubits on which to apply DD.
If None, all qubits will undergo DD (when possible).
spacing (list[float]): a list of spacings between the DD gates.
The available slack will be divided according to this.
The list length must be one more than the length of dd_sequence,
and the elements must sum to 1. If None, a balanced spacing
will be used [d/2, d, d, ..., d, d, d/2].
skip_reset_qubits (bool): if True, does not insert DD on idle
periods that immediately follow initialized/reset qubits (as
qubits in the ground state are less susceptile to decoherence).
target (Target): The :class:`~.Target` representing the target backend, if both
``durations`` and this are specified then this argument will take
precedence and ``durations`` will be ignored.
"""
super().__init__()
self._durations = durations
self._dd_sequence = dd_sequence
self._qubits = qubits
self._spacing = spacing
self._skip_reset_qubits = skip_reset_qubits
self._target = target
if target is not None:
self._durations = target.durations()
for gate in dd_sequence:
if gate.name not in target.operation_names:
raise TranspilerError(
f"{gate.name} in dd_sequence is not supported in the target"
)
def run(self, dag):
"""Run the DynamicalDecoupling pass on dag.
Args:
dag (DAGCircuit): a scheduled DAG.
Returns:
DAGCircuit: equivalent circuit with delays interrupted by DD,
where possible.
Raises:
TranspilerError: if the circuit is not mapped on physical qubits.
"""
if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None:
raise TranspilerError("DD runs on physical circuits only.")
if dag.duration is None:
raise TranspilerError("DD runs after circuit is scheduled.")
durations = self._update_inst_durations(dag)
num_pulses = len(self._dd_sequence)
sequence_gphase = 0
if num_pulses != 1:
if num_pulses % 2 != 0:
raise TranspilerError("DD sequence must contain an even number of gates (or 1).")
noop = np.eye(2)
for gate in self._dd_sequence:
noop = noop.dot(gate.to_matrix())
if not matrix_equal(noop, IGate().to_matrix(), ignore_phase=True):
raise TranspilerError("The DD sequence does not make an identity operation.")
sequence_gphase = np.angle(noop[0][0])
if self._qubits is None:
self._qubits = set(range(dag.num_qubits()))
else:
self._qubits = set(self._qubits)
if self._spacing:
if sum(self._spacing) != 1 or any(a < 0 for a in self._spacing):
raise TranspilerError(
"The spacings must be given in terms of fractions "
"of the slack period and sum to 1."
)
else: # default to balanced spacing
mid = 1 / num_pulses
end = mid / 2
self._spacing = [end] + [mid] * (num_pulses - 1) + [end]
for qarg in list(self._qubits):
for gate in self._dd_sequence:
if not self.__gate_supported(gate, qarg):
self._qubits.discard(qarg)
break
index_sequence_duration_map = {}
for physical_qubit in self._qubits:
dd_sequence_duration = 0
for index, gate in enumerate(self._dd_sequence):
gate = gate.to_mutable()
self._dd_sequence[index] = gate
gate.duration = durations.get(gate, physical_qubit)
dd_sequence_duration += gate.duration
index_sequence_duration_map[physical_qubit] = dd_sequence_duration
new_dag = dag.copy_empty_like()
for nd in dag.topological_op_nodes():
if not isinstance(nd.op, Delay):
new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False)
continue
dag_qubit = nd.qargs[0]
physical_qubit = dag.find_bit(dag_qubit).index
if physical_qubit not in self._qubits: # skip unwanted qubits
new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False)
continue
pred = next(dag.predecessors(nd))
succ = next(dag.successors(nd))
if self._skip_reset_qubits: # discount initial delays
if isinstance(pred, DAGInNode) or isinstance(pred.op, Reset):
new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False)
continue
dd_sequence_duration = index_sequence_duration_map[physical_qubit]
slack = nd.op.duration - dd_sequence_duration
if slack <= 0: # dd doesn't fit
new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False)
continue
if num_pulses == 1: # special case of using a single gate for DD
u_inv = self._dd_sequence[0].inverse().to_matrix()
theta, phi, lam, phase = OneQubitEulerDecomposer().angles_and_phase(u_inv)
# absorb the inverse into the successor (from left in circuit)
if isinstance(succ, DAGOpNode) and isinstance(succ.op, (UGate, U3Gate)):
theta_r, phi_r, lam_r = succ.op.params
succ.op.params = Optimize1qGates.compose_u3(
theta_r, phi_r, lam_r, theta, phi, lam
)
sequence_gphase += phase
# absorb the inverse into the predecessor (from right in circuit)
elif isinstance(pred, DAGOpNode) and isinstance(pred.op, (UGate, U3Gate)):
theta_l, phi_l, lam_l = pred.op.params
pred.op.params = Optimize1qGates.compose_u3(
theta, phi, lam, theta_l, phi_l, lam_l
)
sequence_gphase += phase
# don't do anything if there's no single-qubit gate to absorb the inverse
else:
new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False)
continue
# insert the actual DD sequence
taus = [int(slack * a) for a in self._spacing]
unused_slack = slack - sum(taus) # unused, due to rounding to int multiples of dt
middle_index = int((len(taus) - 1) / 2) # arbitrary: redistribute to middle
taus[middle_index] += unused_slack # now we add up to original delay duration
for tau, gate in itertools.zip_longest(taus, self._dd_sequence):
if tau > 0:
new_dag.apply_operation_back(Delay(tau), [dag_qubit], check=False)
if gate is not None:
new_dag.apply_operation_back(gate, [dag_qubit], check=False)
new_dag.global_phase = new_dag.global_phase + sequence_gphase
return new_dag
def _update_inst_durations(self, dag):
"""Update instruction durations with circuit information. If the dag contains gate
calibrations and no instruction durations were provided through the target or as a
standalone input, the circuit calibration durations will be used.
The priority order for instruction durations is: target > standalone > circuit.
"""
circ_durations = InstructionDurations()
if dag.calibrations:
cal_durations = []
for gate, gate_cals in dag.calibrations.items():
for (qubits, parameters), schedule in gate_cals.items():
cal_durations.append((gate, qubits, parameters, schedule.duration))
circ_durations.update(cal_durations, circ_durations.dt)
if self._durations is not None:
circ_durations.update(self._durations, getattr(self._durations, "dt", None))
return circ_durations
def __gate_supported(self, gate: Gate, qarg: int) -> bool:
"""A gate is supported on the qubit (qarg) or not."""
if self._target is None or self._target.instruction_supported(gate.name, qargs=(qarg,)):
return True
return False
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import numpy as np
from IPython.display import display, Math, Latex
%matplotlib inline
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# The '0' state
plot_bloch_vector([0,0,1])
# The '1' state
plot_bloch_vector([0,0,-1])
qc1 = QuantumCircuit(2,2) # Initializing a quantum ciruit (2 qubits, 2 classical bits)
# All initialized to '0' by default.
qc1.draw(output='mpl') # Draws the circuit diagram
qc1.x(0) # Applying X gate to the first qubit
qc1.draw(output='mpl')
qc1.x(1) # Applying X gate to the second qubit
qc1.draw(output='mpl')
# The '+' state
plot_bloch_vector([1,0,0])
# The '-' state
plot_bloch_vector([-1,0,0])
qc2 = QuantumCircuit(2,2) # A new quantum circuit with 2 qubits and 2 classical bits
qc2.h(0) # Applying the Hadamard gate on first qubit
qc2.draw(output='mpl')
qc2.cx(0,1) # Applying CX gate ('control','target')
qc2.draw(output='mpl')
qc2.measure(0,0) # Measure first qubit and store it in first classical bit
qc2.measure(1,1) # Measure second qubit and store it in second classical bit
# The code below plots a histogram of the measurement result. You can copy it for further use.
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc2)
print(counts)
plot_histogram(counts)
qc1.h(0)
qc1.cx(0, 1)
qc1.draw(output='mpl')
qc1.measure(0,0)
qc1.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc1)
print(counts)
plot_histogram(counts)
qc3 = QuantumCircuit(3,3)
qc3.x(range(3)) # Setting the all qubits to '1'
qc3.toffoli(0,1,2) # (control,control,target)
qc3.measure(0,0)
qc3.measure(1,1)
qc3.measure(2,2)
def run_circuit(qc3):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc3, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc3)
print(counts)
plot_histogram(counts)
# The output should be '011' as the highest (q2) is flipped because the other two qubits were set to '1'
qc4 = QuantumCircuit(2,2)
#Applying the Pauli-X gate to quantum bit 0, we turn it into 1 so that the swap outcome is observable.
qc4.x(0)
qc4.cx(0, 1)
qc4.cx(1, 0)
qc4.cx(0, 1)
qc4.draw(output='mpl')
qc4.measure(0,0)
qc4.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc4)
print(counts)
plot_histogram(counts)
qc5 = QuantumCircuit(2,2)
#We turn quantum bit 1 into 1 so that we can observe the results of HZH on both 0 (from q0) and 1 (from q1).
qc5.x(1)
qc5.h((0, 1))
qc5.z((0, 1))
qc5.h((0, 1))
qc5.draw(output='mpl')
qc5.measure(0,0)
qc5.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc5)
print(counts)
plot_histogram(counts)
qc6 = QuantumCircuit(3,3)
#Initializing quantum bits using gates:
#q0 is initialized to 0.
#q1 is initialized to 1.
qc6.x(1)
#q2 is initialized to the state given above.
qc6.x(2)
qc6.h(2)
qc6.t(2)
#We change q2 for the controlled swap now; we'll bring it back to the same state afterwards.
qc6.tdg(2)
qc6.h(2)
#Controlled swap.
qc6.toffoli(0, 2, 1)
qc6.toffoli(1, 2, 0)
qc6.toffoli(0, 2, 1)
#We convert q2 back to whatever it was.
qc6.h(2)
qc6.t(2)
qc6.draw(output='mpl')
qc6.measure(0, 0)
qc6.measure(1, 1)
qc6.measure(2, 2)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc6)
print(counts)
plot_histogram(counts)
|
https://github.com/Qubit-MU/Qiskit_Fall_Fest_2023
|
Qubit-MU
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
event = "Qiskit Fall Fest"
## Write your code below here. Delete the current information and replace it with your own ##
## Make sure to write your information between the quotation marks!
name = "Rochelle Li"
age = "19"
school = "University of Wisconsin Madison"
## Now press the "Run" button in the toolbar above, or press Shift + Enter while you're active in this cell
## You do not need to write any code in this cell. Simply run this cell to see your information in a sentence. ##
print(f'My name is {name}, I am {age} years old, and I attend {school}.')
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
# Create quantum circuit with 3 qubits and 3 classical bits
# (we'll explain why we need the classical bits later)
qc = QuantumCircuit(3,3)
# return a drawing of the circuit
qc.draw()
## You don't need to write any new code in this cell, just run it
from qiskit import QuantumCircuit
qc = QuantumCircuit(3,3)
# measure all the qubits
qc.measure([0,1,2], [0,1,2])
qc.draw(output="mpl")
from qiskit.providers.aer import AerSimulator
# make a new simulator object
sim = AerSimulator()
job = sim.run(qc) # run the experiment
result = job.result() # get the results
result.get_counts() # interpret the results as a "counts" dictionary
from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
## Write your code below here ##
qc = QuantumCircuit(4,4)
qc.measure([0,1,2,3], [0,1,2,3])
## Do not modify the code under this line ##
qc.draw()
sim = AerSimulator() # make a new simulator object
job = sim.run(qc) # run the experiment
result = job.result() # get the results
answer1 = result.get_counts()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1a
grade_ex1a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
# We start by flipping the first qubit, which is qubit 0, using an X gate
qc.x(0)
# Next we add an H gate on qubit 0, putting this qubit in superposition.
qc.h(0)
# Finally we add a CX (CNOT) gate on qubit 0 and qubit 1
# This entangles the two qubits together
qc.cx(0, 1)
qc.draw(output="mpl")
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
## Write your code below here ##
qc.h(0)
qc.cx(0,1)
## Do not modify the code under this line ##
answer2 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1b
grade_ex1b(answer2)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import *
# Let's create a circuit to put a state in superposition and measure it
circ = QuantumCircuit(1,1) # We use one qubit and also one classical bit for the measure result
circ.h(0) #We apply the H gate
circ.measure(range(1),range(1)) # We measure
circ.draw(output='mpl') #We draw the circuit
print(circ.qasm())
# Executing on the local simulator
backend_sim = Aer.get_backend('qasm_simulator') # We choose the backend
job_sim = execute(circ, backend_sim, shots=1024) # We execute the circuit, selecting the number of repetitions or 'shots'
result_sim = job_sim.result() # We collect the results
counts = result_sim.get_counts(circ) # We obtain the frequency of each result and we show them
print(counts)
plot_histogram(counts)
# Execution to the get the statevector
circ2 = QuantumCircuit(1,1)
circ2.h(0)
backend = Aer.get_backend('statevector_simulator') # We change the backend
job = execute(circ2, backend) # We execute the circuit with the new simulator. Now, we do not need repetitions
result = job.result() # We collect the results and access the stavector
outputstate = result.get_statevector(circ2)
print(outputstate)
backend = Aer.get_backend('unitary_simulator') # We change the backend again
job = execute(circ2, backend) # We execute the circuit
result = job.result() # We collect the results and obtain the matrix
unitary = result.get_unitary()
print(unitary)
# Connecting to the real quantum computers
provider = IBMQ.load_account() # We load our account
provider.backends() # We retrieve the backends to check their status
for b in provider.backends():
print(b.status().to_dict())
# Executing on the IBM Q Experience simulator
backend_sim = provider.get_backend('ibmq_qasm_simulator') # We choose the backend
job_sim = execute(circ, backend_sim, shots=1024) # We execute the circuit, selecting the number of repetitions or 'shots'
result_sim = job_sim.result() # We collect the results
counts = result_sim.get_counts(circ) # We obtain the frequency of each result and we show them
print(counts)
plot_histogram(counts)
# Executing on the quantum computer
backend = provider.get_backend('ibmq_armonk')
job_exp = execute(circ, backend=backend)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(circ)
plot_histogram([counts_exp,counts], legend=['Device', 'Simulator'])
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
from qiskit import QuantumCircuit
import numpy as np
from qiskit import QuantumCircuit, assemble, Aer
def deutsch_problem(seed=None):
"""Returns a circuit that carries out the function
from Deutsch's problem.
Args:
seed (int): If set, then returned circuit will
always be the same for the same seed.
Returns: QuantumCircuit
"""
np.random.seed(seed)
problem = QuantumCircuit(2)
if np.random.randint(2):
print("Function is balanced.")
problem.cx(0, 1)
else:
print("Function is constant.")
if np.random.randint(2):
problem.x(1)
return problem
def deutsch(problem):
"""Implements Deutsch's algorithm.
Args:
function (QuantumCircuit): Deutsch function to solve.
Must be a 2-qubit circuit, and either balanced,
or constant.
Returns:
bool: True if the circuit is balanced, otherwise False.
"""
qc=QuantumCircuit(2,1)
qc.x(1)
qc.h([0,1])
qc.draw()
qc.append(problem.to_gate(label='f'),[0,1])
qc.h(0)
qc.measure(0,0)
qc = qc.decompose('f')
display(qc.draw())
sim = Aer.get_backend('aer_simulator')
state = sim.run(qc).result().get_counts() # Execute the circuit and get the count
state=list(state.keys())[0] ## fetch the bit from the Dictionary
if state=='1':
return('balanced')
if state=='0':
return('constant')
problem=deutsch_problem()
print(deutsch(problem))
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
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()
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}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
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 label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["VibrationalEnergy"]
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
# this is now done explicitly and already requires the basis
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianLogResult
from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
hamiltonian = log_result.get_vibrational_energy()
print(hamiltonian)
hamiltonian.basis = HarmonicBasis([2, 2, 3, 4])
op = hamiltonian.second_q_ops()["VibrationalEnergy"]
print("\n".join(str(op).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianLogResult
from qiskit_nature.second_q.formats import watson_to_problem
from qiskit_nature.second_q.problems import HarmonicBasis
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
watson = log_result.get_watson_hamiltonian()
print(watson)
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = watson_to_problem(watson, basis)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("VibrationalEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
# Cell 1
import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.visualization import plot_histogram
from IPython.display import display, Math, Latex
from may4_challenge import plot_state_qsphere
from may4_challenge.ex1 import minicomposer
from may4_challenge.ex1 import check1, check2, check3, check4, check5, check6, check7, check8
from may4_challenge.ex1 import return_state, vec_in_braket, statevec
# Cell 2
# press shift + return to run this code cell
# then, click on the gate that you want to apply to your qubit
# next, you have to choos
# the qubit that you want to apply it to (choose '0' here)
# click on clear to restart
minicomposer(1, dirac=True, qsphere=True)
# Cell 3
def create_circuit():
qc = QuantumCircuit(1)
qc.x(0)
return qc
# check solution
qc = create_circuit()
state = statevec(qc)
check1(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 4
def create_circuit2():
qc = QuantumCircuit(1)
qc.h(0)
return qc
qc = create_circuit2()
state = statevec(qc)
check2(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 5
def create_circuit3():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
return qc
qc = create_circuit3()
state = statevec(qc)
check3(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 6
def create_circuit4():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.s(0)
return qc
qc = create_circuit4()
state = statevec(qc)
check4(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 7
# press shift + return to run this code cell
# then, click on the gate that you want to apply followed by the qubit(s) that you want it to apply to
# for controlled gates, the first qubit you choose is the control qubit and the second one the target qubit
# click on clear to restart
minicomposer(2, dirac = True, qsphere = True)
# Cell 8
def create_circuit():
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
return qc
qc = create_circuit()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check5(state)
qc.draw(output='mpl') # we draw the circuit
# Cell 9
def create_circuit6():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
qc.h(0)
qc.cx(0,1)
qc.y(1)
return qc
qc = create_circuit6()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check6(state)
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
qc.draw(output='mpl') # we draw the circuit
# Cell 10
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
check
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def create_circuit6():
qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
return qc
qc = create_circuit6()
state = statevec(qc)
display(Math(vec_in_braket(state.data)))
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)
qc.measure(2,2)# we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.draw(output='mpl') # we draw the circuit
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
check8(counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw(output='mpl')
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
from qiskit.transpiler import passes
[pass_ for pass_ in dir(passes) if pass_[0].isupper()]
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
basic_circ.draw(output='mpl')
lookahead_circ.draw(output='mpl')
stochastic_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0)]
qc.initialize(random_state, range(4))
qc.draw()
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
circ.draw(output='mpl')
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
dag.op_nodes()
node = dag.op_nodes()[3]
print("node name: ", node.name)
print("node op: ", node.op)
print("node qargs: ", node.qargs)
print("node cargs: ", node.cargs)
print("node condition: ", node.op.condition)
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]])
mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]])
# substitute the cx node with the above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw(output='mpl')
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
"""Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw(output='mpl')
out_circ.draw(output='mpl')
import logging
logging.basicConfig(level='DEBUG')
from qiskit.providers.fake_provider import FakeTenerife
log_circ = QuantumCircuit(2, 2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0, 1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ, backend);
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend);
# Change log level back to DEBUG
logging.getLogger('qiskit.transpiler').setLevel('DEBUG')
# Transpile multiple circuits
circuits = [log_circ, log_circ]
transpile(circuits, backend);
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend);
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
print("Ch 5: Least busy backend")
print("------------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Finding the least busy backend
backend = least_busy(provider.backends(operational=True, simulator=False))
print("Least busy backend:", backend.name())
filtered_backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
print("\nLeast busy 5-qubit backend:", filtered_backend.name())
from qiskit.tools.monitor import backend_overview
print("\nAll backends overview:\n")
backend_overview()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
import numpy as np
from numpy import linalg as la
from qiskit.tools.monitor import job_monitor
import qiskit.tools.jupyter
qc = QuantumCircuit(1)
#### your code goes here
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
# your code goes here
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
# your code goes here
shots = 2**14 # number of samples used for statistics
sim = Aer.get_backend('qasm_simulator')
bloch_vector_measure = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector_measure.append( probs['0'] - probs['1'] )
# normalizing the bloch sphere vector
bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure)
print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]'
.format(*bloch_vector))
from kaleidoscope.interactive import bloch_sphere
bloch_sphere(bloch_vector, vectors_annotation=True)
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector( bloch_vector )
# circuit for the state Tri1
Tri1 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri2
Tri2 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri3
Tri3 = QuantumCircuit(2)
# your code goes here
# circuit for the state Sing
Sing = QuantumCircuit(2)
# your code goes here
# <ZZ>
measure_ZZ = QuantumCircuit(2)
measure_ZZ.measure_all()
# <XX>
measure_XX = QuantumCircuit(2)
# your code goes here
# <YY>
measure_YY = QuantumCircuit(2)
# your code goes here
shots = 2**14 # number of samples used for statistics
A = 1.47e-6 #unit of A is eV
E_sim = []
for state_init in [Tri1,Tri2,Tri3,Sing]:
Energy_meas = []
for measure_circuit in [measure_XX, measure_YY, measure_ZZ]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
qc = state_init+measure_circuit
counts = execute(qc, sim, shots=shots).result().get_counts()
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E_sim.append(A * np.sum(np.array(Energy_meas)))
# Run this cell to print out your results
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3]))
# reduced plank constant in (eV) and the speed of light(cgs units)
hbar, c = 4.1357e-15, 3e10
# energy difference between the triplets and singlet
E_del = abs(E_sim[0] - E_sim[3])
# frequency associated with the energy difference
f = E_del/hbar
# convert frequency to wavelength in (cm)
wavelength = c/f
print('The wavelength of the radiation from the transition\
in the hyperfine structure is : {:.1f} cm'.format(wavelength))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
# run this cell to get the backend information through the widget
backend
# assign your choice for the initial layout to the list variable `initial_layout`.
initial_layout =
qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing]
for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ]
shots = 8192
job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots)
print(job.job_id())
job_monitor(job)
# getting the results of your job
results = job.result()
## To access the results of the completed job
#results = backend.retrieve_job('job_id').result()
def Energy(results, shots):
"""Compute the energy levels of the hydrogen ground state.
Parameters:
results (obj): results, results from executing the circuits for measuring a hamiltonian.
shots (int): shots, number of shots used for the circuit execution.
Returns:
Energy (list): energy values of the four different hydrogen ground states
"""
E = []
A = 1.47e-6
for ind_state in range(4):
Energy_meas = []
for ind_comp in range(3):
counts = results.get_counts(ind_state*3+ind_comp)
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E.append(A * np.sum(np.array(Energy_meas)))
return E
E = Energy(results, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3]))
from qiskit.ignis.mitigation.measurement import *
# your code to create the circuits, meas_calibs, goes here
meas_calibs, state_labels =
# execute meas_calibs on your choice of the backend
job = execute(meas_calibs, backend, shots = shots)
print(job.job_id())
job_monitor(job)
cal_results = job.result()
## To access the results of the completed job
#cal_results = backend.retrieve_job('job_id').result()
# your code to obtain the measurement filter object, 'meas_filter', goes here
results_new = meas_filter.apply(results)
E_new = Energy(results_new, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3]))
# results for the energy estimation from the simulation,
# execution on a quantum system without error mitigation and
# with error mitigation in numpy array format
Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new)
# Calculate the relative errors of the energy values without error mitigation
# and assign to the numpy array variable `Err_rel_orig` of size 4
Err_rel_orig =
# Calculate the relative errors of the energy values with error mitigation
# and assign to the numpy array variable `Err_rel_new` of size 4
Err_rel_new =
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
without measurement error mitigation : {}'.format(Err_rel_orig))
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
with measurement error mitigation : {}'.format(Err_rel_new))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
#Let us begin by importing necessary libraries.
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import *
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit.utils import algorithm_globals
from qiskit_finance import QiskitFinanceError
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import *
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
warnings.simplefilter("ignore", SymPyDeprecationWarning)
# Set parameters for assets and risk factor
num_assets = 4 # set number of assets to 4
q = 0.5 # set risk factor to 0.5
budget = 2 # set budget as defined in the problem
seed = 132 # set random seed
# Generate time series data
stocks = [("STOCK%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
start=datetime.datetime(1955,11,5),
end=datetime.datetime(1985,10,26),
seed=seed)
data.run()
# Let's plot our finanical data
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.xlabel('days')
plt.ylabel('stock value')
plt.show()
#Let's calculate the expected return for our problem data
mu = data.get_period_return_mean_vector() # Returns a vector containing the mean value of each asset's expected return.
print(mu)
# Let's plot our covariance matrix Σ(sigma)
sigma = data.get_period_return_covariance_matrix() #Returns the covariance matrix of the four assets
print(sigma)
fig, ax = plt.subplots(1,1)
im = plt.imshow(sigma, extent=[-1,1,-1,1])
x_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
y_label_list = ['stock3', 'stock2', 'stock1', 'stock0']
ax.set_xticks([-0.75,-0.25,0.25,0.75])
ax.set_yticks([0.75,0.25,-0.25,-0.75])
ax.set_xticklabels(x_label_list)
ax.set_yticklabels(y_label_list)
plt.colorbar()
plt.clim(-0.000002, 0.00001)
plt.show()
##############################
# Provide your code here
portfolio =
qp =
##############################
print(qp)
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex1a
grade_ex1a(qp)
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print(result)
optimizer = SLSQP(maxiter=1000)
algorithm_globals.random_seed = 1234
backend = Aer.get_backend('statevector_simulator')
##############################
# Provide your code here
vqe =
##############################
vqe_meo = MinimumEigenOptimizer(vqe) #please do not change this code
result = vqe_meo.solve(qp) #please do not change this code
print(result) #please do not change this code
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex1b
grade_ex1b(vqe, qp)
#Step 1: Let us begin by importing necessary libraries
import qiskit
from qiskit import Aer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import *
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit.utils import algorithm_globals
from qiskit_finance import QiskitFinanceError
from qiskit_finance.applications.optimization import *
from qiskit_finance.data_providers import *
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.applications import OptimizationApplication
from qiskit_optimization.converters import QuadraticProgramToQubo
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
import warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
warnings.simplefilter("ignore",SymPyDeprecationWarning)
# Step 2. Generate time series data for four assets.
# Do not change start/end dates specified to generate problem data.
seed = 132
num_assets = 4
stocks = [("STOCK%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
start=datetime.datetime(1955,11,5),
end=datetime.datetime(1985,10,26),
seed=seed)
data.run()
# Let's plot our finanical data (We are generating the same time series data as in the previous example.)
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.xlabel('days')
plt.ylabel('stock value')
plt.show()
# Step 3. Calculate mu and sigma for this problem
mu2 = data.get_period_return_mean_vector() #Returns a vector containing the mean value of each asset.
sigma2 = data.get_period_return_covariance_matrix() #Returns the covariance matrix associated with the assets.
print(mu2, sigma2)
# Step 4. Set parameters and constraints based on this challenge 1c
##############################
# Provide your code here
q2 = #Set risk factor to 0.5
budget2 = #Set budget to 3
##############################
# Step 5. Complete code to generate the portfolio instance
##############################
# Provide your code here
portfolio2 =
qp2 =
##############################
# Step 6. Now let's use QAOA to solve this problem.
optimizer = SLSQP(maxiter=1000)
algorithm_globals.random_seed = 1234
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
##############################
# Provide your code here
qaoa =
##############################
qaoa_meo = MinimumEigenOptimizer(qaoa) #please do not change this code
result2 = qaoa_meo.solve(qp2) #please do not change this code
print(result2) #please do not change this code
# Check your answer and submit using the following code
from qc_grader.challenges.unimelb_2022 import grade_ex1c
grade_ex1c(qaoa, qp2)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
config = backend.configuration()
# Basic Features
print("This backend is called {0}, and is on version {1}. It has {2} qubit{3}. It "
"{4} OpenPulse programs. The basis gates supported on this device are {5}."
"".format(config.backend_name,
config.backend_version,
config.n_qubits,
'' if config.n_qubits == 1 else 's',
'supports' if config.open_pulse else 'does not support',
config.basis_gates))
config.dt # units of seconds
config.meas_levels
config.dtm
config.meas_map
config.drive(0)
config.measure(0)
config.acquire(0)
props = backend.properties()
def describe_qubit(qubit, properties):
"""Print a string describing some of reported properties of the given qubit."""
# Conversion factors from standard SI units
us = 1e6
ns = 1e9
GHz = 1e-9
print("Qubit {0} has a \n"
" - T1 time of {1} microseconds\n"
" - T2 time of {2} microseconds\n"
" - U2 gate error of {3}\n"
" - U2 gate duration of {4} nanoseconds\n"
" - resonant frequency of {5} GHz".format(
qubit,
properties.t1(qubit) * us,
properties.t2(qubit) * us,
properties.gate_error('sx', qubit),
properties.gate_length('sx', qubit) * ns,
properties.frequency(qubit) * GHz))
describe_qubit(0, props)
defaults = backend.defaults()
q0_freq = defaults.qubit_freq_est[0] # Hz
q0_meas_freq = defaults.meas_freq_est[0] # Hz
GHz = 1e-9
print("DriveChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_freq * GHz))
print("MeasureChannel(0) defaults to a modulation frequency of {} GHz.".format(q0_meas_freq * GHz))
calibrations = defaults.instruction_schedule_map
print(calibrations)
measure_schedule = calibrations.get('measure', range(config.n_qubits))
measure_schedule.draw(backend=backend)
# You can use `has` to see if an operation is defined. Ex: Does qubit 3 have an x gate defined?
calibrations.has('x', 3)
# Some circuit operations take parameters. U1 takes a rotation angle:
calibrations.get('u1', 0, P0=3.1415)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Replace each sequence of Clifford, Linear Function or Permutation gates by a single block of these types of gate."""
from functools import partial
from qiskit import QuantumCircuit
from qiskit.circuit import Instruction
from qiskit.circuit.barrier import Barrier
from qiskit.circuit.library import LinearFunction, PermutationGate
from qiskit.converters import circuit_to_dag, dag_to_dagdependency, dagdependency_to_dag
from qiskit.dagcircuit.dagcircuit import DAGCircuit
from qiskit.quantum_info.operators import Clifford
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.passes.optimization.collect_and_collapse import (
CollectAndCollapse,
collapse_to_operation,
)
from qiskit.transpiler.passes.utils import control_flow
CLIFFORD_MAX_BLOCK_SIZE = 9
LINEAR_MAX_BLOCK_SIZE = 9
PERMUTATION_MAX_BLOCK_SIZE = 12
clifford_gate_names = [
"x",
"y",
"z",
"h",
"s",
"sdg",
"cx",
"cy",
"cz",
"swap",
"clifford",
"linear_function",
"pauli",
]
linear_gate_names = ["cx", "swap", "linear_function"]
permutation_gate_names = ["swap"]
class Flatten(TransformationPass):
"""Replaces all instructions that contain a circuit with their circuit"""
def __init__(self, node_names):
super().__init__()
self.node_names = node_names
def run(self, dag: DAGCircuit):
for node in dag.named_nodes(*self.node_names):
if (
hasattr(node.op, "params")
and len(node.op.params) > 1
and isinstance(node.op.params[1], QuantumCircuit)
):
dag.substitute_node_with_dag(node, circuit_to_dag(node.op.params[1]))
return dag
_flatten_cliffords = Flatten(("clifford", "Clifford"))
_flatten_linearfunctions = Flatten(("linear_function", "Linear_function"))
_flatten_permutations = Flatten(("permutation", "Permutation"))
from qiskit.dagcircuit.collect_blocks import BlockCollector
class GreedyBlockCollector(BlockCollector):
def __init__(self, dag, max_block_size):
super().__init__(dag)
self.max_block_size = max_block_size
def collect_matching_block(self, filter_fn):
"""Iteratively collects the largest block of input nodes (that is, nodes with
``_in_degree`` equal to 0) that match a given filtering function, limiting the
maximum size of the block.
"""
current_block = []
unprocessed_pending_nodes = self._pending_nodes
self._pending_nodes = []
block_qargs = set()
# Iteratively process unprocessed_pending_nodes:
# - any node that does not match filter_fn is added to pending_nodes
# - any node that match filter_fn is added to the current_block,
# and some of its successors may be moved to unprocessed_pending_nodes.
while unprocessed_pending_nodes:
node = unprocessed_pending_nodes.pop()
if isinstance(node.op, Barrier):
continue
new_qargs = block_qargs.copy()
for q in node.qargs:
new_qargs.add(q)
if filter_fn(node) and len(new_qargs) <= self.max_block_size:
current_block.append(node)
block_qargs = new_qargs
# update the _in_degree of node's successors
for suc in self._direct_succs(node):
self._in_degree[suc] -= 1
if self._in_degree[suc] == 0:
unprocessed_pending_nodes.append(suc)
else:
self._pending_nodes.append(node)
return current_block
class BlockChecker:
def __init__(self, gates, block_class):
self.gates = gates
self.block_class = block_class
self.current_set = set()
def select(self, node):
"""Decides if the node should be added to the block."""
return (
node.op.name in self.gates and getattr(node.op, "condition", None) is None
)
def collapse(self, circuit):
"""Construcs an Gate object for the block."""
self.current_set = set()
return self.block_class(circuit)
class CliffordInstruction(Instruction):
def __init__(self, circuit):
circuit = _flatten_cliffords(circuit)
super().__init__(
name="Clifford",
num_qubits=circuit.num_qubits,
num_clbits=0,
params=[Clifford(circuit), circuit],
)
def construct_permutation_gate(circuit):
circuit = _flatten_permutations(circuit)
return PermutationGate(LinearFunction(circuit).permutation_pattern())
def construct_linearfunction_gate(circuit):
circuit = _flatten_linearfunctions(circuit)
return LinearFunction(circuit)
class RepeatedCollectAndCollapse(CollectAndCollapse):
def __init__(
self,
block_checker: BlockChecker,
do_commutative_analysis=True,
split_blocks=True,
min_block_size=2,
max_block_size=1000,
split_layers=False,
collect_from_back=False,
num_reps=10,
):
collect_function = lambda dag: GreedyBlockCollector(
dag, max_block_size
).collect_all_matching_blocks(
filter_fn=block_checker.select,
split_blocks=split_blocks,
min_block_size=min_block_size,
split_layers=split_layers,
collect_from_back=collect_from_back,
)
collapse_function = partial(
collapse_to_operation, collapse_function=block_checker.collapse
)
super().__init__(
collect_function=collect_function,
collapse_function=collapse_function,
do_commutative_analysis=do_commutative_analysis,
)
self.num_reps = num_reps
@control_flow.trivial_recurse
def run(self, dag):
"""Run the CollectLinearFunctions pass on `dag`.
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
"""
# If the option commutative_analysis is set, construct DAGDependency from the given DAGCircuit.
if self.do_commutative_analysis:
dag = dag_to_dagdependency(dag)
for _ in range(self.num_reps):
# call collect_function to collect blocks from DAG
blocks = self.collect_function(dag)
# call collapse_function to collapse each block in the DAG
self.collapse_function(dag, blocks)
# If the option commutative_analysis is set, construct back DAGCircuit from DAGDependency.
if self.do_commutative_analysis:
dag = dagdependency_to_dag(dag)
return dag
class CollectCliffords(RepeatedCollectAndCollapse):
"""CollectCliffords(do_commutative_analysis: bool = True, min_block_size: int = 2, max_block_size: int = CLIFFORD_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects Clifford blocks as `Instruction` objects and stores the original sub-circuit to compare against it after synthesis.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect Cliffords pass, defaults to 2.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect Cliffords pass, defaults to 9.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=2,
max_block_size=CLIFFORD_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=clifford_gate_names,
block_class=CliffordInstruction,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
class CollectLinearFunctions(RepeatedCollectAndCollapse):
"""CollectLinearFunctions(do_commutative_analysis: bool = True, min_block_size: int = 4, max_block_size: int = LINEAR_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects blocks of `SWAP` and `CX` as `LinearFunction` objects and stores the original sub-circuit to compare against it after synthesis.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect linear functions pass, defaults to 4.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect linear functions pass, defaults to 9.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=4,
max_block_size=LINEAR_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=linear_gate_names,
block_class=construct_linearfunction_gate,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
class CollectPermutations(RepeatedCollectAndCollapse):
"""CollectPermutations(do_commutative_analysis: bool = True, min_block_size: int = 4, max_block_size: int = PERMUTATION_MAX_BLOCK_SIZE, collect_from_back: bool = False, num_reps: int = 10)
Collects blocks of `SWAP` circuits as `Permutations`.
:param do_commutative_analysis: Enable or disable commutative analysis, defaults to True
:type do_commutative_analysis: bool, optional
:param min_block_size: Set the minimum size for blocks generated during the collect permutations pass, defaults to 4.
:type min_block_size: int, optional
:param max_block_size: Set the maximum size for blocks generated during the collect permutations pass, defaults to 12.
:type max_block_size: int, optional
:param collect_from_back: Specify if collect blocks in reverse order or not, defaults to False.
:type collect_from_back: bool, optional
:param num_reps: Specify how many times to repeat the optimization process, defaults to 10.
:type num_reps: int, optional
"""
def __init__(
self,
do_commutative_analysis=True,
min_block_size=4,
max_block_size=PERMUTATION_MAX_BLOCK_SIZE,
collect_from_back=False,
num_reps=10,
):
super().__init__(
BlockChecker(
gates=permutation_gate_names,
block_class=construct_permutation_gate,
),
do_commutative_analysis=do_commutative_analysis,
split_blocks=True,
min_block_size=min_block_size,
max_block_size=max_block_size,
split_layers=False,
collect_from_back=collect_from_back,
num_reps=num_reps,
)
|
https://github.com/The-Singularity-Research/QISKit-Surface-Codes
|
The-Singularity-Research
|
from collections import Counter
from typing import Tuple, List
from networkx import MultiGraph
from networkx import nx
from networkx.algorithms import bipartite
from sympy.combinatorics import Permutation
import matplotlib.pyplot as plt
# from SurfaceCodes.utilites import permlist_to_tuple
class SurfaceCodeGraph(MultiGraph):
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
super().__init__()
self.sigma = sigma # should include singletons corresponding to fixed points
self.alpha = alpha # should include singletons corresponding to fixed points
f = self.compute_phi()
self.phi = self.permlist_to_tuple(f)
self.build_node_info() # print dictionary for [sigma, alpha, phi]
self.node_dict = self.sigma_dict, self.alpha_dict, self.phi_dict
self.node_info = ["sigma:", self.sigma_dict,
"alpha:", self.alpha_dict,
"phi:", self.phi_dict]
self.code_graph = nx.MultiGraph()
# Create black nodes for each cycle in sigma along with white nodes
# representing "half edges" around the black nodes
for cycle in self.sigma:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_node(node, bipartite=0)
self.code_graph.add_edge(cycle, node)
# Create black nodes for each cycle in phi along with white nodes
# representing "half edges" around the black nodes
for cycle in self.phi:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_edge(cycle, node)
# Create nodes for each cycle in alpha then
# glue the nodes corresponding to a the pairs
for pair in self.alpha:
self.code_graph.add_node(pair)
self.code_graph = nx.contracted_nodes(self.code_graph, pair[0], pair[1], self_loops=True)
# Now contract pair with pair[0] to make sure edges (white nodes) are labeled
# by the pairs in alpha to keep track of the gluing from the previous step
self.code_graph = nx.contracted_nodes(self.code_graph, pair, pair[0], self_loops=True)
# Define the white and black nodes. White correspond to edges labeled by
# cycles in alpha. Black correspond to nodes labeled by cycles in sigma
# (vertices) and phi (faces)
self.black_nodes, self.white_nodes = bipartite.sets(self.code_graph)
def permlist_to_tuple(self, perms):
"""
convert list of lists to tuple of tuples in order to have two level iterables
that are hashable for the dictionaries used later
"""
return tuple(tuple(perm) for perm in perms)
def compute_phi(self):
"""compute the list of lists full cyclic form of phi (faces of dessin [sigma, alpha, phi])"""
s = Permutation(self.sigma)
a = Permutation(self.alpha)
f = ~(a * s)
f = f.full_cyclic_form # prints permutation as a list of lists including all singletons (fixed points)
return f
def build_node_info(self):
count = -1
self.sigma_dict = dict()
for count, cycle in enumerate(self.sigma):
self.sigma_dict[cycle] = count
self.phi_dict = dict()
for count, cycle in enumerate(self.phi, start=count + 1):
self.phi_dict[cycle] = count
self.alpha_dict = dict()
for count, pair in enumerate(self.alpha, start=count + 1):
self.alpha_dict[pair] = count
return tuple([self.sigma_dict, self.alpha_dict, self.phi_dict])
def boundary_1(self, edge):
"""
compute boundary of a single edge given by a white node (cycle in alpha)
"""
boundary1 = [node for node in self.code_graph.neighbors(edge) if node in self.sigma_dict]
return boundary1
def del_1(self, edges: List[Tuple[int]]):
"""
boundary of a list of edges, i.e. an arbitrary 1-chain over Z/2Z
"""
boundary_list = [self.boundary_1(edge) for edge in edges]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def boundary_2(self, face):
"""
compute boundary of a single face
"""
boundary = self.code_graph.neighbors(face)
return boundary
def del_2(self, faces: List[Tuple[int]]):
"""
boundary of a list of faces, i.e. an arbitrary 2-chain over Z/2Z
"""
boundary_list = [self.boundary_2(face) for face in faces]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def coboundary_1(self, star):
"""
compute coboundary of a single star
"""
coboundary = self.code_graph.neighbors(star)
return coboundary
def delta_1(self, stars: List[Tuple[int]]):
"""
coboundary of a list of stars, i.e. an arbitrary 0-cochain over Z/2Z
"""
coboundary_list = [self.coboundary_1(star) for star in stars]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def coboundary_2(self, edge):
"""
compute coboundary of a single edge given by a white node (cycle in alpha)
"""
coboundary2 = [node for node in self.code_graph.neighbors(edge) if node in self.phi_dict]
return coboundary2
def delta_2(self, edges: List[Tuple[int]]):
"""
coboundary of a list of edges, i.e. an arbitrary 1-cochain over Z/2Z
given by a list of cycles in alpha
"""
coboundary_list = [self.coboundary_2(edge) for edge in edges]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def euler_characteristic(self):
"""
Compute the Euler characteristic of the surface in which the graph is embedded
"""
chi = len(self.phi) - len(self.alpha) + len(self.sigma)
return (chi)
def genus(self):
"""
Compute the genus of the surface in which the graph is embedded
"""
g = int(-(len(self.phi) - len(self.alpha) + len(self.sigma) - 2) / 2)
return (g)
def draw(self, node_type='', layout = ''):
"""
Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices
corresponding to the qubit indices for the surface code
"""
if not node_type in ['cycles', 'dict']:
raise ValueError('node_type can be "cycles" or "dict"')
if layout == 'spring':
pos=nx.spring_layout(self.code_graph)
if layout == 'spectral':
pos=nx.spectral_layout(self.code_graph)
if layout == 'planar':
pos=nx.planar_layout(self.code_graph)
if layout == 'shell':
pos=nx.shell_layout(self.code_graph)
if layout == 'circular':
pos=nx.circular_layout(self.code_graph)
if layout == 'spiral':
pos=nx.spiral_layout(self.code_graph)
if layout == 'random':
pos=nx.random_layout(self.code_graph)
# white nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.alpha),
node_color='c',
node_size=500,
alpha=0.3)
# vertex nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.sigma),
node_color='b',
node_size=500,
alpha=0.6)
# face nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.phi),
node_color='r',
node_size=500,
alpha=0.6)
# edges
nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5)
labels={}
if node_type == 'cycles':
'''
label nodes the cycles of sigma, alpha, and phi
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node]=f'$e$({node})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node]=f'$v$({node})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node]=f'$f$({node})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
if node_type == 'dict':
'''
label nodes with v, e, f and indices given by node_dict corresponding to
qubit indices of surface code
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node]=f'$e$({self.alpha_dict[node]})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node]=f'$v$({self.sigma_dict[node]})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node]=f'$f$({self.phi_dict[node]})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
# plt.axis('off')
# plt.savefig("labels_and_colors.png") # save as png
plt.show() # display
sigma = ((0,1,2),(3,4,5),(6,7))
alpha = ((0,3),(1,6),(2,4),(5,7))
SCG = SurfaceCodeGraph(sigma, alpha)
SCG
SCG.draw('cycles', 'spring')
SCG.phi
SCG.node_info
SCG.code_graph.nodes
bipartite.sets(SCG.code_graph)
SCG.white_nodes
SCG.black_nodes
SCG.draw('dict', 'spring')
SCG.euler_characteristic()
SCG.genus()
SCG.del_2([(1,3,7)])
SCG.del_2([(0, 4), (1,3,7)])
SCG.delta_1([(0,1,2)])
SCG.delta_1([(0,1,2), (3,4,5)])
SCG.boundary_1((0,3))
SCG.boundary_1((1,6))
SCG.del_1([(0,3), (1,6)])
SCG.coboundary_2((0,3))
SCG.coboundary_2((1,6))
SCG.delta_2([(0,3), (1,6)])
from typing import Tuple
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
# from SurfaceCodes.surface_code_class import SurfaceCodeGraph
# from SurfaceCodes.utilites import permlist_to_tuple
class SurfaceCodeCircuit(QuantumCircuit):
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
super().__init__()
self.sigma = sigma
self.alpha = alpha
self.scgraph = SurfaceCodeGraph(self.sigma, self.alpha)
'''
Compute the permutation corresponding to phi and create a
'surface code circuit' based on a (multi)graph 'surface_code_graph'
given by sigma, alpha, and phi
Create quantum and classical registers based on the number of nodes in G
'''
# f = self.scgraph.compute_phi()
self.phi = self.scgraph.phi
self.qr = QuantumRegister(len(self.scgraph.code_graph.nodes))
self.cr = ClassicalRegister(len(self.scgraph.code_graph.nodes))
self.circ = QuantumCircuit(self.qr, self.cr)
self.node_info = self.scgraph.node_dict
self.sigma_dict, self.alpha_dict, self.phi_dict = self.node_info
for cycle in self.sigma:
self.circ.h(self.sigma_dict[cycle])
for cycle in self.phi:
self.circ.h(self.phi_dict[cycle])
def x_measurement(self, qubit: int, cbit: int):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'
:param qubit, cbit:
:return None
"""
# circuit.measure = measure # fix a bug in qiskit.circuit.measure
self.circ.h(qubit)
self.circ.measure(qubit, cbit)
self.circ.h(qubit)
def star_syndrome_measure(self, vertex: Tuple[int]):
"""
Applies CX gates to surrounding qubits of a star then measures star qubit in X-basis
:param vertex:
:return: self.circ, self.scgraph, self.node_info
"""
for node in self.scgraph.code_graph.neighbors(vertex):
self.circ.cx(self.sigma_dict[vertex], self.alpha_dict[node])
self.circ.barrier()
self.x_measurement(self.sigma_dict[vertex], self.sigma_dict[vertex])
self.circ.barrier()
return self.circ, self.scgraph, self.node_info
def face_syndrome_measure(self, vertex: Tuple[int]):
"""
Applies CZ gates to surrounding qubits of a face then measures face qubit in X-basis
:param vertex:
:return:
"""
for node in self.scgraph.code_graph.neighbors(vertex):
self.circ.cz(self.phi_dict[vertex], self.alpha_dict[node])
self.circ.barrier()
self.x_measurement(self.phi_dict[vertex], self.phi_dict[vertex])
self.circ.barrier()
return self.circ, self.scgraph, self.node_info
def product_Z(self, faces):
"""
Pauli product Z operator for arbitrary 2-chain boundary
"""
boundary_nodes = self.scgraph.del_2(faces)
for node in boundary_nodes:
self.circ.z(self.alpha_dict[node])
def product_X(self, stars):
"""
Pauli product X operator for arbitrary 0-cochain coboundary
"""
coboundary_nodes = self.scgraph.delta_1(stars)
for node in coboundary_nodes:
self.circ.x(self.alpha_dict[node])
def draw_graph(self, node_type='', layout = ''):
if layout == 'spring':
pos=nx.spring_layout(self.scgraph.code_graph)
if layout == 'spectral':
pos=nx.spectral_layout(self.scgraph.code_graph)
if layout == 'planar':
pos=nx.planar_layout(self.scgraph.code_graph)
if layout == 'shell':
pos=nx.shell_layout(self.scgraph.code_graph)
if layout == 'circular':
pos=nx.circular_layout(self.scgraph.code_graph)
if layout == 'spiral':
pos=nx.spiral_layout(self.scgraph.code_graph)
if layout == 'random':
pos=nx.random_layout(self.scgraph.code_graph)
if node_type == 'cycles':
self.scgraph.draw('cycles', layout)
if node_type == 'dict':
self.scgraph.draw('dict', layout)
SCC = SurfaceCodeCircuit(sigma, alpha)
SCC.circ.draw('mpl')
nx.draw(SCC.scgraph.code_graph, with_labels = True)
SCC.draw_graph('cycles', 'spring')
SCC.draw_graph('dict', 'spring')
SCC.node_info
SCC.sigma
SCC.alpha
SCC.phi
SCC.scgraph.code_graph.nodes
SCC.star_syndrome_measure(((0,1,2)))
SCC.circ.draw('mpl')
SCC.face_syndrome_measure(((2, 6, 5)))
SCC.circ.draw('mpl')
SCC.product_Z([(0, 4), (2, 6, 5)])
SCC.circ.draw('mpl')
SCC.product_X([(3, 4, 5), (6, 7)])
SCC.circ.draw('mpl')
sigma = ((0,1),(2,3,4),(5,6,7),(8,9),(10,11,12),(13,14,15,16),(17,18,19,20),(21,22,23),(24,25,26),(27,28,29,30),(31,32,33,34),(35,36,37),(38,39),(40,41,42),(43,44,45),(46,47))
alpha = ((0,2),(1,10),(3,5),(4,14),(6,8),(7,18),(9,22),(11,13),(12,24),(15,17),(16,28),(19,21),(20,32),(23,36),(25,27),(26,38),(29,31),(30,41),(33,35),(34,44),(37,47),(39,40),(42,43),(45,46))
SCG = SurfaceCodeGraph(sigma, alpha)
SCG.genus()
SCG.draw('dict', 'planar')
SCG.draw('dict', 'spectral')
len(SCG.code_graph.nodes())
len(SCG.sigma)
len(SCG.alpha)
len(SCG.phi)
SCG.phi
SCG.code_graph.nodes()
SCG.code_graph.remove_node((0, 10, 24, 38, 40, 43, 46, 37, 23, 9, 6, 3))
len(SCG.code_graph.nodes())
nx.draw_spectral(SCG.code_graph, with_labels = False)
G = nx.Graph()
pos = dict()
for x in range(7):
for y in range(7):
G.add_node((x,y))
pos[(x,y)] = (x,y)
if x>0:
G.add_edge((x-1,y),(x,y))
if y>0:
G.add_edge((x,y),(x,y-1))
nx.draw(G, pos=pos, with_labels = True)
nx.is_isomorphic(SCG.code_graph, G)
G1, G2 = SCG.code_graph, G
GM = nx.isomorphism.GraphMatcher(G1,G2)
GM.is_isomorphic()
GM.mapping
node_color = {(x[0], x[1]): 1-((x[0]+x[1])%2)/2 for x in G.nodes()}
for y in range(1,7,2):
for z in range(1,7,2):
node_color[(y,z)] = .2
node_color = [node_color[x] for x in sorted(node_color.keys())]
nx.draw(G, pos = pos, node_color = node_color)
|
https://github.com/matheusmtta/Quantum-Computing
|
matheusmtta
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
from qiskit.visualization import plot_state_qsphere
def BuildBell(x, y):
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
if x == 1:
U.cz(0, 1)
if y == 1:
U.x(1)
U = U.to_gate()
U.name = 'Build Bell'
#ctl_U = U.control() make it a controlled gate
return U
backend = BasicAer.get_backend('statevector_simulator')
n = 2
#bell state 00
[x, y] = [0, 0]
b00 = QuantumCircuit(n, n)
b00.append(BuildBell(x, y), range(n))
#bell state 01
[x, y] = [0, 1]
b01 = QuantumCircuit(n, n)
b01.append(BuildBell(x, y), range(n))
#bell state 10
[x, y] = [1, 0]
b10 = QuantumCircuit(n, n)
b10.append(BuildBell(x, y), range(n))
#bell state 11
[x, y] = [1, 1]
b11 = QuantumCircuit(n, n)
b11.append(BuildBell(x, y), range(n))
bqs00 = execute(b00, backend).result()
bqs01 = execute(b01, backend).result()
bqs10 = execute(b10, backend).result()
bqs11 = execute(b11, backend).result()
#GENERAL CIRCUIT b_00
bxy = QuantumCircuit(n, n)
bxy.h(0)
bxy.cx(0, 1)
bxy.measure(range(n), range(n))
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(bxy, backend=backend, shots=atp).result()
ans = res.get_counts()
bxy.draw('mpl')
plot_histogram(ans)
plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere
plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere
plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere
plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
|
https://github.com/lkcoredo/qiskitWorkshop
|
lkcoredo
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('86ae6d9e149ed5f78869fe4c6ba5b9b42419053fed9e1c0f731d63d6c7b416c9812292cc69fd2cf108e4096a6c3e20f5d7366d48de2ac650fc599d86acaa526c')
IBMQ.load_account()
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit = QuantumCircuit(qr, cr)
circuit.draw()
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')
simulator = Aer.get_backend("qasm_simulator")
execute(circuit, backend = simulator)
result = execute(circuit, backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
qcomp = provider.get_backend('ibmq_santiago')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_count(circuit))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/mentesniker/Quantum-error-mitigation
|
mentesniker
|
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, ClassicalRegister
from qiskit.ignis.verification.topological_codes import RepetitionCode
from qiskit.ignis.verification.topological_codes import lookuptable_decoding
from qiskit.ignis.verification.topological_codes import GraphDecoder
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
from qiskit.visualization import plot_histogram
import random
backend = Aer.get_backend('qasm_simulator')
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return ''.join([str(x) for x in result])
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
def get_noise(circuit,probability,qubits):
random_number = random.uniform(0, 1)
if(random_number <= probability):
qubit = random.randint(0,len(qubits)-1)
circuit.x(qubit)
return circuit
def codificate(bitString):
qubits = list()
for i in range(len(bitString)):
mycircuit = QuantumCircuit(1,1)
if(bitString[i] == "1"):
mycircuit.x(0)
qubits.append(mycircuit)
return qubits
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
m0 = tobits("I like dogs")
qubits = codificate(m0)
measurements = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit = get_noise(qubit,0.2,range(qubit.num_qubits))
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
print(frombits(measurements))
for i in range(len(qubits)):
cb = QuantumRegister(1,'code_qubit')
lq = QuantumRegister(4,'ancilla_qubit')
sb = ClassicalRegister(2,'syndrome_bit')
out = ClassicalRegister(1,'output_bit')
mycircuit = QuantumCircuit(cb,lq,sb,out)
if(m0[i] == "1"):
mycircuit.x(0)
mycircuit.cx(0,1)
mycircuit.cx(1,2)
mycircuit = get_noise(mycircuit,0.2,range(3))
mycircuit.cx(0,3)
mycircuit.cx(1,3)
mycircuit.cx(0,4)
mycircuit.cx(2,4)
mycircuit.measure(3,0)
mycircuit.measure(4,1)
qubits[i] = mycircuit
measurements = list()
raw_bits = list()
for i in range(len(qubits)):
qubit = qubits[i]
qubit.measure(0,2)
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
raw_bits.append(int(bits[0]))
for i in range(len(qubits)):
qubit = qubits[i]
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
if(bits[2] == '1' and bits[3] == '0'):
qubit.x(2)
if(bits[2] == '0' and bits[3] == '1'):
qubit.x(1)
if(bits[2] == '1' and bits[3] == '1'):
qubit.x(0)
qubit.measure(0,2)
result = execute(qubit, backend, shots=1, memory=True).result()
bits = result.get_memory()[0]
measurements.append(int(bits[0]))
print("without error correction the string was: " + frombits(raw_bits))
print("with error correction the string was: " + frombits(measurements))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(0, 0)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
qc = QuantumCircuit(q, c)
qc.h([0, 1, 2])
qc.barrier()
qc.measure(q, c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
from math import pi
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2, 0, 1)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc_S.cp(pi/2, 0, 1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2, 0).c_if(c, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2 ** (m - 2)):
qc_S.cp(pi/2, 0, 1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
from qiskit_aer.primitives import Sampler
sampler = Sampler()
job = sampler.run(qc_S)
result = job.result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1, 2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4, [0, 1], 2)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc.mcp(pi/4, [0, 1], 2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2, 0).c_if(c, 1)
qc.draw('mpl')
for _ in range(2 ** (m - 2)):
qc.mcp(pi/4, [0, 1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4, 0).c_if(c, 1)
qc.p(-pi/2, 0).c_if(c, 2)
qc.p(-3*pi/2, 0).c_if(c, 3)
# c-U operations
for _ in range(2 ** (m - 3)):
qc.mcp(pi/4, [0, 1], 2)
# X measurement
qc.h(0)
qc.measure(0, 2)
qc.draw('mpl')
result = sampler.run(qc).result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Shor's Factoring Algorithm Benchmark - Qiskit
"""
import sys
sys.path[1:1] = ["_common", "_common/qiskit", "shors/_common", "quantum-fourier-transform/qiskit"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../shors/_common", "../../quantum-fourier-transform/qiskit"]
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import math
from math import gcd
from fractions import Fraction
import time
import random
import numpy as np
np.random.seed(0)
import execute as ex
import metrics as metrics
from qft_benchmark import inv_qft_gate
from qft_benchmark import qft_gate
import copy
from utils import getAngles, getAngle, modinv, generate_numbers, choose_random_base, determine_factors
verbose = True
############### Circuit Definition
# Creation of the circuit that performs addition by a in Fourier Space
# Can also be used for subtraction by setting the parameter inv to a value different from 0
def phiADD(num_qubits, a):
qc = QuantumCircuit(num_qubits, name="\u03C6ADD")
angle = getAngles(a, num_qubits)
for i in range(0, num_qubits):
# addition
qc.u1(angle[i], i)
global PHIADD_
if PHIADD_ == None or num_qubits <= 3:
if num_qubits < 4: PHIADD_ = qc
return qc
# Single controlled version of the phiADD circuit
def cphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits, a).to_gate()
cphiadd_gate = phiadd_gate.control(1)
return cphiadd_gate
# Doubly controlled version of the phiADD circuit
def ccphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits, a).to_gate()
ccphiadd_gate = phiadd_gate.control(2)
return ccphiadd_gate
# Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N)
def ccphiADDmodN(num_qubits, a, N):
qr_ctl = QuantumRegister(2)
qr_main = QuantumRegister(num_qubits + 1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_main, qr_ancilla, name="cc\u03C6ADDmodN")
# Generate relevant gates for circuit
ccphiadda_gate = ccphiADD(num_qubits + 1, a)
ccphiadda_inv_gate = ccphiADD(num_qubits + 1, a).inverse()
phiaddN_inv_gate = phiADD(num_qubits + 1, N).inverse()
cphiaddN_gate = cphiADD(num_qubits + 1, N)
# Create relevant temporary qubit lists
ctl_main_qubits = [i for i in qr_ctl];
ctl_main_qubits.extend([i for i in qr_main])
anc_main_qubits = [qr_ancilla[0]];
anc_main_qubits.extend([i for i in qr_main])
# Create circuit
qc.append(ccphiadda_gate, ctl_main_qubits)
qc.append(phiaddN_inv_gate, qr_main)
qc.append(inv_qft_gate(num_qubits + 1), qr_main)
qc.cx(qr_main[-1], qr_ancilla[0])
qc.append(qft_gate(num_qubits + 1), qr_main)
qc.append(cphiaddN_gate, anc_main_qubits)
qc.append(ccphiadda_inv_gate, ctl_main_qubits)
qc.append(inv_qft_gate(num_qubits + 1), qr_main)
qc.x(qr_main[-1])
qc.cx(qr_main[-1], qr_ancilla[0])
qc.x(qr_main[-1])
qc.append(qft_gate(num_qubits + 1), qr_main)
qc.append(ccphiadda_gate, ctl_main_qubits)
global CCPHIADDMODN_
if CCPHIADDMODN_ == None or num_qubits <= 2:
if num_qubits < 3: CCPHIADDMODN_ = qc
return qc
# Circuit that implements the inverse of doubly controlled modular addition by a
def ccphiADDmodN_inv(num_qubits, a, N):
cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N)
cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse()
return cchpiAddmodN_inv_circ
# Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits
# needed to represent the integer number N
def cMULTamodN(n, a, N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n + 1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name="cMULTamodN")
# quantum Fourier transform only on auxillary qubits
qc.append(qft_gate(n + 1), qr_main)
for i in range(n):
ccphiADDmodN_gate = ccphiADDmodN(n, (2 ** i) * a % N, N)
# Create relevant temporary qubit list
qubits = [qr_ctl[0]];
qubits.extend([qr_x[i]])
qubits.extend([i for i in qr_main]);
qubits.extend([qr_ancilla[0]])
qc.append(ccphiADDmodN_gate, qubits)
# inverse quantum Fourier transform only on auxillary qubits
qc.append(inv_qft_gate(n + 1), qr_main)
global CMULTAMODN_
if CMULTAMODN_ == None or n <= 2:
if n < 3: CMULTAMODN_ = qc
return qc
# Creates circuit that implements single controlled Ua gate. n represents the number of bits
# needed to represent the integer number N
def controlled_Ua(n, a, exponent, N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n)
qr_ancilla = QuantumRegister(2)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main, qr_ancilla, name=f"C-U^{a}^{exponent}")
# Generate Gates
a_inv = modinv(a ** exponent, N)
cMULTamodN_gate = cMULTamodN(n, a ** exponent, N)
cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse()
# Create relevant temporary qubit list
qubits = [i for i in qr_ctl];
qubits.extend([i for i in qr_x]);
qubits.extend([i for i in qr_main])
qubits.extend([i for i in qr_ancilla])
qc.append(cMULTamodN_gate, qubits)
for i in range(n):
qc.cswap(qr_ctl, qr_x[i], qr_main[i])
qc.append(cMULTamodN_inv_gate, qubits)
global CUA_
if CUA_ == None or n <= 2:
if n < 3: CUA_ = qc
return qc
# Execute Shor's Order Finding Algorithm given a 'number' to factor,
# the 'base' of exponentiation, and the number of qubits required 'input_size'
def ShorsAlgorithm(number, base, method, verbose=verbose):
# Create count of qubits to use to represent the number to factor
# NOTE: this should match the number of bits required to represent (number)
n = int(math.ceil(math.log(number, 2)))
# this will hold the 2n measurement results
measurements = [0] * (2 * n)
# Standard Shors Algorithm
if method == 1:
num_qubits = 4 * n + 2
if verbose:
print(
f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}")
# Create a circuit and allocate necessary qubits
qr_up = QuantumRegister(2 * n) # Register for sequential QFT
qr_down = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication
cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT
qc = QuantumCircuit(qr_up, qr_down, qr_aux, cr_data, name="main")
# Initialize down register to 1 and up register to superposition state
qc.h(qr_up)
qc.x(qr_down[0])
qc.barrier()
# Apply Multiplication Gates for exponentiation
for i in range(2 * n):
cUa_gate = controlled_Ua(n, int(base), 2 ** i, number)
# Create relevant temporary qubit list
qubits = [qr_up[i]];
qubits.extend([i for i in qr_down]);
qubits.extend([i for i in qr_aux])
qc.append(cUa_gate, qubits)
qc.barrier()
i = 0
while i < ((qr_up.size - 1) / 2):
qc.swap(qr_up[i], qr_up[2 * n - 1 - i])
i = i + 1
qc.append(inv_qft_gate(2 * n), qr_up)
# Measure up register
qc.measure(qr_up, cr_data)
elif method == 2:
# Create a circuit and allocate necessary qubits
num_qubits = 2 * n + 3
if verbose:
print(f"... running Shors to factor number [ {number} ] with base={base} using num_qubits={n}")
qr_up = QuantumRegister(1) # Single qubit for sequential QFT
qr_down = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n + 2) # Register for addition and multiplication
cr_data = ClassicalRegister(2 * n) # Register for measured values of QFT
cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements
qc = QuantumCircuit(qr_down, qr_up, qr_aux, cr_data, cr_aux, name="main")
# Initialize down register to 1
qc.x(qr_down[0])
# perform modular exponentiation 2*n times
for k in range(2 * n):
# one iteration of 1-qubit QPE
# Reset the top qubit to 0 if the previous measurement was 1
qc.x(qr_up).c_if(cr_aux, 1)
qc.h(qr_up)
cUa_gate = controlled_Ua(n, base ** (2 ** (2 * n - 1 - k)), number)
qc.append(cUa_gate, [qr_up[0], qr_down, qr_aux])
# perform inverse QFT --> Rotations conditioned on previous outcomes
for i in range(2 ** k):
qc.u1(getAngle(i, k), qr_up[0]).c_if(cr_data, i)
qc.h(qr_up)
qc.measure(qr_up[0], cr_data[k])
qc.measure(qr_up[0], cr_aux[0])
global QC_, QFT_
if QC_ == None or n <= 2:
if n < 3: QC_ = qc
if QFT_ == None or n <= 2:
if n < 3: QFT_ = qft_gate(n + 1)
# turn the measured values into a number in [0,1) by summing their binary values
ma = [(measurements[2 * n - 1 - i]*1. / (1 << (i + 1))) for i in range(2 * n)]
y = sum(ma)
y = 0.833
# continued fraction expansion to get denominator (the period?)
r = Fraction(y).limit_denominator(number - 1).denominator
f = Fraction(y).limit_denominator(number - 1)
if verbose:
print(f" ... y = {y} fraction = {f.numerator} / {f.denominator} r = {f.denominator}")
# return the (potential) period
return r
# DEVNOTE: need to resolve this; currently not using the standard 'execute module'
# measure and flush are taken care of in other methods; do not add here
return qc
# Execute Shor's Factoring Algorithm given a 'number' to factor,
# the 'base' of exponentiation, and the number of qubits required 'input_size'
# Filter function, which defines the gate set for the first optimization
# (don't decompose QFTs and iQFTs to make cancellation easier)
'''
def high_level_gates(eng, cmd):
g = cmd.gate
if g == QFT or get_inverse(g) == QFT or g == Swap:
return True
if isinstance(g, BasicMathGate):
#return False
return True
print("***************** should never get here !")
if isinstance(g, AddConstant):
return True
elif isinstance(g, AddConstantModN):
return True
return False
return eng.next_engine.is_available(cmd)
'''
# Attempt to execute Shor's Algorithm to find factors, up to a max number of tries
# Returns number of failures, 0 if success
def attempt_factoring(input_size, number, verbose):
max_tries = 5
trials = 0
failures = 0
while trials < max_tries:
trials += 1
# choose a base at random
base = choose_random_base(number)
if base == 0: break
# execute the algorithm which determines the period given this base
r = ShorsAlgorithm(input_size, number, base, verbose=verbose)
# try to determine the factors from the period 'r'
f1, f2 = determine_factors(r, base, number)
# Success! if these are the factors and both are greater than 1
if (f1 * f2) == number and f1 > 1 and f2 > 1:
if verbose:
print(f" ==> Factors found :-) : {f1} * {f2} = {number}")
break
else:
failures += 1
if verbose:
print(f" ==> Bad luck: Found {f1} and {f2} which are not the factors")
print(f" ... trying again ...")
return failures
############### Circuit end
# Print analyzed results
# Analyze and print measured results
# Expected result is always the secret_int, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, marked_item, num_shots):
if verbose: print(f"For marked item {marked_item} measured: {result}")
key = format(marked_item, f"0{num_qubits}b")[::-1]
fidelity = result[key]
return fidelity
# Define custom result handler
def execution_handler(result, num_qubits, number, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
fidelity = analyze_and_print_result(result, num_qubits - 1, int(number), num_shots)
metrics.store_metric(num_qubits, number, 'fidelity', fidelity)
#################### Benchmark Loop
# Execute program with default parameters
def run(min_qubits=5, max_circuits=3, max_qubits=10, num_shots=100,
verbose=verbose, interactive=False,
backend_id='qasm_simulator', provider_backend=None,
hub="ibm-q", group="open", project="main"):
print("Shor's Factoring Algorithm Benchmark - Qiskit")
# Generate array of numbers to factor
numbers = generate_numbers()
min_qubits = max(min_qubits, 5) # need min of 5
max_qubits = max(max_qubits, min_qubits) # max must be >= min
max_qubits = min(max_qubits, len(numbers)) # max cannot exceed available numbers
# Initialize metrics module
metrics.init_metrics()
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
hub=hub, group=group, project=project)
if interactive:
do_interactive_test(verbose=verbose)
return;
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1):
input_size = num_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2 ** (input_size), max_circuits)
print(
f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}, input_size = {input_size}")
##print(f"... choices at {input_size} = {numbers[input_size]}")
# determine array of numbers to factor
numbers_to_factor = np.random.choice(numbers[input_size], num_circuits, False)
##print(f"... numbers = {numbers_to_factor}")
# Number of times the factoring attempts failed for each qubit size
failures = 0
# loop over all of the numbers to factor
for number in numbers_to_factor:
# convert from np form (created by np.random)
number = int(number)
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
# not currently used
# n_iterations = int(np.pi * np.sqrt(2 ** input_size) / 4)
# attempt to execute Shor's Algorithm to find factors
failures += attempt_factoring(input_size, number, verbose)
metrics.store_metric(num_qubits, number, 'create_time', time.time() - ts)
metrics.store_metric(num_qubits, number, 'exec_time', time.time() - ts)
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
# ex.submit_circuit(eng, qureg, num_qubits, number, num_shots)
# Report how many factoring failures occurred
if failures > 0:
print(f"*** Factoring attempts failed {failures} times!")
# execute all circuits for this group, aggregate and report metrics when complete
# ex.execute_circuits()
metrics.aggregate_metrics_for_group(num_qubits)
metrics.report_metrics_for_group(num_qubits)
# Alternatively, execute all circuits, aggregate and report metrics
# ex.execute_circuits()
# metrics.aggregate_metrics_for_group(num_qubits)
# metrics.report_metrics_for_group(num_qubits)
# print the last circuit created
# print(qc)
# Plot metrics for all circuit sizes
metrics.plot_metrics("Benchmark Results - Shor's Factoring Algorithm - Qiskit")
# For interactive_shors_factoring testing
def do_interactive_test(verbose):
done = False
while not done:
s = input('\nEnter the number to factor: ')
if len(s) < 1:
break
number = int(s)
print(f"Factoring number = {number}\n")
input_size = int(math.ceil(math.log(number, 2)))
# attempt to execute Shor's Algorithm to find factors
failures = attempt_factoring(input_size, number, verbose)
# Report how many factoring failures occurred
if failures > 0:
print(f"*** Factoring attempts failed {failures} times!")
print("... exiting")
# if main, execute method
if __name__ == '__main__': run() # max_qubits = 6, max_circuits = 5, num_shots=100)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
from src.clonk.backend_utils.topology_visualization import pretty_print
from src.clonk.backend_utils.mock_backends import FakeModular
pb = FakeModular(module_size=5, children=4, total_levels=2)
pretty_print(pb)
from qiskit.quantum_info.random import random_unitary
from qiskit import QuantumCircuit
from src.clonk.utils.riswap_gates.riswap import RiSwapGate
from src.clonk.utils.transpiler_passes.weyl_decompose import RootiSwapWeylDecomposition
from qiskit.transpiler.passes import CountOps
from qiskit.transpiler import PassManager
from tqdm import tqdm
N = 2000
basis_gate = RiSwapGate(0.5)
pm0 = PassManager()
pm0.append(RootiSwapWeylDecomposition(basis_gate=basis_gate))
pm0.append(CountOps())
res = 0
for _ in tqdm(range(N)):
qc = QuantumCircuit(2)
qc.append(random_unitary(dims=4), [0, 1])
pm0.run(qc)
res += pm0.property_set["count_ops"]["riswap"]
print("Haar score:", res / N)
from src.clonk.benchmark_suite.backend_suite_v3 import simple_backends_v3
print([backend.label for backend in simple_backends_v3])
from src.clonk.benchmark_suite.circuit_suite import circuits
q_size = 4
circuits["QAOA_Vanilla"].circuit_lambda(q_size).decompose().draw()
"""Example:"""
from src.clonk.benchmark_suite.main_plotting import benchmark, plot_wrap
for circuit_gen in circuits.values():
benchmark(
backends=simple_backends_v3,
circuit_generator=circuit_gen,
q_range=[4, 6, 8, 12, 14, 16],
continuously_save=1,
overwrite=0, # NOTE: turn this to 1 if you want to scrap the saved data and recollect a new batch
repeat=1,
)
# NOTE when plotting use motivation = 1 to plot SWAP counts, and motivation = 0 to plot gate durations
plot_wrap(simple_backends_v3, circuits.keys(), motivation=True, plot_average=True)
"""Fig 4"""
from src.clonk.benchmark_suite.backend_suite_v2 import motivation_backends
for circuit_gen in circuits.values():
benchmark(
backends=motivation_backends,
circuit_generator=circuit_gen,
q_range=motivation_backends[0].q_range,
continuously_save=True,
overwrite=False,
repeat=1,
)
plot_wrap(motivation_backends, circuits.keys(), motivation=True, plot_average=True)
"""Fig 10"""
from src.clonk.benchmark_suite.backend_suite_v2 import small_results_backends
for circuit_gen in circuits.values():
benchmark(
backends=small_results_backends,
circuit_generator=circuit_gen,
q_range=small_results_backends[0].q_range,
continuously_save=True,
overwrite=False,
repeat=1,
)
plot_wrap(small_results_backends, circuits.keys(), motivation=True, plot_average=True)
# """Fig 12"""
from src.clonk.benchmark_suite.backend_suite_v2 import results_backends
for circuit_gen in circuits.values():
benchmark(
backends=results_backends,
circuit_generator=circuit_gen,
q_range=results_backends[0].q_range,
continuously_save=True,
overwrite=False,
repeat=1,
)
plot_wrap(results_backends, circuits.keys(), motivation=True, plot_average=True)
"""Fig 13"""
from src.clonk.benchmark_suite.backend_suite_v2 import small_results_part2_backends
for circuit_gen in circuits.values():
benchmark(
backends=small_results_part2_backends,
circuit_generator=circuit_gen,
q_range=small_results_part2_backends[0].q_range,
continuously_save=True,
overwrite=False,
repeat=1,
)
plot_wrap(
small_results_part2_backends, circuits.keys(), motivation=False, plot_average=True
)
"""Fig 14"""
plot_wrap(results_backends, circuits.keys(), motivation=False, plot_average=True)
from src.clonk.benchmark_suite.backend_suite_v2 import small_results_part2_backendsv2
from qiskit.converters import circuit_to_dag
import numpy as np
ignore = ["u"]
for circuit_gen in circuits.values(): # [circuits['Quantum_Volume']]:
print(circuit_gen.label)
qc = circuit_gen.circuit_lambda(16)
for backend in small_results_part2_backendsv2:
print(backend.label)
c = backend.pass_manager.run(qc) # transpile :)
d = circuit_to_dag(c)
w = d.qubits # if use wires error bc returns classical bits
qubit_wire_counts = np.zeros(20)
for i, wi in enumerate(w):
for node in d.nodes_on_wire(wi, only_ops=True):
if node.name in ignore:
continue
# count the 2Q ops
if node.name in ["cx", "fSim", "riswap"]:
qubit_wire_counts[i] += 1
# print(qubit_wire_counts)
print(sum(qubit_wire_counts))
from src.clonk.benchmark_suite.nuop_script import create_plot2, collect_random2q_data
N = 20
base_fidelity_list = [0.97, 0.98, 1 - 10e-3, 1 - 5e-3, 1 - 10e-4, 1]
filename = f"src/clonk/benchmark_suite/data-archive2/data1_random.h5" # NOTE preloaded, change name of file to recollect
gate_error, decomp_error, fidelity_error = collect_random2q_data(
1 - 10e-3, N=N, mode="random", fn=filename
)
create_plot2(gate_error, decomp_error, fidelity_error, plot_bool=0, fn=filename);
create_plot2(gate_error, decomp_error, fidelity_error, plot_bool=1, fn=filename);
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import logging
import qiskit
from ddt import ddt, data as test_data, unpack
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit_aer.backends.aerbackend import AerBackend
import dc_qiskit_algorithms.DraperAdder
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger('test_DraperAdder')
@ddt
class DraperAdderTwoBitTest(unittest.TestCase):
@test_data(
(0, 0, None), (0, 1, None), (0, 2, None), (0, 3, None),
(1, 0, None), (1, 1, None), (1, 2, None), (1, 3, None),
(2, 0, None), (2, 1, None), (2, 2, None), (2, 3, None),
(3, 0, None), (3, 1, None), (3, 2, None), (3, 3, None),
(0, 0, 2), (0, 1, 2), (0, 2, 2), (0, 3, 2),
(1, 0, 2), (1, 1, 2), (1, 2, 2), (1, 3, 2),
(2, 0, 2), (2, 1, 2), (2, 2, 2), (2, 3, 2),
(3, 0, 2), (3, 1, 2), (3, 2, 2), (3, 3, 2),
(7, 0, None), (7, 1, None), (7, 2, None),
(7, 3, None), (7, 4, None), (7, 5, None),
(7, 6, None), (7, 7, None)
)
# @test_data((7, 1, None), (7, 2, None), (7, 3, None))
@unpack
def test_two_bit_adder(self, a, b, length):
log.info("Testing 'DraperAdder' with a=%d(%s), b=%d(%s).",
a, "{0:b}".format(a), b, "{0:b}".format(b))
length = dc_qiskit_algorithms.DraperAdderGate.compute_length(a, b, length)
qubit_a = QuantumRegister(length, "a")
qubit_b = QuantumRegister(length, "b")
readout_a = ClassicalRegister(length, "c_a")
readout_b = ClassicalRegister(length, "c_b")
qc = QuantumCircuit(qubit_a, qubit_b, readout_a, readout_b, name="draper adder")
qc.add_draper(a, b, list(qubit_a) + list(qubit_b), length)
qc.measure(qubit_a, readout_a)
qc.measure(qubit_b, readout_b)
backend = qiskit.Aer.get_backend('qasm_simulator') # type: AerBackend
job = qiskit.execute(qc, backend, shots=8192)
counts = job.result().get_counts()
result_list = [{'b': k[::-1].split(' ')[1], 'a': k[::-1].split(' ')[0], 'counts': v} for k, v in counts.items()]
log.info(result_list)
self.assertEqual(len(result_list), 1)
data = result_list[0] # type: dict
self.assertEqual(int(data['b'], 2), b, "Register b must be unchanged!")
self.assertEqual(int(data['a'], 2), (a + b) % 2**length, "Addition must be correctly performed!")
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/Alice-Bob-SW/emulation-examples
|
Alice-Bob-SW
|
import math
import random
import numpy as np
import qrisp
import qiskit
from qrisp.interface import VirtualQiskitBackend
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
provider = AliceBobLocalProvider()
backend = provider.get_backend("EMU:40Q:LOGICAL_TARGET")
vrtl_qasm_sim = VirtualQiskitBackend(backend)
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def find_period_classical(g, N):
# returns the period of g in Z_N
e = 1
while pow(g, e, N) != 1:
e = e + 1
return e
def classical_Shor(N):
# returns the factors of N by using Shor's algorithm
# with a classical brute-force period finding routine
if N % 2 == 0:
return (2, N // 2)
if is_prime(N):
return (1, N)
while True:
a = random.randint(2, N - 1)
if math.gcd(a, N) != 1:
return sorted([math.gcd(a, N), N // math.gcd(a, N)])
r = find_period_classical(a, N)
if r % 2 == 0:
x = pow(a, r // 2, N)
p = math.gcd(x - 1, N)
q = math.gcd(x + 1, N)
if p != 1 and p != N:
return sorted([p, N // p])
if q != 1 and q != N:
return sorted([q, N // q])
classical_Shor(15)
from sympy import continued_fraction_convergents, continued_fraction_iterator, Rational
def get_r_candidates(approx):
rationals = continued_fraction_convergents(
continued_fraction_iterator(Rational(approx))
)
return [rat.q for rat in rationals]
def get_phase_candidates(a, N):
qg = qrisp.QuantumModulus(N)
qg[:] = 1
qpe_res = qrisp.QuantumFloat(2 * qg.size + 1, exponent=-(2 * qg.size + 1))
qrisp.h(qpe_res)
x = a
for i in range(len(qpe_res)):
with qrisp.control(qpe_res[i]):
qg *= x
x = (x * x) % N
qrisp.QFT(qpe_res, inv=True)
qiskit_qc = qpe_res.qs.compile().to_qiskit()
# Compile the circuit to qiskit for technical limitations
# of the qrisp framework.
cr = qiskit.ClassicalRegister(len(qpe_res))
qiskit_qc.add_register(cr)
qiskit_qc.measure(range(len(qg), len(qpe_res) + len(qg)), range(len(cr)))
results = qiskit.execute(qiskit_qc, backend=backend, shots=5).result().get_counts()
return results
def binary_to_float(binaries):
# Convert binary string to floating-point decimal
results = []
for binary in binaries:
decimal = 0
for i, bit in enumerate(binary):
if bit == "1":
decimal += 2 ** -(i + 1)
results.append(decimal)
return results
def quantum_shor(a, N):
meas_res = get_phase_candidates(a, N)
r_candidates = sum(
[get_r_candidates(approx) for approx in binary_to_float(meas_res.keys())], []
)
for cand in sorted(set(r_candidates)):
if (a**cand) % N == 1:
r = cand
break
else:
raise Exception(
"Could not find the right candidate for the period. Please try resampling."
)
if r % 2:
raise Exception(
"Found an odd period for the given base. Please retry with another value of a."
)
p = np.gcd(a ** (r // 2) + 1, N)
q = int(N / p)
if p > q:
return (q, p)
return (p, q)
a = 2
N = 15
# WARNING: The code below takes approximatively 10 minutes to run
quantum_shor(a, N)
from qiskit_alice_bob_provider.processor.logical_cat import (
_logical_bit_flip_error,
_logical_phase_flip_error,
)
def logical_error_rate(distance, average_nb_photons, kappa_1, kappa_2):
# Returns the logical error rate for the given parameters.
return _logical_bit_flip_error(
d=distance, nbar=average_nb_photons
) + _logical_phase_flip_error(
d=distance, nbar=average_nb_photons, k1=kappa_1, k2=kappa_2
)
def error_rate_upper_bound(V, success_rate):
if success_rate <= 0 or success_rate > 1:
raise Exception("The success rate should be between 0 and 1")
return 1 - np.exp(np.log(success_rate) / V)
a = 2
N = 15
qg = qrisp.QuantumModulus(N)
qg[:] = 1
qpe_res = qrisp.QuantumFloat(2 * qg.size + 1, exponent=-(2 * qg.size + 1))
qrisp.h(qpe_res)
x = a
for i in range(len(qpe_res)):
with qrisp.control(qpe_res[i]):
qg *= x
x = (x * x) % N
qrisp.QFT(qpe_res, inv=True)
# Parameters of the `EMU:40Q:LOGICAL_TARGET` backend
distance = 15
n_qubits = 40
kappa_1 = 100
kappa_2 = 1e7
average_nb_photons = 19
qc_qiskit_TARGET = qpe_res.qs.compile().to_qiskit()
print("Circuit width before transpilation:", qc_qiskit_TARGET.width())
print("Circuit depth before transpilation:", qc_qiskit_TARGET.depth())
qc_qiskit_transpiled_TARGET = qiskit.transpile(qc_qiskit_TARGET, backend=backend)
print("Circuit width after transpilation:", qc_qiskit_transpiled_TARGET.width())
print("Circuit depth after transpilation:", qc_qiskit_transpiled_TARGET.depth())
q_volume_TARGET = qc_qiskit_transpiled_TARGET.depth() * (qc_qiskit_transpiled_TARGET.width()) #width * depth of the circuit
print('Quantum volume of the transpiled circuit:', q_volume_TARGET)
erub_TARGET = error_rate_upper_bound(q_volume_TARGET, 0.5)
print('Error rate upper bound:', f"{erub_TARGET:.3e}")
ler_TARGET = logical_error_rate(distance,average_nb_photons,kappa_1,kappa_2)
print('Backend logical error rate:', f"{ler_TARGET:.3e}")
backend = provider.get_backend("EMU:15Q:LOGICAL_EARLY")
# Parameters of the `EMU:15Q:LOGICAL_EARLY` backend
distance = 13
n_qubits = 15
kappa_1 = 100
kappa_2 = 100000
average_nb_photons = 7
qc_qiskit_EARLY = qpe_res.qs.compile().to_qiskit()
print("Circuit width before transpilation:", qc_qiskit_EARLY.width())
print("Circuit depth before transpilation:", qc_qiskit_EARLY.depth())
qc_qiskit_transpiled_EARLY = qiskit.transpile(qc_qiskit_EARLY, backend=backend)
print("Circuit width after transpilation:", qc_qiskit_transpiled_EARLY.width())
print("Circuit depth after transpilation:", qc_qiskit_transpiled_EARLY.depth())
q_volume_EARLY = qc_qiskit_transpiled_EARLY.depth() * (qc_qiskit_transpiled_EARLY.width()) #width * depth of the circuit
print('Quantum volume of the transpiled circuit:', q_volume_EARLY)
erub_EARLY = error_rate_upper_bound(q_volume_EARLY, 0.5)
print('Error rate upper bound:', f"{erub_EARLY:.3e}")
ler_EARLY = logical_error_rate(distance,average_nb_photons,kappa_1,kappa_2)
print('Backend logical error rate:', f"{ler_EARLY:.3e}")
# WARNING: The code below takes approximatively 30 minutes to run"
for _ in range(10):
print(quantum_shor(a,N))
import pandas as pd
data = [
[
qc_qiskit_transpiled_EARLY.width(),
qc_qiskit_transpiled_EARLY.depth(),
q_volume_EARLY,
f"{ler_EARLY:.3e}",
f"{erub_EARLY:.3e}",
],
[
qc_qiskit_transpiled_TARGET.width(),
qc_qiskit_transpiled_TARGET.depth(),
q_volume_TARGET,
f"{ler_TARGET:.3e}",
f"{erub_TARGET:.3e}",
],
]
pd.DataFrame(
data,
columns=["Width", "Depth", "Volume", "Logical Error Rate", "Upper bound"],
index=["EMU:40Q:LOGICAL_TARGET", "EMU:15Q:LOGICAL_EARLY"],
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the converter dag dependency to circuit and circuit to dag
dependency."""
import unittest
from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit
from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestCircuitToDagCanonical(QiskitTestCase):
"""Test QuantumCircuit to DAGDependency."""
def test_circuit_and_dag_canonical(self):
"""Check convert to dag dependency and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_dependency = circuit_to_dagdependency(circuit_in)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out, circuit_in)
def test_circuit_and_dag_canonical2(self):
"""Check convert to dag dependency and back
also when the option ``create_preds_and_succs`` is False."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_dependency = circuit_to_dagdependency(circuit_in, create_preds_and_succs=False)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out, circuit_in)
def test_calibrations(self):
"""Test that calibrations are properly copied over."""
circuit_in = QuantumCircuit(1)
circuit_in.add_calibration("h", [0], None)
self.assertEqual(len(circuit_in.calibrations), 1)
dag_dependency = circuit_to_dagdependency(circuit_in)
self.assertEqual(len(dag_dependency.calibrations), 1)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(len(circuit_out.calibrations), 1)
def test_metadata(self):
"""Test circuit metadata is preservered through conversion."""
meta_dict = {"experiment_id": "1234", "execution_number": 4}
qr = QuantumRegister(2)
circuit_in = QuantumCircuit(qr, metadata=meta_dict)
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.measure_all()
dag_dependency = circuit_to_dagdependency(circuit_in)
self.assertEqual(dag_dependency.metadata, meta_dict)
circuit_out = dagdependency_to_circuit(dag_dependency)
self.assertEqual(circuit_out.metadata, meta_dict)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/ColibrITD-SAS/mpqp
|
ColibrITD-SAS
|
from mpqp import QCircuit
from mpqp.gates import *
circuit = QCircuit([H(0), CNOT(0,1), Ry(2.6, 0), Ry(-0.87, 1)])
print(circuit)
from mpqp.measures import Observable, ExpectationMeasure
import numpy as np
from mpqp.tools.maths import is_hermitian
matrix = np.array([[4, 2, 3, 8],
[2, -3, 1, 0],
[3, 1, -1, 5],
[8, 0, 5, 2]])
is_hermitian(matrix)
obs = Observable(matrix)
circuit.add(ExpectationMeasure([0,1], observable=obs, shots=0))
from mpqp.execution import run, ATOSDevice, IBMDevice
result = run(circuit, ATOSDevice.MYQLM_PYLINALG)
print(result)
print(result.expectation_value)
circuit = circuit.without_measurements()
circuit.add(ExpectationMeasure([0,1], observable=obs, shots=2000))
results = run(circuit, [ATOSDevice.MYQLM_PYLINALG, IBMDevice.AER_SIMULATOR])
print(results)
from mpqp.measures import I, X, Y, Z
ps_1 = I@Z - 3 * X@Y
print(f"{ps_1=}")
ps_2 = I@Z + 2.555555555*Y@I + X@Z - X@Z
print("ps_2 =",repr(ps_2))
print(" =",repr(ps_2.simplify()))
print(" ~=",repr(ps_2.round(1)))
print(" ~=",ps_2)
ps_2 = ps_2.round(1).simplify()
print(f"""Addition:
({ps_1}) + ({ps_2}) = {ps_1 + ps_2}
Subtraction:
({ps_1}) - ({ps_2}) = {ps_1 - ps_2}
Scalar product:
2 * ({ps_1}) = {2 * ps_1}
Scalar division:
({ps_2}) / 3 ~= {ps_2 / 3}
Tensor product:
({ps_1}) @ Z = {ps_1@Z}
({ps_1}) @ ({ps_2}) = {ps_1@ps_2}""")
obs1 = Observable(ps_1)
print("`obs` created with matrix:")
print("matrix:")
print(obs.matrix)
print("Pauli string:")
print(obs.pauli_string)
print("\n\n`obs1` created with Pauli string:")
print("Pauli string:")
print(obs1.pauli_string)
print("matrix:")
print(obs1.matrix)
circuit = circuit.without_measurements()
circuit.add(ExpectationMeasure([0, 1], observable=obs1, shots=1000))
results = run(
circuit,
[
ATOSDevice.MYQLM_PYLINALG,
IBMDevice.AER_SIMULATOR,
ATOSDevice.MYQLM_CLINALG,
],
)
print(results)
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import math
from math import sqrt
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.circuit.random import random_circuit
from scipy.stats import chi2_contingency, ttest_ind, chisquare
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
pi = np.pi
def measure_z(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def flip_endian(dict):
newdict = {}
for key in list(dict):
newdict[key[::-1]] = dict.pop(key)
return newdict
def set_measure_x(circuit, n):
for num in range(n):
circuit.h(num)
def set_measure_y(circuit, n):
for num in range(n):
circuit.sdg(num)
circuit.h(num)
def qft_rotations(circuit, n):
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
set_measure_x(qc, 2)
qc.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
backend = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.x(0)
circ = qft_rotations(qc,2)#call the recursive qft method
print(circ)
#set it to measure the x axis
set_measure_x(qc, 2)
job = execute(qc, backend, shots=100000)#run the circuit 1000000 times
print(flip_endian(job.result().get_counts()))#return the result counts
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
q1=[]
q2=[]
qubitDict = dict.fromkeys(['qubit1','qubit2'])
qubitDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
print("new dict", qubitDict)
classicalQubitIndex = 1
for qubit in qubitDict.keys():
print("this qubit:",qubit)
for measurement in zMemory:
# print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
# print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
# print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
measDf12=measDf1.transpose()
print(measDf12)
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
# qc3.x(1)
qc3.x(0)
qc3.h(0)
qc3.cnot(0,1)
# qc3.rx(np.pi/2,qr[0])
qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
# print(qc3)
assertEntangled(backend,qc3,[0,1],2000,0.05)
# circuit = QuantumCircuit(2)
# circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
# assertEntangled(backend,circuit,[0,1],10,0.05)
def getDf(qc,qubits_to_assert,measurements_to_make,backend):
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 3
yQuantumCircuit = measure_y(qc.copy(), qubits_to_assert)
xQuantumCircuit = measure_x(qc.copy(), qubits_to_assert)
zQuantumCircuit = measure_z(qc, qubits_to_assert)
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
## get z axis results
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
return resDf
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf2 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf3 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf4 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
resDf5 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
q1Vals = []
q2Vals = []
q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i'], resDf2.at[0,'1'],resDf2.at[0,'-'],resDf2.at[0,'-i'], resDf3.at[0,'1'],resDf3.at[0,'-'],resDf3.at[0,'-i'], resDf4.at[0,'1'],resDf4.at[0,'-'],resDf4.at[0,'-i'], resDf5.at[0,'1'],resDf5.at[0,'-'],resDf5.at[0,'-i']])
print(q1Vals)
q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i'], resDf2.at[1,'1'],resDf2.at[1,'-'],resDf2.at[1,'-i'],resDf3.at[1,'1'],resDf3.at[1,'-'],resDf3.at[1,'-i'],resDf4.at[1,'1'],resDf4.at[1,'-'],resDf4.at[1,'-i'],resDf5.at[1,'1'],resDf5.at[1,'-'],resDf5.at[1,'-i'] ])
print(q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
# qc.cnot(0,1)
qc.x(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
# Complete needs to be checked
# Assertion to check if expected probability of viewing a particular qubitstate is to its actual probaility
# Qubitchoice is an optional argument that if passed will only compare the expected probabilty with the probability of observing
# that particular qubit (first or second) in the desired qubitState for the qc
def assertProbability(qc, qubitState :str, expectedProbability, qubitChoice=None):
sv = Statevector.from_label("00") # Creates a statevector with states 00
evl = sv.evolve(qc) # Passes the qc into the statevector in order to evolve
# Performs a check to observe if qubitChoice has been passed or not
if(qubitChoice!=None):
probs = evl.probabilities_dict([qubitChoice]) # If passed we will get the probabilities for that particular qubit
else:
probs = evl.probabilities_dict()
probsRound = {key: round(values,2) for key,values in probs.items()} # rounds off the probabilities in the dictionary
# Loops over the prob dictionary with rounded values
for key,value in probsRound.items():
if(key==qubitState):
if(value==expectedProbability):
print("Expected Probability present")
return True
else:
raise(AssertionError("Probability not present"))
raise(AssertionError("Probability not present or Desired state has no probability"))
qc = QuantumCircuit(2)
qc.h(0)
assertProbability(qc,"0",1,1)
print("------")
assertProbability(qc,"00",0.5)
circuit = QuantumCircuit(2)
circuit.initialize([1, 0], 0)
circuit.initialize(random_statevector(2).data, 1)
print("another",circuit.global_phase)
# print(circuit)
qasm_circuit = circuit.decompose().decompose().decompose()
print(type(qasm_circuit))
print("here",qasm_circuit._global_phase)
qc = QuantumCircuit(2)
initial_state = qc.initialize(random_statevector(2).data, 0)
initial_state1 = qc.initialize(random_statevector(2).data, 1)
# print(qc)
qasm_circuit1 = qc.decompose().decompose().decompose()
print(qasm_circuit1)
import random
def generateQC(theta_range,phi_range,lam_range):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [theta_range,phi_range,lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(theta_range[0],theta_range[1])
phi=random.randint(phi_range[0],phi_range[1])
lam=random.randint(lam_range[0],lam_range[1])
qc.u(theta,phi,lam,i)
return qc
# In Qsharp qubit initialisation was perfromed as such:
# { q : Qubit (36 ,72) (0 ,360) };
first = generateQC([36,72],[0,360],[0,360])
# QUBITS TO ASSERT PROBLEM HOW WILL I KNOW IF QUBIT IS 0 OR 1
print(first)
class property:
def __init__(self,backend,theta_range,phi_range,lam_range,which_assertion,measurements_to_make,alpha,experiments,noOfTests):
self.backend = backend
self.theta_range = theta_range
self.phi_range = phi_range
self.lam_range = lam_range
# self.predicate = predicate
self.which_assertion = which_assertion
self.measurements_to_make = measurements_to_make
self.alpha = alpha
self.experiments = experiments
self.noOfTests = noOfTests
def generateQC(self):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [self.theta_range,self.phi_range,self.lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(self.theta_range[0],self.theta_range[1])
phi=random.randint(self.phi_range[0],self.phi_range[1])
lam=random.randint(self.lam_range[0],self.lam_range[1])
qc.u(theta,phi,lam,i)
return qc
def run(self, qcToTest):
# assertEntangled(backend,qc3,[1,0],2000,0.05)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# qcToTest = generateQC(theta_range)
# if(which_assertion=assertEntangled)
return self.which_assertion(backend,qcToTest,[0,1], self.measurements_to_make,self.experiments,self.alpha)
# number_of_test_cases = 7
# number_of_measurements = 2000
# number_of_experiments = 20
# for tc in range(testcases):, testcases
# qc = new qc()
# for e in range(experiment):, experiments
# AssertEntangles(qc), measurements done here
def check(self):
for j in range(self.noOfTests):
qcToTest = generateQC(self.theta_range,self.phi_range,self.lam_range)
initial_state = qcToTest.copy()
# final_state =
# print(qcToTest)
# for i in range(self.experiments):
try:
self.run(qcToTest)
except AssertionError:
raise AssertionError("Property failed after run", self.noOfTests * j)
pbt = property(backend,[36,72],[0,360],[0,360],assertEntangled,2000,0.05,10,3)
pbt.check()
pbt2 = property(backend,[36,72],[0,360],[0,360],assertEqual,2000,0.05,10,3)
pbt2.check()
#pass created qubits into whichever function
#then pass that into assertions
class property:
def __init__(self,backend,theta_range,phi_range,lam_range,which_assertion,measurements_to_make,alpha,experiments,noOfTests):
self.backend = backend
self.theta_range = theta_range
self.phi_range = phi_range
self.lam_range = lam_range
# self.predicate = predicate
self.which_assertion = which_assertion
self.measurements_to_make = measurements_to_make
self.alpha = alpha
self.experiments = experiments
self.noOfTests = noOfTests
def generateQC(self):
# make sure theta phi and lamba are all in lists
# make sure they have size of 2
lists = [self.theta_range,self.phi_range,self.lam_range]
for i in lists:
if (not isinstance(i, list)):
i = [i]
if len(i)!=2:
raise ValueError("Range has to be two")
qc = QuantumCircuit(2)
for i in range(2):
theta=random.randint(self.theta_range[0],self.theta_range[1])
phi=random.randint(self.phi_range[0],self.phi_range[1])
lam=random.randint(self.lam_range[0],self.lam_range[1])
qc.u(theta,phi,lam,i)
return qc
def run(self, qcToTest):
# assertEntangled(backend,qc3,[1,0],2000,0.05)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# qcToTest = generateQC(theta_range)
# if(which_assertion=assertEntangled)
return self.which_assertion(backend,qcToTest,[0,0], self.measurements_to_make,self.experiments,self.alpha)
# number_of_test_cases = 7
# number_of_measurements = 2000
# number_of_experiments = 20
# for tc in range(testcases):, testcases
# qc = new qc()
# for e in range(experiment):, experiments
# AssertEntangles(qc), measurements done here
def check(self):
for j in range(self.noOfTests):
qcToTest = generateQC(self.theta_range,self.phi_range,self.lam_range)
# print(qcToTest)
# for i in range(self.experiments):
try:
self.run(qcToTest)
except AssertionError:
raise AssertionError("Property failed after run", self.noOfTests * j)
pbt = property(backend,[36,72],[0,360],[0,360],assertEntangled,2000,0.05,10,3)
pbt.check()
pbt2 = property(backend,[36,72],[0,360],[0,360],assertEqual,2000,0.05,10,3)
pbt2.check()
#pass created qubits into whichever function
#then pass that into assertions
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,experiments,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
q1=[]
q2=[]
for i in range (experiments):
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
qubitDict = dict.fromkeys(['qubit1','qubit2'])
qubitDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
# print("new dict", qubitDict)
classicalQubitIndex = 1
for qubit in qubitDict.keys():
# print("this qubit:",qubit)
for measurement in zMemory:
# print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
# print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
# print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
# print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
# print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
measDf12=measDf1.transpose()
print(measDf12)
# print(measDf12)
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
# qc3.x(1)
qc3.x(0)
qc3.h(0)
qc3.cnot(0,1)
# qc3.rx(np.pi/2,qr[0])
qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
# print(qc3)
qc4 = QuantumCircuit(2)
qc4.u(64,343,57,0)
qc4.u(65,43,226,1)
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.x(1)
circ = qft_rotations(qc1,2)
print(circ)
assertEntangled(backend,circ,[1,1],2000,1,0.05)
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, experiments, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
q1Vals = []
q2Vals = []
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
for i in range(experiments):
resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i']])
q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
print(q1Vals)
print(q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
# qc.cnot(0,1)
qc.x(1)
# qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
qc1 = QuantumCircuit(2)
# qc1.x(0)
qc1.h(0)
qc1.cnot(0,1)
# circ = qft_rotations(qc1,2)
assertEqual(backend, qc, [0,1], 300000, 10, 0.05)
# assertEntangled(backend,circ,[1,0],3000,10,0.05)
# Completed but more testing required
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, experiments, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
q1Vals = []
q2Vals = []
# Get Df is a function I made to return a dataframe containing measurements for each each qubit across all axes and I use 5 such different measurements for my dataset
for i in range(experiments):
# resDf1 = getDf(quantumCircuit,qubits_to_assert,measurements_to_make,backend)
# q1Vals.extend([resDf1.at[0,'1'],resDf1.at[0,'-'],resDf1.at[0,'-i']])
# q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
zQuantumCircuit = measure_z(quantumCircuit,qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
# zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
# print(i,zCounts)
# for k,v in zCounts.items():
# print(i,k,v)
# if(i==0):
# q1Vals.extend([v])
# else:
# q2Vals.extend([v])
resDf = pd.DataFrame(columns=['0','1'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount = 0,0
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
# print(i,"0:",zero_amount)
# print(i,"1:",one_amount)
df = {'0':zero_amount, '1':one_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
q1Vals.extend([resDf.at[0,'1']/measurements_to_make])
q2Vals.extend([resDf.at[1,'1']/measurements_to_make])
# print("here",q1Vals)
# print("here",q2Vals)
equalTest(q1Vals,q2Vals,alpha)
def equalTest(q1Vals,q2Vals,alpha):
# q1Vals.extend([resDf.at[0,'1'],resDf.at[0,'0']])
# q2Vals.extend([resDf1.at[1,'1'],resDf1.at[1,'-'],resDf1.at[1,'-i']])
# q2Vals.extend([resDf.at[1,'1'],resDf.at[1,'0']])
print("q1",q1Vals)
print("q2",q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2,2)
backend = Aer.get_backend('aer_simulator')
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
qc.h(0)
qc.x(1)
qc.h(1)
# qc.cnot(0,1)
# qc.x(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
# assertEqual(backend, qc, [0,1], 300000, 3, 0.05)
# assertEqual(backend, qc, [0,0], 300000, 0.05)
qc1 = QuantumCircuit(2)
# qc1.x(0)
qc1.x(0)
qc1.cnot(0,1)
# circ = qft_rotations(qc1,2)
assertEqual(backend, qc, [0,1], 300000, 30, 0.05)
# assertEntangled(backend,circ,[1,0],3000,10,0.05)
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import random
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, execute
from qiskit.circuit import ParameterVector
from qiskit.quantum_info import state_fidelity
from qiskit.quantum_info import Statevector, DensityMatrix, Operator
class Compressor:
def __init__(self, ensemble, block_size):
# Initialize parameters
self.ensemble = ensemble
self.n = block_size
self.m = block_size
self.theta = ParameterVector('theta', length=block_size)
self.phi = ParameterVector('phi', length=block_size)
# Initialize density matrix properties
self.rho = np.zeros((2, 2))
self.s0 = np.array([0, 0])
self.s1 = np.array([0, 0])
self.entropy = 1
self.initialize_density_matrix()
self.noise = ParameterVector('noise', length=self.m)
# Build subcircuits
self.ns_ckt = QuantumCircuit(self.n, name='$Noise$')
self.source = QuantumCircuit(self.n, name='$Src$')
self.tx_ckt = QuantumCircuit(self.n, name='$Tx$')
self.rx_ckt = QuantumCircuit(self.n, name='$Rx$')
self.initialize_subcircuits()
def initialize_density_matrix(self):
# Evaluate density matrix and list of states
for key in self.ensemble.keys():
theta = key[0]
phi = key[1]
state = np.array([np.cos(theta/2), np.sin(theta/2) * np.exp(phi*complex(1, 0))])
self.rho = self.rho + self.ensemble[key] * np.outer(state, state)
# Evaluate spectrum
self.rho: np.ndarray
v, w = np.linalg.eig(self.rho)
s0 = Statevector(w[:, 0])
s1 = Statevector(w[:, 1])
self.rho = DensityMatrix(self.rho)
# Evaluate entropy and typical basis
if state_fidelity(s0, self.rho) > state_fidelity(s1, self.rho):
self.s0 = s0
self.s1 = s1
else:
self.s0 = s1
self.s1 = s0
self.entropy = -np.real(sum([p * np.log2(p) for p in v]))
self.m = int(np.ceil(self.entropy * self.n))
def initialize_subcircuits(self):
# Build source
self.source.reset(range(self.n))
for i in range(self.n):
self.source.ry(self.theta[i], i)
self.source.rz(self.phi[i], i)
# Build typical basis change operator
U = Operator(np.column_stack((self.s0.data, self.s1.data))).adjoint()
for i in range(self.n):
self.tx_ckt.unitary(U, [i], label='$Basis$')
# Build permutation operator
data = list(range(2 ** self.n))
data = [("{0:0" + str(self.n) + "b}").format(i) for i in data]
data = sorted(data, key=lambda x: x.count('1'))
data = [int(x, 2) for x in data]
V = np.zeros((2 ** self.n, 2 ** self.n))
for i in range(2 ** self.n):
V[i, data[i]] = 1
self.tx_ckt.unitary(V, list(range(self.n)), label='$Perm$')
# Build bit flip noisy channel
for i in range(self.m):
self.ns_ckt.u3(self.noise[i], 0, self.noise[i], i)
# Build receiver
self.rx_ckt.reset(range(self.m, self.n))
self.rx_ckt.append(self.tx_ckt.to_gate().inverse(), list(range(self.n)))
def simulate(self, num_shots=1, bit_flip_prob=0.0):
# Get backend and circuit
simulator = Aer.get_backend('statevector_simulator')
circ = self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt
fid_list = []
for i in range(num_shots):
# Acquire parameters
states = random.choices(list(self.ensemble.keys()), self.ensemble.values(), k=self.n)
noise = random.choices([0, np.pi], [1-bit_flip_prob, bit_flip_prob], k=self.m)
theta = [p[0] for p in states]
phi = [p[1] for p in states]
circ1 = self.source.bind_parameters({self.theta: theta, self.phi: phi})
circ2 = circ.bind_parameters({self.theta: theta, self.phi: phi, self.noise: noise})
# Simulate
ini_state = execute(circ1, simulator).result().get_statevector()
fin_state = execute(circ2, simulator).result().get_statevector()
fid_list.append(state_fidelity(ini_state, fin_state))
# Return results
return fid_list
def visualize(self):
# Draw components
self.source.draw('mpl', reverse_bits=True).suptitle('Source Circuit')
self.tx_ckt.draw('mpl', reverse_bits=True).suptitle('Tx Circuit')
self.rx_ckt.draw('mpl', reverse_bits=True).suptitle('Rx Circuit')
(self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt).draw('mpl', reverse_bits=True).suptitle('Full Circuit')
plt.show()
if __name__ == '__main__':
ensemble = {(0, 0): 0.5, (np.pi/2, 0): 0.5}
com = Compressor(ensemble, 3)
com.visualize()
fid1 = com.simulate(num_shots=100)
fid2 = com.simulate(num_shots=100, bit_flip_prob=0.1)
print('Noiseless System Fidelity: ', np.mean(fid1))
print('Noisy (p = 0.1) System Fidelity: ', np.mean(fid2))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
#!pip install pennylane
#improt pennylane dependnecies
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
from sklearn.preprocessing import StandardScaler
# load the csv files
import pandas as pd
# plot the historical acc and cost
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
scale = StandardScaler()
scale.fit(X_train)
X_train = scale.transform(X_train)
X_test = scale.transform(X_test)
dev = qml.device("default.qubit", wires=4)
def layer_1(W):
qml.RY(W[0], wires=0)
qml.RY(W[1], wires=1)
qml.RY(W[2], wires=2)
qml.RY(W[3], wires=3)
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.Hadamard(wires=3)
qml.RZ(W[4], wires=0)
qml.RZ(W[5], wires=1)
qml.RZ(W[6], wires=2)
qml.RZ(W[7], wires=3)
qml.CNOT(wires=[1,0])
qml.RY(W[8], wires=1)
qml.CNOT(wires=[2,0])
qml.RY(W[9], wires=2)
qml.CNOT(wires=[3,0])
qml.RY(W[10], wires=3)
qml.CNOT(wires=[2,1])
qml.RY(W[11], wires=2)
qml.CNOT(wires=[3,1])
qml.RY(W[12], wires=3)
# qml.Hadamard(wires=0)
# qml.Hadamard(wires=1)
# qml.Hadamard(wires=2)
# qml.Hadamard(wires=3)
#qml.CNOT(wires=[1,0])
#qml.CNOT(wires=[2,0])
#qml.CNOT(wires=[3,0])
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_wires = 4
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MPS.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
def circuit(weights, x):
#statepreparation(x)
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
#for i in range(4):
#qml.Hadamard(wires=i)
#qml.RY(x[i], wires=i)
#qml.Hadamard(wires=i)
#qml.RX(x[i+4], wires=i)
#qml.RX(x[i+8], wires=i)
#qml.CNOT(wires=[0,1])
#qml.CNOT(wires=[1,2])
#qml.CNOT(wires=[2,3])
#qml.CNOT(wires=[3,0])
#qml.CNOT(wires=[4,0])
#qml.CNOT(wires=[0,1])
#qml.CNOT(wires=[1,2])
#qml.CNOT(wires=[2,3])
#qml.CNOT(wires=[3,0])
for w in weights:
#layer_1(w[:13])
#layer_2(w[12:21])
#layer_2(w[16:24])
#layer_3(w[21:])
qml.MPS(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(3))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 1
weights_init = 2*np.pi * np.random.randn(num_layers,3, 2, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3,4,5,6,7])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
if sum(x) == 0:
x[0]=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
y_test_pred = []
for i in y_pred:
if i < 0:
y_test_pred.append(-1)
else:
y_test_pred.append(1)
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'mps_1_layers_std.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
def find_secret_number(secter_number):
# Using Bernstein Vazirani Algorithm
secret_number = str(secter_number)
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
# circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
# print(counts)
return circuit, counts
secret_number = int(input("enter number: "))
circuit, number = find_secret_number(secret_number)
print('required number: ', number)
circuit.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
# Install packages
#!pip install numpy
#!pip install matplotlib
#!pip install qiskit
#!pip install qiskit[visualization]
#!pip install qiskit[optimization]
#!pip install qiskit_machine_learning
# Load packages
## General tools
import numpy as np
import matplotlib.pyplot as plt
from math import pi
## Qiskit Circuit Functions
from qiskit import *
from qiskit.quantum_info import *
from qiskit.visualization import *
# install the latest released version of PennyLane
!pip install pennylane
from pennylane import numpy as np
import matplotlib.pyplot as plt
from math import pi
import pennylane as qml
# Setup the device using qml.device()
## Assigning the device and defining the measurement of the circuit
dev = qml.device(name = 'default.qubit', wires = 2)
@qml.qnode(dev)
def circuit():
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer())
# Setup the device using qml.device()
## Assigning names to each wires
dev = qml.device(name = 'default.qubit', wires = ['a', 'b'])
@qml.qnode(dev)
def circuit(x):
return qml.expval(qml.PauliZ('a') @ qml.PauliZ('b'))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer(0.5))
# Setup the device using qml.device()
## Assigning the number of shots
shots_list = [5, 10, 1000] # number of shots for each batches
dev = qml.device("default.qubit", wires=2, shots=shots_list)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.expval(qml.PauliZ(0))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer(x = 0.5))
## The result of the execution of the circuit.
circuit(0.5)
dev = qml.device('default.qubit', wires=['aux', 'q1', 'q2'])
# Quntum function
def my_quantum_function(x, y):
qml.RZ(x, wires='q1')
qml.CNOT(wires=['aux' ,'q1'])
qml.RY(y, wires='q2')
return qml.expval(qml.PauliZ('q2'))
circuit = qml.QNode(my_quantum_function, dev)
circuit(x = np.pi/4, y = 0.7)
# Plot the circuit
print(qml.draw(circuit)(np.pi/4, 0.7))
# Plot the circuit with matplotlib.pyplot library
import matplotlib.pyplot as plt
fig, ax = qml.draw_mpl(circuit)(x = np.pi/4, y = 0.7)
plt.show()
# Measurement 1) Sampling result from each shots
dev = qml.device("default.qubit", wires=2, shots=1000)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1))
fig, ax = qml.draw_mpl(circuit)()
plt.show()
result_sample = circuit()
# Print out the dimension of the result
print(result_sample.shape)
# Let's look at the result
result_sample
# Measurement 2) Sampling result from each shots
dev = qml.device("default.qubit", wires=2, shots=1000)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.probs(wires=[0, 1])
fig, ax = qml.draw_mpl(circuit)()
plt.show()
result_prob = circuit()
# Print out the dimension of the result
print(result_prob.shape)
# Let's look at the result
result_prob
# Measurement 3) Sampling result from each shots
dev = qml.device("default.qubit", wires=3, shots=1000)
@qml.qnode(dev)
def my_quantum_function(x, y):
qml.RZ(x, wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(y, wires=1)
qml.CNOT(wires=[0, 2])
return qml.expval(qml.PauliZ(0) @ qml.Identity(1) @qml.PauliX(2))
fig, ax = qml.draw_mpl(my_quantum_function)(x = pi/2, y = pi/3)
plt.show()
result_tensor = my_quantum_function(x = pi/2, y = pi/3)
# Let's look at the result
result_tensor
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
dev = qml.device("default.qubit", wires=4)
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.Rot(W[2, 0], W[2, 1], W[2, 2], wires=2)
qml.Rot(W[3, 0], W[3, 1], W[3, 2], wires=3)
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
qml.CNOT(wires=[2, 3])
qml.CNOT(wires=[3, 0])
def statepreparation(x):
qml.BasisState(x, wires=[0, 1, 2, 3])
@qml.qnode(dev)
def circuit(weights, x):
statepreparation(x)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
from pennylane import numpy as np
data = np.array([[0., 0., 0., 0., 0],
[0., 0., 0., 1., 1],
[0., 0., 1., 0., 1],
[0., 0., 1., 1., 0],
[0., 1., 0., 0., 1],
[0., 1., 0., 1., 0],
[0., 1., 1., 0., 0],
[0., 1., 1., 1., 1],
[1., 0., 0., 0., 1],
[1., 0., 0., 1., 0],
[1., 0., 1., 0., 0],
[1., 0., 1., 1., 1],
[1., 1., 0., 0., 0],
[1., 1., 0., 1., 1],
[1., 1., 1., 0., 1],
[1., 1., 1., 1., 0]])
X = np.array(data[:, :-1], requires_grad=False)
Y = np.array(data[:, -1], requires_grad=False)
Y = Y * 2 - np.ones(len(Y)) # shift label from {0, 1} to {-1, 1}
for i in range(5):
print("X = {}, Y = {: d}".format(X[i], int(Y[i])))
print("...")
np.random.seed(0)
num_qubits = 4
num_layers = 2
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
opt = NesterovMomentumOptimizer(0.5)
batch_size = 5
weights = weights_init
bias = bias_init
iter_num = 10
for it in range(iter_num):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X), (batch_size,))
X_batch = X[batch_index]
Y_batch = Y[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, X_batch, Y_batch)
# Compute accuracy
predictions = [np.sign(variational_classifier(weights, bias, x)) for x in X]
acc = accuracy(Y, predictions)
print(
"Iter: {:5d} | Cost: {:0.7f} | Accuracy: {:0.7f} ".format(
it + 1, cost(weights, bias, X, Y), acc
)
)
dev = qml.device("default.qubit", wires=2)
def get_angles(x):
beta0 = 2 * np.arcsin(np.sqrt(x[1] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12))
beta1 = 2 * np.arcsin(np.sqrt(x[3] ** 2) / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12))
beta2 = 2 * np.arcsin(
np.sqrt(x[2] ** 2 + x[3] ** 2)
/ np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2)
)
return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2])
def statepreparation(a):
qml.RY(a[0], wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[2], wires=1)
qml.PauliX(wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[3], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[4], wires=1)
qml.PauliX(wires=0)
x = np.array([0.53896774, 0.79503606, 0.27826503, 0.0], requires_grad=False)
ang = get_angles(x)
@qml.qnode(dev)
def test(angles):
statepreparation(angles)
return qml.expval(qml.PauliZ(0))
test(ang)
print("x : ", x)
print("angles : ", ang)
print("amplitude vector: ", np.real(dev.state))
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(weights, angles):
statepreparation(angles)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, angles):
return circuit(weights, angles) + bias
def cost(weights, bias, features, labels):
predictions = [variational_classifier(weights, bias, f) for f in features]
return square_loss(labels, predictions)
# !pip install pandas
# !pip install sklearn
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
# visualization package
import matplotlib.pyplot as plt
import seaborn as sns
iris = load_iris() # sample data load
#print(iris) # pring out data with variable types and its description
print(iris.DESCR) # Description of the dataset
# feature_names(x variables) 와 target(y variable)을 잘 나타내도록 data frame 생성
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
# 숫자형으로 기록된 target(y variable) - (0.0, 1.0, 2.0)을 문자값으로 변환
df['target'] = df['target'].map({0:"setosa", 1:"versicolor", 2:"virginica"})
print(df)
sns.pairplot(df, hue="target", height=3)
plt.show()
from pennylane import numpy as np
data = np.loadtxt("iris_classes1and2_scaled.txt")
X = data[:, 0:2]
print("First X sample (original) :", X[0])
# pad the vectors to size 2^2 with constant values
padding = 0.3 * np.ones((len(X), 1))
X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))]
print("First X sample (padded) :", X_pad[0])
# normalize each input
normalization = np.sqrt(np.sum(X_pad ** 2, -1))
X_norm = (X_pad.T / normalization).T
print("First X sample (normalized):", X_norm[0])
# angles for state preparation are new features
features = np.array([get_angles(x) for x in X_norm], requires_grad=False)
print("First features sample :", features[0])
Y = data[:, -1]
import matplotlib.pyplot as plt
plt.figure()
plt.scatter(X[:, 0][Y == 1], X[:, 1][Y == 1], c="b", marker="o", edgecolors="k")
plt.scatter(X[:, 0][Y == -1], X[:, 1][Y == -1], c="r", marker="o", edgecolors="k")
plt.title("Original data")
plt.show()
plt.figure()
dim1 = 0
dim2 = 1
plt.scatter(
X_norm[:, dim1][Y == 1], X_norm[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
X_norm[:, dim1][Y == -1], X_norm[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Padded and normalised data (dims {} and {})".format(dim1, dim2))
plt.show()
plt.figure()
dim1 = 0
dim2 = 3
plt.scatter(
features[:, dim1][Y == 1], features[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
features[:, dim1][Y == -1], features[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Feature vectors (dims {} and {})".format(dim1, dim2))
plt.show()
np.random.seed(0)
num_data = len(Y)
num_train = int(0.75 * num_data)
index = np.random.permutation(range(num_data))
feats_train = features[index[:num_train]]
Y_train = Y[index[:num_train]]
feats_val = features[index[num_train:]]
Y_val = Y[index[num_train:]]
# We need these later for plotting
X_train = X[index[:num_train]]
X_val = X[index[num_train:]]
num_qubits = 2
num_layers = 6
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
opt = NesterovMomentumOptimizer(0.01)
batch_size = 50
# train the variational classifier
weights = weights_init
bias = bias_init
Iter_num = 25
for it in range(Iter_num):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, num_train, (batch_size,))
feats_train_batch = feats_train[batch_index]
Y_train_batch = Y_train[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in feats_train]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in feats_val]
# Compute accuracy on train and validation set
acc_train = accuracy(Y_train, predictions_train)
acc_val = accuracy(Y_val, predictions_val)
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost(weights, bias, features, Y), acc_train, acc_val)
)
plt.figure(figsize=(12,9))
cm = plt.cm.RdBu
# make data for decision regions
xx, yy = np.meshgrid(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20))
X_grid = [np.array([x, y]) for x, y in zip(xx.flatten(), yy.flatten())]
# preprocess grid points like data inputs above
padding = 0.3 * np.ones((len(X_grid), 1))
X_grid = np.c_[np.c_[X_grid, padding], np.zeros((len(X_grid), 1))] # pad each input
normalization = np.sqrt(np.sum(X_grid ** 2, -1))
X_grid = (X_grid.T / normalization).T # normalize each input
features_grid = np.array(
[get_angles(x) for x in X_grid]
) # angles for state preparation are new features
predictions_grid = [variational_classifier(weights, bias, f) for f in features_grid]
Z = np.reshape(predictions_grid, xx.shape)
# plot decision regions
cnt = plt.contourf(
xx, yy, Z, levels=np.arange(-1, 1.1, 0.1), cmap=cm, alpha=0.8, extend="both"
)
plt.contour(
xx, yy, Z, levels=[0.0], colors=("black",), linestyles=("--",), linewidths=(0.8,)
)
plt.colorbar(cnt, ticks=[-1, 0, 1])
# plot data
plt.scatter(
X_train[:, 0][Y_train == 1],
X_train[:, 1][Y_train == 1],
c="b",
marker="o",
edgecolors="k",
label="class 1 train",
)
plt.scatter(
X_val[:, 0][Y_val == 1],
X_val[:, 1][Y_val == 1],
c="b",
marker="^",
edgecolors="k",
label="class 1 validation",
)
plt.scatter(
X_train[:, 0][Y_train == -1],
X_train[:, 1][Y_train == -1],
c="r",
marker="o",
edgecolors="k",
label="class -1 train",
)
plt.scatter(
X_val[:, 0][Y_val == -1],
X_val[:, 1][Y_val == -1],
c="r",
marker="^",
edgecolors="k",
label="class -1 validation",
)
plt.legend()
plt.show()
# Install packages
# !pip install tensorflow
# Loading packages
import pennylane as qml
from pennylane import numpy as np
from pennylane.templates import RandomLayers
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
n_epochs = 30 # Number of optimization epochs
n_layers = 1 # Number of random layers
n_train = 50 # Size of the train dataset
n_test = 30 # Size of the test dataset
# SAVE_PATH = "quanvolution/" # Data saving folder. Here we don't need to make saving path.
PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH
np.random.seed(0) # Seed for NumPy random number generator
tf.random.set_seed(0) # Seed for TensorFlow random number generator
# Assigning MNIST data into train / test data
mnist_dataset = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_dataset.load_data()
# Reduce dataset size
## Previouslys, we set the number of train / test data in setting the hyper-parameters.
train_images = train_images[:n_train]
train_labels = train_labels[:n_train]
test_images = test_images[:n_test]
test_labels = test_labels[:n_test]
# Normalize pixel values within 0 and 1.
## We are modifying the data values between 0 and 1.
train_images = train_images / 255
test_images = test_images / 255
# Add extra dimension for convolution channels
train_images = np.array(train_images[..., tf.newaxis], requires_grad=False)
test_images = np.array(test_images[..., tf.newaxis], requires_grad=False)
# Setup the device using qml.device()
dev = qml.device("default.qubit", wires=4)
# Random circuit parameters using in rotation-Y gate
rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4))
@qml.qnode(dev)
def circuit(phi):
# Encoding of 4 classical input values
for j in range(4):
qml.RY(np.pi * phi[j], wires=j)
# Random quantum circuit
RandomLayers(rand_params, wires=list(range(4)))
# Measurement producing 4 classical output values
return [qml.expval(qml.PauliZ(j)) for j in range(4)]
## Assigning phi_value to plot the circuit
phi_value = [0,0,0,0]
## Plotting the quantum circuit
fig, ax = qml.draw_mpl(circuit)(phi_value)
plt.show()
def quanv(image):
"""Convolves the input image with many applications of the same quantum circuit."""
out = np.zeros((14, 14, 4))
# Loop over the coordinates of the top-left pixel of 2X2 squares
for j in range(0, 28, 2):
for k in range(0, 28, 2):
# Process a squared 2x2 region of the image with a quantum circuit
q_results = circuit(
[
image[j, k, 0],
image[j, k + 1, 0],
image[j + 1, k, 0],
image[j + 1, k + 1, 0]
]
)
# Assign expectation values to different channels of the output pixel (j/2, k/2)
for c in range(4):
out[j // 2, k // 2, c] = q_results[c]
return out
if PREPROCESS == True:
q_train_images = []
print("Quantum pre-processing of train images:")
for idx, img in enumerate(train_images):
print("{}/{} ".format(idx + 1, n_train), end="\r")
q_train_images.append(quanv(img))
q_train_images = np.asarray(q_train_images)
q_test_images = []
print("\nQuantum pre-processing of test images:")
for idx, img in enumerate(test_images):
print("{}/{} ".format(idx + 1, n_test), end="\r")
q_test_images.append(quanv(img))
q_test_images = np.asarray(q_test_images)
# # Save pre-processed images
# np.save(SAVE_PATH + "q_train_images.npy", q_train_images)
# np.save(SAVE_PATH + "q_test_images.npy", q_test_images)
# # Load pre-processed images
# q_train_images = np.load(SAVE_PATH + "q_train_images.npy")
# q_test_images = np.load(SAVE_PATH + "q_test_images.npy")
n_samples = 4
n_channels = 4
fig, axes = plt.subplots(1 + n_channels, n_samples, figsize=(10, 10))
for k in range(n_samples):
axes[0, 0].set_ylabel("Input")
if k != 0:
axes[0, k].yaxis.set_visible(False)
axes[0, k].imshow(train_images[k, :, :, 0], cmap="gray")
# Plot all output channels
for c in range(n_channels):
axes[c + 1, 0].set_ylabel("Output [ch. {}]".format(c))
if k != 0:
axes[c, k].yaxis.set_visible(False)
axes[c + 1, k].imshow(q_train_images[k, :, :, c], cmap="gray")
plt.tight_layout()
plt.show()
def MyModel():
"""Initializes and returns a custom Keras model
which is ready to be trained."""
model = keras.models.Sequential([
keras.layers.Flatten(),
keras.layers.Dense(10, activation="softmax")
])
model.compile(
optimizer='adam',
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
q_model = MyModel()
q_history = q_model.fit(
q_train_images,
train_labels,
validation_data=(q_test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,
)
c_model = MyModel()
c_history = c_model.fit(
train_images,
train_labels,
validation_data=(test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,
)
import matplotlib.pyplot as plt
plt.style.use("seaborn")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 9))
ax1.plot(q_history.history["val_accuracy"], "-ob", label="With quantum layer")
ax1.plot(c_history.history["val_accuracy"], "-og", label="Without quantum layer")
ax1.set_ylabel("Accuracy")
ax1.set_ylim([0, 1])
ax1.set_xlabel("Epoch")
ax1.legend()
ax2.plot(q_history.history["val_loss"], "-ob", label="With quantum layer")
ax2.plot(c_history.history["val_loss"], "-og", label="Without quantum layer")
ax2.set_ylabel("Loss")
ax2.set_ylim(top=2.5)
ax2.set_xlabel("Epoch")
ax2.legend()
plt.tight_layout()
plt.show()
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
import numpy as np
# import basic plot tools
from qiskit.visualization import plot_histogram
# length of the n-bit string
n = 4
constant_oracle = QuantumCircuit(n+1)
constant_oracle.clear()
output = np.random.randint(2) # random no. 0/1 as output
if output == 1:
constant_oracle.x(n)
balance_oracle = QuantumCircuit(n+1)
balance_oracle.clear()
b_str = "1000"
# implementing x-gates
for i in range(len(b_str)):
if b_str[i] == '1':
balance_oracle.x(i)
balance_oracle.barrier()
# implementing cnot gates
for qubit in range(n):
balance_oracle.cx(qubit, n)
balance_oracle.barrier()
balance_oracle.draw()
# implemneting x-gates
for i in range (len(b_str)):
if b_str[i] == '1':
balance_oracle.x(i)
balance_oracle.barrier()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(constant_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
dj_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(dj_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
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')
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend=simulator)
result = execute(circuit, backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
# plot_histogram
provider = IBMQ.get_provider('ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
job =execute(circuit, backend= backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
resolutions = [i for i in range(10, 55, 5)]
resolutions
from qiskit import IBMQ
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate, Initialize
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from time import sleep
import sys
sys.path.append("../..")
import os
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-education')
# santiago = provider.get_backend('ibmq_santiago')
# casablanca = provider.get_backend('ibmq_casablanca')
# bogota = provider.get_backend('ibmq_bogota')
sim = Aer.get_backend('qasm_simulator')
# athens = provider.get_backend('ibmq_athens')
from Modules.normal_SPEA import SPEA
from Modules.changed_SPEA import global_max_SPEA
def generate_plots(unitary_size, costs, errors, overlaps, algorithm):
import random
colors = ['red', 'brown', 'cyan', 'green',
'grey', 'blue', 'purple', 'black', 'orange']
c1, c2, c3 = random.sample(colors, 3)
# plot
os.makedirs("Experiment_1/"+str(unitary_size) +
"_qubit(random)/", exist_ok=True)
# plot 1
fig = plt.figure(figsize=(13, 6))
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title(str(unitary_size)+" qubit "+algorithm +
" Cost v/s Max iters", fontsize=16)
ax1.set_xlabel("Number of Resolutions ", fontsize=15)
ax1.set_ylabel("Metrics Returned for unitary ", fontsize=15)
ax1.plot(resolutions, costs, label='Costs of Unitary',
marker='o', color=c1, alpha=0.7)
ax1.plot(resolutions, overlaps, label='Average overlap from nearest eigenvector',
marker='s', color=c2, alpha=0.6)
ax1.legend(loc='best')
ax1.grid()
# plot 2
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_title(str(unitary_size)+" qubit "+algorithm +
" % error v/s Max iters", fontsize=16)
ax2.set_xlabel("Number of resolutions ", fontsize=15)
ax2.set_ylabel("% error for nearest eigenvalue", fontsize=15)
ax2.plot(resolutions, errors, label='Average error from nearest eigenvalue',
marker='o', color=c3, alpha=0.6)
ax2.legend(loc='best')
ax2.grid()
# save axure
fig.savefig("Experiment_1/"+str(unitary_size)+"_qubit(random)/" +
algorithm+" Algorithm (alternate).JPG", dpi=200)
def get_results(eig_vals, eig_vect, bases, basis_indices, unitary, algorithm, experiments):
'''Return the results of running the algorithm for this particular unitary matrix'''
costs_g = []
errors_g = []
max_overlaps_g = []
# find how the cost converges with increasing iterations
for reso in resolutions:
costs = []
errors = []
overlaps = []
i = 0
# run the experiments ...
while len(costs) < experiments:
if algorithm == 'original':
spea = SPEA(unitary, resolution=reso, error=3, max_iters=10)
else:
spea = global_max_SPEA(
unitary, resolution=reso, error=3, max_iters=10)
result = spea.get_eigen_pair(
progress=False, backend=sim, algo='alternate', basis=bases[i], basis_ind=basis_indices[i],
randomize=False,shots = 2**12)
# if result['cost'] < 0.65:
# continue
# increment the basis index
i+=1 # in exp 1 -> basis[0], in exp 2 -> basis[1] and so on....
# find the costs
costs.append(result['cost'])
theta = result['theta']
res_state = result['state']
# find the abs difference in this theta with the closest eigenvalue
# and append that to the errors ...
min_error = 1e5
for e in eig_vals:
error = abs(e - theta)
if error < min_error:
min_error = error
perc_error = ((error)/e)*100
errors.append(perc_error)
# find overlaps
max_overlap = -1
for k in eig_vect:
dot = np.linalg.norm(np.dot(k, res_state.conjugate().T))**2
max_overlap = max(max_overlap, dot)
overlaps.append(max_overlap)
print("Result with", reso, " resolutions :")
print("AVG. COST :", np.average(costs),
"AVG. ERROR :", np.average(errors))
# append the average result of your algorithm ...
costs_g.append(np.average(costs))
errors_g.append(np.average(errors))
max_overlaps_g.append(np.average(overlaps))
return costs_g, errors_g, max_overlaps_g
unit_2 = unitary_group.rvs(4)
unit_2
eig_vals2, eig_vect2 = np.linalg.eig(unit_2)
eig_vals2 = np.angle(eig_vals2)
e = []
for k in eig_vals2:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals2 = np.array(e)
print("Eigenstates :", eig_vect2)
print("Eigenvalues :", eig_vals2)
bases2 , basis_indices2 = [], []
for _ in range(4):
sample = unitary_group.rvs(4)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
ind = np.random.choice(range(4))
bases2.append(basis)
basis_indices2.append(ind)
print("Basis set :",bases2)
print("Basis indices :",basis_indices2)
costs_2qubit_b, errors_eig_2qubit_b, max_overlaps_2qubit_b = get_results(
eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'original', 4)
generate_plots(2, costs_2qubit_b, errors_eig_2qubit_b,
max_overlaps_2qubit_b, "Original")
costs_2qubit_c, errors_eig_2qubit_c, max_overlaps_2qubit_c = get_results(
eig_vals2, eig_vect2, bases2, basis_indices2, unit_2, 'modified', 4)
generate_plots(2, costs_2qubit_c, errors_eig_2qubit_c,
max_overlaps_2qubit_c, "Modified")
unit_3 = unitary_group.rvs(8)
unit_3
eig_vals3, eig_vect3 = np.linalg.eig(unit_3)
eig_vals3 = np.angle(eig_vals3)
e = []
for k in eig_vals3:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals3 = np.array(e)
print("Eigenstates :", eig_vect3)
print("Eigenvalues :", eig_vals3)
bases3 , basis_indices3 = [], []
for _ in range(4):
sample = unitary_group.rvs(8)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
ind = np.random.choice(range(8))
bases3.append(basis)
basis_indices3.append(ind)
print("Basis indices :",basis_indices3)
costs_3qubit_b, errors_eig_3qubit_b, max_overlaps_3qubit_b = get_results(
eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'original', 4)
generate_plots(3, costs_3qubit_b, errors_eig_3qubit_b,
max_overlaps_3qubit_b, "Original")
costs_3qubit_c, errors_eig_3qubit_c, max_overlaps_3qubit_c = get_results(
eig_vals3, eig_vect3, bases3, basis_indices3, unit_3, 'modified', 4)
generate_plots(3, costs_3qubit_c, errors_eig_3qubit_c,
max_overlaps_3qubit_c, "Modified")
unit_4 = unitary_group.rvs(16)
# unit_4
eig_vals4, eig_vect4 = np.linalg.eig(unit_4)
eig_vals4 = np.angle(eig_vals4)
e = []
for k in eig_vals4:
if k < 0:
v = (k + 2*np.pi)/(2*np.pi)
else:
v = (k)/(2*np.pi)
e.append(v)
eig_vals4 = np.array(e)
print("Eigenstates :", eig_vect4)
print("Eigenvalues :", eig_vals4)
bases4 , basis_indices4 = [], []
for _ in range(4):
sample = unitary_group.rvs(16)
basis = []
for k in sample:
basis.append(np.array(k, dtype=complex))
ind = np.random.choice(range(16))
bases4.append(basis)
basis_indices4.append(ind)
print("Basis indices :",basis_indices4)
costs_4qubit_b, errors_eig_4qubit_b, max_overlaps_4qubit_b = get_results(
eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'original', 4)
generate_plots(4, costs_4qubit_b,
errors_eig_4qubit_b, max_overlaps_4qubit_b, "Original")
costs_4qubit_c, errors_eig_4qubit_c, max_overlaps_4qubit_c = get_results(
eig_vals4, eig_vect4, bases4, basis_indices4, unit_4, 'modified', 4)
generate_plots(4, costs_4qubit_c,
errors_eig_4qubit_c,max_overlaps_4qubit_c, "Modified")
|
https://github.com/mrvee-qC-bee/SCQC23
|
mrvee-qC-bee
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.quantum_info import Statevector
from qiskit_aer import AerSimulator
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# with Session(backend=service.backend("ibmq_qasm_simulator")):
# result = Sampler().run(circuits).result()
import math #may be helpful
coords = [] # Put your code here in this format: [radius, theta, phi]
plot_bloch_vector(coords, coord_type='spherical')
qc = QuantumCircuit(1)
# Add your code here
sv = Statevector(qc)
plot_bloch_multivector(sv)
# You will already have defined 'qc' in the code cell above. Use that circuit for this exercise.
backend = # Choose your backend - this should be the Aer Simulator!
job = # Run your circuit through a job
result = # Get the result from the job
counts = # Get the counts dictionary from the result
plot_histogram(counts)
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
import sys
import os
current_dir = os.getcwd()
sys.path.append(current_dir)
from quantum_circuit import QuantumCircuit
# import qiskit.providers.fake_provider
from qiskit.transpiler import CouplingMap
import qiskit_ibm_runtime.fake_provider
from Backend.backend import Backend
class FakeBackend(Backend):
def __init__(self, backend_name : str) -> None:
self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name)
@staticmethod
def get_ibm_fake_backend_name_list() -> list[str]:
ibm_dir = dir(qiskit_ibm_runtime.fake_provider)
return [val for val in ibm_dir if '__' not in val and 'Fake' in val]
@staticmethod
def get_ibm_fake_backend(backend_name : str):
try:
return getattr(qiskit_ibm_runtime.fake_provider, backend_name)()
except: pass
fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list()
for backend in fake_backend_name:
backend = FakeBackend.get_ibm_fake_backend(backend)
if backend is not None:
try:
if backend.name == backend_name:
return backend
except: pass
return None
@staticmethod
def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]:
limited_backend = []
fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list()
for backend in fake_backend_name:
backend = FakeBackend.get_ibm_fake_backend(backend)
if backend is not None:
try:
num_qubit = backend.num_qubits
if num_qubit >= min_qubit and num_qubit <= max_qubit:
limited_backend.append(backend.name)
except: pass
return limited_backend
if __name__ == "__main__":
print(FakeBackend.get_ibm_fake_backend_name_list())
backend = FakeBackend('fake_auckland')
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
qc.measure_all()
print(qc.draw())
job = backend.run(qc)
print(job.result())
qc_transpile = backend.traspile_qiskit(qc)[0]
print(qc_transpile.draw())
job = backend.run(qc_transpile)
print(job.result())
|
https://github.com/pbark/qiskit_tutorials
|
pbark
|
# import common packages
import numpy as np
import matplotlib.pyplot as plt
from qiskit import Aer, IBMQ, QuantumRegister
from qiskit.providers.ibmq import least_busy
from qiskit.providers.aer import noise
# lib from Qiskit Aqua
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import QiskitChemistry
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
# setup qiskit.chemistry logging
import logging
from qiskit.chemistry import set_qiskit_chemistry_logging
# function that allows us to create multiple figures in single notebook cell
def show_figure(fig):
dummy_fig = plt.figure()
new_dummy_fig_manager = dummy_fig.canvas.manager
new_dummy_fig_manager.canvas.figure = fig
fig.set_canvas(new_dummy_fig_manager.canvas)
set_qiskit_chemistry_logging(logging.INFO) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
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))
print("Contents of molecule object: \n{}".format(sorted(molecule.__dir__())))
# get the integrals from molecule object
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
# create a fermionic operator
ferOp = FermionicOperator(h1=h1, h2=h2)
map_type = 'parity' # 'jordan_wigner', 'parity', 'bravyi_kitaev', 'bksf'
# if 'parity' mapping is selected, reduce the number of qubits (-2 qubits)
qubit_reduction = True if map_type == 'parity' else False
qubitOp = ferOp.mapping(map_type=map_type, threshold=10**-10) # paulis with coefs below threshold are not considered
qubitOp = qubitOp.two_qubit_reduced_operator(num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10) # cut out the pauli strings with prefacator smaller then
print(qubitOp)
qubitOp.paulis
# to see all the contents of given class
# qubitOp.__dir__()
# one can group the Paulis
# qubitOp.to_grouped_paulis()
# qubitOp.paulis
for pauli in qubitOp.paulis:
print(pauli[0],str(pauli[1]))
max_iter = 200 # maximum number of iterations
# optimizer = COBYLA(maxiter=max_iter)
# optimizer = SPSA(maxiter=max_iter)
optimizer = L_BFGS_B(maxiter=max_iter)
HF_state = HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type,
qubit_reduction)
HF_state_vec = HF_state.construct_circuit(mode='vector')
# we can use qiskit's vizualisation module to plot the state
from qiskit.visualization import plot_state_city
plot_state_city(HF_state_vec)
# you might want to visualise on the Bloch sphere for a non-superposition state
from qiskit.visualization import plot_state_city, plot_bloch_multivector
plot_bloch_multivector(HF_state_vec)
var_form_uccsd = UCCSD(qubitOp.num_qubits, depth=1,
num_orbitals=num_spin_orbitals, num_particles=num_particles,
active_occupied=None, active_unoccupied=None, # you could modify the active space here
initial_state=HF_state, qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction, num_time_slices=1)
var_form_swaprz = SwapRZ(qubitOp.num_qubits, depth=1,
initial_state=HF_state)
var_form_ryrz = RYRZ(qubitOp.num_qubits, depth=1,
initial_state=HF_state)
# var_form_ry = RY(qubitOp.num_qubits, depth=1,
# initial_state=HF_state)
simultation_type = 'state_vector'# qasm, qasm_cloud, real_device, state_vector
if simultation_type == 'qasm':
sv_mode = False
qasm_simulator = Aer.get_backend('qasm_simulator') # qasm_simulator, ibmq_qasm_simulator
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
# set the noise model
device = provider.get_backend('ibmq_16_melbourne') # ibmq_16_melbourne
properties = device.properties()
coupling_map = device.configuration().coupling_map
noise_model = noise.device.basic_device_noise_model(properties)
basis_gates = noise_model.basis_gates
shots = 8192 # choose the maximal number of shots (8192 is max on the ibmq_qasm_simulator)
num_qubits = qubitOp.num_qubits
# run on qasm_simulator
quantum_instance = QuantumInstance(qasm_simulator, shots=shots, basis_gates=basis_gates, coupling_map=coupling_map, noise_model=noise_model)
# all the details of noise model
print(noise_model.to_dict())
elif simultation_type == 'qasm_cloud':
sv_mode = False
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
qasm_simulator_cloud = provider.get_backend('ibmq_qasm_simulator') # ibmq_16_melbourne , ibmq_qasm_simulator
# set the qasm cloud simulator
shots = 8192
quantum_instance = QuantumInstance(qasm_simulator_cloud, shots=shots)
elif simultation_type == 'real_device':
sv_mode = False
# uncomment this and put your token from the IBMQ website.
#IBMQ.save_account('Your IBMQ API-token', overwrite=True)
IBMQ.load_accounts() # connect with your token to IBMQ
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
print(provider.backends()) # lists available backends
# set the noise model
device = provider.get_backend('ibmq_16_melbourne') # ibmq_16_melbourne
# run on qasm_simulator
shots = 8192
quantum_instance = QuantumInstance(device, shots=shots)
elif simultation_type == 'state_vector':
sv_mode = True
num_qubits = qubitOp.num_qubits
sv_simulator = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(sv_simulator)
else:
raise Exception('Please select for simultation_type == qasm, qasm_cloud, real_device, state_vector')
vqe_uccsd = VQE(qubitOp, var_form_uccsd, optimizer)
vqe_ryrz = VQE(qubitOp, var_form_ryrz, optimizer)
vqe_swaprz = VQE(qubitOp, var_form_swaprz, optimizer)
for pauli in qubitOp.paulis:
print('Circuit for:', pauli[1])
circuit_uccsd = vqe_uccsd.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_uccsd._num_parameters))
for i in range(len(circuit_uccsd)):
fig = circuit_uccsd[i].draw(output='mpl')
show_figure(fig)
fig.show()
circuit_swaprz = vqe_swaprz.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_swaprz._num_parameters))
circuit_swaprz[1].draw(output='mpl')
circuit_ryrz = vqe_ryrz.construct_circuit(statevector_mode=sv_mode, parameter=np.ones(var_form_ryrz._num_parameters))
circuit_ryrz[1].draw(output='mpl')
results = vqe_uccsd.run(quantum_instance)
print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0]))
print('The total ground state energy is: {:.12f}'.format(results['eigvals'][0] + nuclear_repulsion_energy))
print("Parameters: {}".format(results['opt_params']))
evolution_time = 100 # how many time steps
num_time_slices = 4 # number of Trotter steps
qr = QuantumRegister(num_qubits,'q')
initial_circuit = HF_state.construct_circuit(mode='circuit')
evolution_circuit = qubitOp.evolve(state_in=initial_circuit, evo_time=evolution_time, evo_mode='circuit',num_time_slices=num_time_slices, expansion_mode='trotter')
evolution_circuit.draw(output='mpl')
max_time=evolution_time
statevector_of_t = np.zeros([max_time,2*num_qubits])
for evo_t in range(max_time):
evolution_circuit = qubitOp.evolve(state_in=initial_circuit, evo_time=evo_t, evo_mode='circuit',num_time_slices=num_time_slices, expansion_mode='trotter')
result = quantum_instance.execute(evolution_circuit)
statevector_of_t[evo_t,:] = np.asarray(result.get_statevector(evolution_circuit))
time_min = 0
time_max = 4
for i in range(time_min, time_max):
fig = plot_state_city(statevector_of_t[i,:])
show_figure(fig)
fig.show()
# First, we use classical eigendecomposition to get ground state energy (including nuclear repulsion energy) as reference.
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': 'H2/H2_equilibrium_0.735_sto-3g.hdf5'},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
solver = QiskitChemistry()
result_classical = solver.run(qiskit_chemistry_dict)
# Second, we use variational quantum eigensolver (VQE)
qiskit_chemistry_dict['algorithm']['name'] = 'VQE'
qiskit_chemistry_dict['optimizer'] = {'name': 'SPSA', 'max_trials': 350}
qiskit_chemistry_dict['variational_form'] = {'name': 'RYRZ', 'depth': 3, 'entanglement':'full'}
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict, backend=backend)
# We print out the results
print('Ground state energy (classical): {:.12f}'.format(result_classical['energy']))
print('Ground state energy (quantum) : {:.12f}'.format(result['energy']))
print("====================================================")
# You can also print out other info in the field 'printable'
for line in result['printable']:
print(line)
molecule='H2'
maxiter = 10 # increase to allow optimizer to converge, set low to test
mol_distances = np.arange(0.2, 3.1, 0.2)
mol_distances_vqe = np.arange(0.2, 3.1,1)
# Exact eigensolver
qiskit_chemistry_dict_ee = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'ExactEigensolver'}
}
# choose which backend want to use
# backend = Aer.get_backend('qasm_simulator')
backend = Aer.get_backend('statevector_simulator')
# VQE
qiskit_chemistry_dict_vqe = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': ''},
'operator': {'name':'hamiltonian',
'qubit_mapping': 'parity',
'two_qubit_reduction': True},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'L_BFGS_B', 'maxiter': maxiter}, # or SPSA, max_trials=200
'variational_form': {'name': 'RY', 'depth': 1, 'entanglement':'full'}, # RYRZ, UCCSD (delete entanglement field)
'backend': {'shots': 1024}
}
algos = ['ExactEigensolver', 'VQE']
energy = np.zeros((len(algos), len(mol_distances)))
energy_vqe = np.zeros((len(algos), len(mol_distances_vqe)))
# Run the algos
for j, algo in enumerate([qiskit_chemistry_dict_ee, qiskit_chemistry_dict_vqe]):
algo_name = algo['algorithm']['name']
print("Using {}".format(algo_name))
if algo_name == 'VQE':
for i, dis in enumerate(mol_distances_vqe):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
algo['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(algo, backend=backend if algo_name == 'VQE' else None)
energy_vqe[j][i] = result['energy']
else:
for i, dis in enumerate(mol_distances):
print("Processing atomic distance: {:1.1f} Angstrom".format(dis), end='\r')
algo['HDF5']['hdf5_input'] = "{}/{:1.1f}_sto-3g.hdf5".format(molecule, dis)
result = solver.run(algo, backend=backend if algo_name == 'VQE' else None)
energy[j][i] = result['energy']
for i, algo in enumerate(algos):
if algo == 'VQE':
plt.plot(mol_distances_vqe, energy_vqe[i], label=algo, linestyle='', marker='x')
else:
plt.plot(mol_distances, energy[i], label=algo)
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy [Ha]')
plt.legend()
plt.show()
mol_distances_errors = []
energy_errors = []
for i, pts_vqe in enumerate(mol_distances_vqe):
for j, pts in enumerate(mol_distances):
# find the entries with same bond distances
if pts_vqe == pts:
mol_distances_errors.append(pts)
energy_errors.append(abs(energy[0][j]-energy_vqe[1][i]))
# plot the errors
print('Errors |Exact - VQE|:\n',energy_errors)
plt.plot(mol_distances_errors, energy_errors, label='Errors(Exact-VQE)', linestyle='', marker='x')
# chemical accuracy of 1 mHa
plt.hlines(0.001, 0, 3, colors='k', label='Chemical Accuracy')
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
""" This file allows to test the various QFT implemented. The user must specify:
1) The number of qubits it wants the QFT to be implemented on
2) The kind of QFT want to implement, among the options:
-> Normal QFT with SWAP gates at the end
-> Normal QFT without SWAP gates at the end
-> Inverse QFT with SWAP gates at the end
-> Inverse QFT without SWAP gates at the end
The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state
This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves
the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient
qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ, BasicAer
""" Imports to Python functions """
import time
""" Local Imports """
from qfunctions import create_QFT, create_inverse_QFT
""" Function to properly print the final state of the simulation """
""" This is only possible in this way because the program uses the statevector_simulator """
def show_good_coef(results, n):
i=0
max = pow(2,n)
if max > 100: max = 100
""" Iterate to all possible states """
while i<max:
binary = bin(i)[2:].zfill(n)
number = results.item(i)
number = round(number.real, 3) + round(number.imag, 3) * 1j
""" Print the respective component of the state if it has a non-zero coefficient """
if number!=0:
print('|{}>'.format(binary),number)
i=i+1
""" Main program """
if __name__ == '__main__':
""" Select how many qubits want to apply the QFT on """
n = int(input('\nPlease select how many qubits want to apply the QFT on: '))
""" Select the kind of QFT to apply using the variable what_to_test:
what_to_test = 0: Apply normal QFT with the SWAP gates at the end
what_to_test = 1: Apply normal QFT without the SWAP gates at the end
what_to_test = 2: Apply inverse QFT with the SWAP gates at the end
what_to_test = 3: Apply inverse QFT without the SWAP gates at the end
"""
print('\nSelect the kind of QFT to apply:')
print('Select 0 to apply normal QFT with the SWAP gates at the end')
print('Select 1 to apply normal QFT without the SWAP gates at the end')
print('Select 2 to apply inverse QFT with the SWAP gates at the end')
print('Select 3 to apply inverse QFT without the SWAP gates at the end\n')
what_to_test = int(input('Select your option: '))
if what_to_test<0 or what_to_test>3:
print('Please select one of the options')
exit()
print('\nTotal number of qubits used: {0}\n'.format(n))
print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n')
ts = time.time()
""" Create quantum and classical registers """
quantum_reg = QuantumRegister(n)
classic_reg = ClassicalRegister(n)
""" Create Quantum Circuit """
circuit = QuantumCircuit(quantum_reg, classic_reg)
""" Create the input state desired
Please change this as you like, by default we put H gates in every qubit,
initializing with a maximimal superposition state
"""
#circuit.h(quantum_reg)
""" Test the right QFT according to the variable specified before"""
if what_to_test == 0:
create_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 1:
create_QFT(circuit,quantum_reg,n,0)
elif what_to_test == 2:
create_inverse_QFT(circuit,quantum_reg,n,1)
elif what_to_test == 3:
create_inverse_QFT(circuit,quantum_reg,n,0)
else:
print('Noting to implement, exiting program')
exit()
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1)
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
""" Get the statevector of the final quantum state """
outputstate = sim_result.get_statevector(circuit, decimals=3)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print final quantum state to user """
print('The final state after applying the QFT is:\n')
show_good_coef(outputstate,n)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# let's print all numbers between 0 and 9
for i in range(10): print(i)
# range(n) represents the list of all numbers from 0 to n-1
# i is the variable to take the values in the range(n) iteratively: 0, 1, ..., 9 in our example
# let's write the same code in two lines
for i in range(10): # do not forget to use colon
print(i)
# the second line is indented
# this means that the command in the second line will be executed inside the for-loop
# any other code executed inside the for-loop must be intented in the same way
#my_code_inside_for-loop_2 will come here
#my_code_inside_for-loop_3 will come here
#my_code_inside_for-loop_4 will come here
# now I am out of the scope of for-loop
#my_code_outside_for-loop_1 will come here
#my_code_outside_for-loop_2 will come here
# let's calculate the summation 1+2+...+10 by using a for-loop
# we use variable total for the total summation
total = 0
for i in range(11): # do not forget to use colon
total = total + i # total is increased by i in each iteration
# alternatively, the same assignment can shortly be written as total += i similarly to languages C, C++, Java, etc.
# now I am out of the scope of for-loop
# let's print the latest value of total
print(total)
# let's calculate the summation 10+12+14+...+44
# we create a list having all numbers in the summation
# for this purpose, this time we will use three parameters in range
total = 0
for j in range(10,45,2): # the range is defined between 10 and 44, and the value of j will be increased by 2 after each iteration
total += j # let's use the shortened version of total = total + j
print(total)
# let's calculate the summation 1+2+4+8+16+...+256
# remark that 256 = 2*2*...*2 (8 times)
total = 0
current_number = 1 # this value will be multiplied by 2 after each iteration
for k in range(9):
total = total + current_number # current_number is 1 at the beginning, and its value will be doubled after each iteration
current_number = 2 * current_number # let's double the value of the current_number for the next iteration
# short version of the same assignment: current_number *= 2 as in the languages C, C++, Java, etc.
# now I am out of the scope of for-loop
# let's print the latest value of total
print(total)
# instead of a range, we can directly use a list
for i in [1,10,100,1000,10000]:
print(i)
# instead of [...], we can also use (...)
# but this time it is a tuple, not a list (keep in your mind that the values in a tuple cannot be changed)
for i in (1,10,100,1000,10000):
print(i)
# let's create a range between 10 and 91 that contains the multiples of 7
for j in range(14,92,7):
# 14 is the first multiple of 7 greater than or equal to 10
# 91 should be in the range, and so we write 92
print(j)
# let's create a range between 11 and 22
for i in range(11,23):
print(i)
# we can also use variables in range
n = 5
for j in range(n,2*n):
print(j) # we will print all numbers in {n,n+1,n+2,...,2n-1}
# we can use a list of strings
for name in ("Asja","Balvis","Fyodor"):
print("Hello",name,":-)")
# any range can be converted to a list
L1 = list(range(10))
print(L1)
L2 = list(range(55,200,11))
print(L2)
#
# your solution is here
#
#
# your solution is here
#
# let's calculate the summation 1+2+4+8+...+256 by using a while-loop
total = 0
i = 1
#while condition(s):
# your_code1
# your_code2
# your_code3
while i < 257: # this loop iterates as long as i is less than 257
total = total + i
i = i * 2 # i is doubled in each iteration, and so soon it will be greater than 256
print(total)
# remember that we calculated this summation as 511 before
L = [0,1,2,3,4,5,11] # this is a list containing 7 integer values
i = 0
while i in L: # this loop will be iterated as long as i is in L
print(i)
i = i + 1 # the value of i iteratively increased, and so soon it will hit a value not in the list L
# the loop is terminated after i is set to 6, because 6 is not in L
# let's use negation in the condition of while-loop
L = [10] # this list has a single element
i = 0
while i not in L: # this loop will be iterated as long as i is not equal to 10
print(i)
i = i+1 # the value of i will hit 10 after ten iterations
# let's rewrite the same loop by using a direct inequality
i = 0
while i != 10: # "!=" is used for "not equal to" operator
print(i)
i=i+1
# let's rewrite the same loop by using negation of equality
i = 0
while not (i == 10): # "==" is used for "equal to" operator
print(i)
i=i+1
# while-loop seems having more fun :-)
# but we should be more careful when writing the condition(s)!
# summation and n is zero at the beginning
S = 0
n = 0
while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000)
n = n +1
S = S + n
# let's print n and S
print("n =",n," S =",S)
# three examples for the operator "less than or equal to"
#print (4 <= 5)
#print (5 <= 5)
#print (6 <= 5)
# you may comment out the above three lines and see the results by running this cell
#
# your solution is here
#
# this is the code for including function randrange into our program
from random import randrange
# randrange(n) picks a number from the list [0,1,2,...,n-1] randomly
#r = randrange(100)
#print(r)
#
# your solution is here
#
# here is a schematic example for double nested loops
#for i in range(10):
# your_code1
# your_code2
# while j != 7:
# your_code_3
# your_code_4
#
# your solution is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.problems import ElectronicBasis
driver = PySCFDriver()
driver.run_pyscf()
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
ao_hamil = ao_problem.hamiltonian
print(ao_hamil.electronic_integrals.alpha)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
qcschema = driver.to_qcschema()
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
print(basis_transformer.initial_basis)
print(basis_transformer.final_basis)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
mo_hamil = mo_problem.hamiltonian
print(mo_hamil.electronic_integrals.alpha)
import numpy as np
from qiskit_nature.second_q.operators import ElectronicIntegrals
from qiskit_nature.second_q.problems import ElectronicBasis
from qiskit_nature.second_q.transformers import BasisTransformer
ao2mo_alpha = np.random.random((2, 2))
ao2mo_beta = np.random.random((2, 2))
basis_transformer = BasisTransformer(
ElectronicBasis.AO,
ElectronicBasis.MO,
ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta),
)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.molecule)
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
fc_transformer = FreezeCoreTransformer()
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
print(fc_problem.hamiltonian.constants)
fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5])
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
as_transformer = ActiveSpaceTransformer(2, 2)
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4])
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
from typing import Iterator, List, Set, Tuple
import numpy as np
import pytest
from qiskit import QuantumCircuit, execute
from qiskit_aer.backends import AerSimulator
from qiskit_aer.noise import NoiseModel, pauli_error
from qiskit_alice_bob_provider.local.backend import ProcessorSimulator
from qiskit_alice_bob_provider.local.job import ProcessorSimulationJob
from qiskit_alice_bob_provider.processor.description import (
AppliedInstruction,
InstructionProperties,
ProcessorDescription,
)
from qiskit_alice_bob_provider.processor.interpolated_cat import (
InterpolatedCatProcessor,
)
from qiskit_alice_bob_provider.processor.serialization.model import (
SerializedProcessor,
)
from qiskit_alice_bob_provider.processor.utils import pauli_errors_to_chi
from .processor_fixture import (
LargeSimpleProcessor,
OneQubitProcessor,
SimpleAllToAllProcessor,
SimpleProcessor,
)
def gen_circuits() -> Iterator[Tuple[str, QuantumCircuit, Set[str]]]:
circ = QuantumCircuit(2, 2)
circ.initialize('0', 0)
circ.initialize('+', 1)
circ.x(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure_x(1, 1)
yield ('everything_circuit', circ, {'11'})
@pytest.mark.parametrize(
['tup', 'backend'],
(
(tup, backend)
for tup in gen_circuits()
for backend in [
ProcessorSimulator(SimpleProcessor()),
ProcessorSimulator(
SimpleAllToAllProcessor(),
translation_stage_plugin='sk_synthesis',
),
]
),
)
def test_circuit(
tup: Tuple[str, QuantumCircuit, Set[str]], backend: ProcessorSimulator
) -> None:
_, circ, expected_keys = tup
# backend = ProcessorSimulator(SimpleProcessor())
job: ProcessorSimulationJob = execute(circ, backend)
result = job.result()
try:
assert result.get_counts().keys() == expected_keys
except AssertionError:
print('==== Original circuit ====')
print(circ)
print('==== Scheduled circuit ====')
print(job.circuits()[0])
print('==== Noisy circuit ====')
print(job.noisy_circuits()[0])
raise
def test_multiple_experiments() -> None:
circ1 = QuantumCircuit(1, 1)
circ1.x(0)
circ1.measure(0, 0)
circ2 = QuantumCircuit(1, 1)
circ2.initialize('+')
circ2.measure_x(0, 0)
backend = ProcessorSimulator(SimpleProcessor())
job: ProcessorSimulationJob = execute([circ1, circ2], backend)
result = job.result()
assert len(result.get_counts()) == 2
def test_non_default_shots() -> None:
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.measure(0, 0)
shots = 5
backend = ProcessorSimulator(SimpleProcessor())
job: ProcessorSimulationJob = execute(circ, backend, shots=shots)
result = job.result()
assert sum(result.get_counts().values()) == shots
class _CXProcessor(ProcessorDescription):
clock_cycle = 1
def all_instructions(self) -> Iterator[InstructionProperties]:
for i in range(2):
yield InstructionProperties(name='p0', params=[], qubits=(i,))
yield InstructionProperties(name='mz', params=[], qubits=(i,))
yield InstructionProperties(name='cx', params=[], qubits=(0, 1))
yield InstructionProperties(name='cx', params=[], qubits=(1, 0))
def apply_instruction(
self, name: str, qubits: Tuple[int, ...], params: List[float]
) -> AppliedInstruction:
if name == 'cx':
return AppliedInstruction(
duration=self.clock_cycle,
quantum_errors=pauli_errors_to_chi({'IX': 1.0}),
readout_errors=None,
)
return AppliedInstruction(
duration=self.clock_cycle,
quantum_errors=None,
readout_errors=None,
)
def gen_circuits_ordering() -> Iterator[Tuple[str, QuantumCircuit]]:
circ = QuantumCircuit(2, 2)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
yield ('01_circuit', circ)
circ = QuantumCircuit(2, 2)
circ.cx(1, 0)
circ.measure(0, 0)
circ.measure(1, 1)
yield ('10_circuit', circ)
@pytest.mark.parametrize('tup', gen_circuits_ordering())
def test_qubit_ordering(tup: Tuple[str, QuantumCircuit]) -> None:
_, circ = tup
aer = AerSimulator()
nm = NoiseModel()
nm.add_all_qubit_quantum_error(pauli_error([('IX', 1.0)]), 'cx')
aer_counts = execute(circ, aer, noise_model=nm).result().get_counts()
backend = ProcessorSimulator(_CXProcessor())
proc_counts = execute(circ, backend).result().get_counts()
try:
assert aer_counts == proc_counts
except AssertionError:
print(circ)
def test_interpolated_cat() -> None:
with open(
'tests/processor/serialization/data/all_types.json',
encoding='utf-8',
) as f:
ser = SerializedProcessor.model_validate_json(f.read())
proc = InterpolatedCatProcessor(ser, alpha=np.sqrt(5))
backend = ProcessorSimulator(proc)
circ = QuantumCircuit(2, 2)
circ.initialize('+', 0)
circ.initialize('0', 1)
circ.x(0)
circ.delay(800, 0, unit='s')
circ.y(0)
circ.rz(1.57, 0)
circ.cx(0, 1)
circ.measure_x(0, 0)
circ.measure(0, 1)
job = execute(circ, backend)
assert isinstance(job, ProcessorSimulationJob)
noisy_circ = job.noisy_circuits()[0]
assert len(noisy_circ.get_instructions('p0_error')) == 1
assert len(noisy_circ.get_instructions('p+_error')) == 1
assert len(noisy_circ.get_instructions('mx_error')) == 1
assert len(noisy_circ.get_instructions('x_error')) == 1
assert len(noisy_circ.get_instructions('y_error')) == 0
assert len(noisy_circ.get_instructions('rz_error')) == 1
assert len(noisy_circ.get_instructions('cx_error')) == 1
assert len(noisy_circ.get_instructions('mx_error')) == 1
assert len(noisy_circ.get_instructions('mz_error')) == 1
assert len(noisy_circ.get_instructions('delay')) == 1
# The next lines test that we can simulate without errors
job.result().get_counts()
def test_no_delay() -> None:
"""This test makes sure that quantum errors get inserted even when there
are no delay in the circuit after scheduling."""
backend = ProcessorSimulator(OneQubitProcessor())
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.measure_x(0, 0)
assert execute(circ, backend, shots=1).result().get_counts() == {'1': 1}
class _ConditioningProcessor(ProcessorDescription):
def __init__(self, clock_cycle: float = 1):
self.clock_cycle = clock_cycle
self.n_qubits = 2
def all_instructions(self) -> Iterator[InstructionProperties]:
yield InstructionProperties(name='p+', params=[], qubits=None)
yield InstructionProperties(name='p-', params=[], qubits=None)
yield InstructionProperties(name='mx', params=[], qubits=None)
yield InstructionProperties(name='x', params=[], qubits=None)
def apply_instruction(
self, name: str, qubits: Tuple[int, ...], params: List[float]
) -> AppliedInstruction:
if name == 'mx':
return AppliedInstruction(
duration=1e4,
quantum_errors=None,
readout_errors=None,
)
elif name in {'p+', 'p-'}:
return AppliedInstruction(
duration=1e2,
quantum_errors=None,
readout_errors=None,
)
elif name == 'x':
return AppliedInstruction(
duration=1e3,
quantum_errors=pauli_errors_to_chi({'Z': 1.0}),
readout_errors=None,
)
raise NotImplementedError()
def test_conditional_instruction() -> None:
# Noiseless backend, except the X gate that has a 100% Z-flip error
backend = ProcessorSimulator(_ConditioningProcessor())
circ = QuantumCircuit(2, 2)
circ.initialize('++')
circ.measure_x(0, 0)
circ.x(1).c_if(0, 0)
circ.measure_x(1, 1)
assert execute(circ, backend, shots=1).result().get_counts() == {'10': 1}
circ = QuantumCircuit(2, 2)
circ.initialize('+-')
circ.measure_x(0, 0)
circ.x(1).c_if(0, 0)
circ.measure_x(1, 1)
job = execute(circ, backend, shots=1)
assert job.result().get_counts() == {'01': 1}
def test_large_processor() -> None:
"""A processor with more qubits (40 here) than accepted by AerSimulator
(29 on my machine, this is based on system memory) would fail. A fix was
implemented in local/backend.py"""
backend = ProcessorSimulator(LargeSimpleProcessor())
circ = QuantumCircuit(1, 1)
circ.initialize('0')
circ.delay(1, 0, unit='s')
circ.measure(0, 0)
execute(circ, backend)
|
https://github.com/msramalho/Teach-Me-Quantum
|
msramalho
|
import qiskit
from qiskit import IBMQ # requires qiskit version >= 0.6
IBMQ.save_account("MY_TOKEN")
IBMQ.load_accounts()
for backend in IBMQ.backends():
print(backend)
backend_0 = IBMQ.backends()[0] # retrieve the Backend at index 0
print(backend_0.configuration())
print("Go check its specification at %s" % backend_0.configuration()["url"])
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Assembler Test."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import copy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.exceptions import QiskitError
from qiskit.pulse import Schedule, Acquire, Play
from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel
from qiskit.pulse.configuration import Kernel, Discriminator
from qiskit.pulse.library import gaussian
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.pulse.macros import measure
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeHanoi,
)
class RxGate(Gate):
"""Used to test custom gate assembly.
Useful for testing pulse gates with parameters, as well.
Note: Parallel maps (e.g., in assemble_circuits) pickle their input,
so circuit features have to be defined top level.
"""
def __init__(self, theta):
super().__init__("rxtheta", 1, [theta])
class TestCircuitAssembler(QiskitTestCase):
"""Tests for assembling circuits to qobj."""
def setUp(self):
super().setUp()
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
self.circ = QuantumCircuit(qr, cr, name="circ")
self.circ.h(qr[0])
self.circ.cx(qr[0], qr[1])
self.circ.measure(qr, cr)
self.backend = FakeYorktown()
self.backend_config = self.backend.configuration()
self.num_qubits = self.backend_config.n_qubits
# lo test values
self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)]
self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)]
self.user_lo_config_dict = {
pulse.DriveChannel(0): 5.55e9,
pulse.MeasureChannel(0): 6.64e9,
pulse.DriveChannel(3): 4.91e9,
pulse.MeasureChannel(4): 6.1e9,
}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
def test_assemble_single_circuit(self):
"""Test assembling a single circuit."""
qobj = assemble(self.circ, shots=2000, memory=True)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 2000)
self.assertEqual(qobj.config.memory, True)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(qobj.experiments[0].instructions[1].name, "cx")
def test_assemble_multiple_circuits(self):
"""Test assembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.seed_simulator, 6)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(qobj.experiments[1].config.n_qubits, 3)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(len(qobj.experiments[1].instructions), 6)
def test_assemble_no_run_config(self):
"""Test assembling with no run_config, relying on default."""
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 1024)
def test_shots_greater_than_max_shots(self):
"""Test assembling with shots greater than max shots"""
self.assertRaises(QiskitError, assemble, self.backend, shots=1024000)
def test_shots_not_of_type_int(self):
"""Test assembling with shots having type other than int"""
self.assertRaises(QiskitError, assemble, self.backend, shots="1024")
def test_shots_of_type_numpy_int64(self):
"""Test assembling with shots having type numpy.int64"""
qobj = assemble(self.circ, shots=np.int64(2048))
self.assertEqual(qobj.config.shots, 2048)
def test_default_shots_greater_than_max_shots(self):
"""Test assembling with default shots greater than max shots"""
self.backend_config.max_shots = 5
qobj = assemble(self.circ, self.backend)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 5)
def test_assemble_initialize(self):
"""Test assembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize")
np.testing.assert_almost_equal(
qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186]
)
def test_assemble_meas_level_meas_return(self):
"""Test assembling a circuit schedule with `meas_level`."""
qobj = assemble(self.circ, meas_level=1, meas_return="single")
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 1)
self.assertEqual(qobj.config.meas_return, "single")
# no meas_level set
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 2)
self.assertEqual(hasattr(qobj.config, "meas_return"), False)
def test_assemble_backend_rep_delays(self):
"""Check that rep_delay is properly set from backend values."""
rep_delay_range = [2.5e-3, 4.5e-3] # sec
default_rep_delay = 3.0e-3
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend)
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_delay works."""
# set custom rep_delay in runtime config
rep_delay = 2.2e-6
rep_delay_range = [0, 3e-6] # sec
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
# dynamic rep rates off (no default so shouldn't be in qobj config)
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# turn on dynamic rep rates, rep_delay should be set
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(qobj.config.rep_delay, 2.2)
# test ``rep_delay=0``
qobj = assemble(self.circ, self.backend, rep_delay=0)
self.assertEqual(qobj.config.rep_delay, 0)
# use ``rep_delay`` outside of ``rep_delay_range```
rep_delay_large = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.circ, self.backend, rep_delay=rep_delay_large)
def test_assemble_opaque_inst(self):
"""Test opaque instruction is assembled as-is"""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(len(qobj.experiments[0].instructions), 1)
self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst")
self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_assemble_unroll_parametervector(self):
"""Verfiy that assemble unrolls parametervectors ref #5467"""
pv1 = ParameterVector("pv1", 3)
pv2 = ParameterVector("pv2", 3)
qc = QuantumCircuit(2, 2)
for i in range(3):
qc.rx(pv1[i], 0)
qc.ry(pv2[i], 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]})
qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}])
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000)
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000)
self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000)
self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000)
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000)
self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000)
def test_measure_to_registers_when_conditionals(self):
"""Verify assemble_circuits maps all measure ops on to a register slot
for a circuit containing conditionals."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
first_measure, second_measure = (
op for op in qobj.experiments[0].instructions if op.name == "measure"
)
self.assertTrue(hasattr(first_measure, "register"))
self.assertEqual(first_measure.register, first_measure.memory)
self.assertTrue(hasattr(second_measure, "register"))
self.assertEqual(second_measure.register, second_measure.memory)
def test_convert_to_bfunc_plus_conditional(self):
"""Verify assemble_circuits converts conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x1")
self.assertEqual(bfunc_op.val, "0x1")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_convert_to_bfunc_plus_conditional_onebit(self):
"""Verify assemble_circuits converts single bit conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[2], 1)
qobj = assemble(qc)
inst_set = qobj.experiments[0].instructions
[bfunc_op, h_op] = inst_set
self.assertEqual(len(inst_set), 2)
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x4")
self.assertEqual(bfunc_op.val, "0x4")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_resize_value_to_register(self):
"""Verify assemble_circuits converts the value provided on the classical
creg to its mapped location on the device register."""
qr = QuantumRegister(1)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
qc.h(qr[0]).c_if(cr2, 2)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0xC")
self.assertEqual(bfunc_op.val, "0x8")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_circuits_raises_for_bind_circuit_mismatch(self):
"""Verify assemble_circuits raises error for parameterized circuits without matching
binds."""
qr = QuantumRegister(2)
x = Parameter("x")
y = Parameter("y")
full_bound_circ = QuantumCircuit(qr)
full_param_circ = QuantumCircuit(qr)
partial_param_circ = QuantumCircuit(qr)
partial_param_circ.p(x, qr[0])
full_param_circ.p(x, qr[0])
full_param_circ.p(y, qr[1])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]}
inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]}
# Raise when parameters passed for non-parametric circuit
self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args)
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, partial_param_circ)
self.assertRaises(QiskitError, assemble, full_param_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args)
# Raise when not all circuits have all parameters
self.assertRaises(
QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args
)
# Raise when not all binds have all circuit params
self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args)
def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self):
"""Verify assemble_circuits raises for invalid binds for circuit including
ParameterExpressions.
"""
qr = QuantumRegister(1)
x = Parameter("x")
y = Parameter("y")
expr_circ = QuantumCircuit(qr)
expr_circ.p(x + y, qr[0])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, expr_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args)
def test_assemble_circuits_binds_parameters(self):
"""Verify assemble_circuits applies parameter bindings and output circuits are bound."""
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
qc3 = QuantumCircuit(qr)
x = Parameter("x")
y = Parameter("y")
sum_ = x + y
product_ = x * y
qc1.u(x, y, 0, qr[0])
qc2.rz(x, qr[0])
qc2.rz(y, qr[0])
qc3.u(sum_, product_, 0, qr[0])
bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]}
qobj = assemble([qc1, qc2, qc3], **bind_args)
self.assertEqual(len(qobj.experiments), 9)
self.assertEqual(
[len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1]
)
def _qobj_inst_params(expt_no, inst_no):
expt = qobj.experiments[expt_no]
inst = expt.instructions[inst_no]
return [float(p) for p in inst.params]
self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0])
self.assertEqual(_qobj_inst_params(3, 0), [0])
self.assertEqual(_qobj_inst_params(3, 1), [0])
self.assertEqual(_qobj_inst_params(4, 0), [1])
self.assertEqual(_qobj_inst_params(4, 1), [0])
self.assertEqual(_qobj_inst_params(5, 0), [1])
self.assertEqual(_qobj_inst_params(5, 1), [1])
self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.circ)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_circuit_with_global_phase(self):
"""Test that global phase for a circuit is handled correctly."""
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
circ.global_phase = 0.3 * np.pi
qobj = assemble([circ, self.circ])
self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0)
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi)
def test_circuit_global_phase_gate_definitions(self):
"""Test circuit with global phase on gate definitions."""
class TestGate(Gate):
"""dummy gate"""
def __init__(self):
super().__init__("test_gate", 1, [])
def _define(self):
circ_def = QuantumCircuit(1)
circ_def.x(0)
circ_def.global_phase = np.pi
self._definition = circ_def
gate = TestGate()
circ = QuantumCircuit(1)
circ.append(gate, [0])
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0)
circ.global_phase = np.pi / 2
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2)
def test_pulse_gates_single_circ(self):
"""Test that we can add calibrations to circuits."""
theta = Parameter("theta")
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [0])
circ.append(RxGate(theta), [1])
circ = circ.assign_parameters({theta: 3.14})
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1))
circ.add_calibration("h", [0], custom_h_schedule)
circ.add_calibration(RxGate(3.14), [0], x180)
circ.add_calibration(RxGate(3.14), [1], x180)
qobj = assemble(circ, FakeOpenPulse2Q())
# Only one circuit, so everything is stored at the job level
cals = qobj.config.calibrations
lib = qobj.config.pulse_library
self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations"))
self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2)
self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1)
self.assertEqual(len(lib), 2)
self.assertTrue(all(len(item.samples) == 50 for item in lib))
def test_pulse_gates_with_parameteric_pulses(self):
"""Test that pulse gates are assembled efficiently for backends that enable
parametric pulses.
"""
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.add_calibration("h", [0], custom_h_schedule)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(circ, backend)
self.assertFalse(hasattr(qobj.config, "pulse_library"))
self.assertTrue(hasattr(qobj.config, "calibrations"))
def test_pulse_gates_multiple_circuits(self):
"""Test one circuit with cals and another without."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.pulse_library), 1)
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2)
self.assertFalse(hasattr(qobj.config, "calibrations"))
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_pulse_gates_common_cals(self):
"""Test that common calibrations are added at the top level."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
circ2.add_calibration(RxGate(3.14), [1], dummy_sched)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
# Identical pulses are only added once
self.assertEqual(len(qobj.config.pulse_library), 1)
# Identical calibrations are only added once
self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta")
self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14])
self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1])
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1)
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_assemble_adds_circuit_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"})
qobj = assemble(circ, shots=100, memory=False, seed_simulator=6)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_pulse_gates_delay_only(self):
"""Test that a single delay gate is translated to an instruction."""
circ = QuantumCircuit(2)
circ.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0))
circ.add_calibration("test", [0], test_sched)
qobj = assemble(circ, FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2)
self.assertEqual(
qobj.config.calibrations.gates[0].instructions[1].to_dict(),
{"name": "delay", "t0": 64, "ch": "d0", "duration": 160},
)
def test_job_qubit_meas_los_no_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out
any lo range."""
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
def test_job_lo_errors(self):
"""Test that job lo's are checked against the lo ranges and that errors are thrown if either
quantity has an incorrect length or type."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
# lo range not a nested list
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[4.995e9 for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# qubit lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# meas lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# qubit lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# meas lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)],
)
def test_job_qubit_meas_los_w_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo
ranges input. Verify that lo ranges do not enter into the config."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=meas_lo_range,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertNotIn("qubit_lo_range", qobj.config.to_dict())
self.assertNotIn("meas_lo_range", qobj.config.to_dict())
def test_assemble_single_circ_single_lo_config(self):
"""Test assembling a single circuit, with a single experiment level lo config."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_single_lo_config_dict(self):
"""Test assembling a single circuit, with a single experiment level lo config supplied as
dictionary."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_multi_lo_config(self):
"""Test assembling a single circuit, with multiple experiment level lo configs (frequency
sweep).
"""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_multi_lo_config(self):
"""Test assembling circuits, with the same number of experiment level lo configs (n:n
setup)."""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_single_lo_config(self):
"""Test assembling multiple circuits, with a single experiment level lo config (should
override job level)."""
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 2)
def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self):
"""Test assembling circuits, with a different number of experiment level lo configs (n:m
setup).
"""
with self.assertRaises(QiskitError):
assemble(
[self.circ, self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
)
def test_assemble_circ_lo_config_errors(self):
"""Test that lo config errors are raised properly if experiment level los are provided and
some are missing or if default values are not provided. Also check that experiment level lo
range is validated."""
# no defaults, but have drive/meas experiment level los for each qubit (no error)
full_lo_config_dict = {
pulse.DriveChannel(0): 4.85e9,
pulse.DriveChannel(1): 4.9e9,
pulse.DriveChannel(2): 4.95e9,
pulse.DriveChannel(3): 5e9,
pulse.DriveChannel(4): 5.05e9,
pulse.MeasureChannel(0): 6.8e9,
pulse.MeasureChannel(1): 6.85e9,
pulse.MeasureChannel(2): 6.9e9,
pulse.MeasureChannel(3): 6.95e9,
pulse.MeasureChannel(4): 7e9,
}
qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict)
self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05])
self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7])
self.assertEqual(len(qobj.experiments), 1)
# no defaults and missing experiment level drive lo raises
missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_drive_lo_config_dict.pop(pulse.DriveChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict)
# no defaults and missing experiment level meas lo raises
missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict)
# verify lo ranges are checked at experiment level
lo_values = list(full_lo_config_dict.values())
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]]
# out of range drive lo
full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
qubit_lo_range=qubit_lo_range,
schedule_los=full_lo_config_dict,
)
full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value
# out of range meas lo
full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
meas_lo_range=meas_lo_range,
schedule_los=full_lo_config_dict,
)
class TestPulseAssembler(QiskitTestCase):
"""Tests for assembling schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
test_pulse = pulse.Waveform(
samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128),
name="pulse0",
)
self.schedule = pulse.Schedule(name="fake_experiment")
self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0)))
for i in range(self.backend_config.n_qubits):
self.schedule = self.schedule.insert(
5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i))
)
self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
self.default_qubit_lo_freq = [4.9e9, 5.0e9]
self.default_meas_lo_freq = [6.5e9, 6.6e9]
self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"}
self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"}
def test_assemble_adds_schedule_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"}
qobj = assemble(
self.schedule,
shots=100,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_assemble_sample_pulse(self):
"""Test that the pulse lib and qobj instruction can be paired up."""
schedule = pulse.Schedule()
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2"
)
schedule += pulse.Play(
pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
qobj = assemble(
schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
experiment = test_dict["experiments"][0]
inst0_name = experiment["instructions"][0]["name"]
inst1_name = experiment["instructions"][1]["name"]
inst2_name = experiment["instructions"][2]["name"]
pulses = {}
for item in test_dict["config"]["pulse_library"]:
pulses[item["name"]] = item["samples"]
self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name]))
# Their pulses are the same
self.assertEqual(inst0_name, inst1_name)
self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16))
self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16))
def test_assemble_single_schedule_without_lo_config(self):
"""Test assembling a single schedule, no lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_multi_schedules_without_lo_config(self):
"""Test assembling schedules, no lo config."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config(self):
"""Test assembling a single schedule, with a single lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config_dict(self):
"""Test assembling a single schedule, with a single lo config supplied as dictionary."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_multi_lo_configs(self):
"""Test assembling a single schedule, with multiple lo configs (frequency sweep)."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_multi_lo_configs(self):
"""Test assembling schedules, with the same number of lo configs (n:n setup)."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self):
"""Test assembling schedules, with a different number of lo configs (n:m setup)."""
with self.assertRaises(QiskitError):
assemble(
[self.schedule, self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
def test_assemble_meas_map(self):
"""Test assembling a single schedule, no lo config."""
schedule = Schedule(name="fake_experiment")
schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0)))
schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1)))
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertIsInstance(qobj, PulseQobj)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_memory_slots(self):
"""Test assembling a schedule and inferring number of memoryslots."""
n_memoryslots = 10
# single acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
# multiple acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
schedule = schedule.insert(
10,
Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
def test_assemble_memory_slots_for_schedules(self):
"""Test assembling schedules with different memory slots."""
n_memoryslots = [10, 5, 7]
schedules = []
for n_memoryslot in n_memoryslots:
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1)
)
schedules.append(schedule)
qobj = assemble(
schedules,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, max(n_memoryslots))
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0])
self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1])
self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2])
def test_pulse_name_conflicts(self):
"""Test that pulse name conflicts can be resolved."""
name_conflict_pulse = pulse.Waveform(
samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0"
)
self.schedule = self.schedule.insert(
1, Play(name_conflict_pulse, self.backend_config.drive(1))
)
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name)
def test_pulse_name_conflicts_in_other_schedule(self):
"""Test two pulses with the same name in different schedule can be resolved."""
backend = FakeHanoi()
defaults = backend.defaults()
schedules = []
ch_d0 = pulse.DriveChannel(0)
for amp in (0.1, 0.2):
sched = Schedule()
sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0)
sched += measure(qubits=[0], backend=backend) << 100
schedules.append(sched)
qobj = assemble(
schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est
)
# two user pulses and one measurement pulse should be contained
self.assertEqual(len(qobj.config.pulse_library), 3)
def test_assemble_with_delay(self):
"""Test that delay instruction is not ignored in assembly."""
delay_schedule = pulse.Delay(10, self.backend_config.drive(0))
delay_schedule += self.schedule
delay_qobj = assemble(delay_schedule, self.backend)
self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0)
def test_delay_removed_on_acq_ch(self):
"""Test that delay instructions on acquire channels are skipped on assembly with times
shifted properly.
"""
delay0 = pulse.Delay(5, self.backend_config.acquire(0))
delay1 = pulse.Delay(7, self.backend_config.acquire(1))
sched0 = delay0
sched0 += self.schedule # includes ``Acquire`` instr
sched0 += delay1
sched1 = self.schedule # includes ``Acquire`` instr
sched1 += delay0
sched1 += delay1
sched2 = delay0
sched2 += delay1
sched2 += self.schedule # includes ``Acquire`` instr
delay_qobj = assemble([sched0, sched1, sched2], self.backend)
# check that no delay instrs occur on acquire channels
is_acq_delay = False
for exp in delay_qobj.experiments:
for instr in exp.instructions:
if instr.name == "delay" and "a" in instr.ch:
is_acq_delay = True
self.assertFalse(is_acq_delay)
# check that acquire instr are shifted from ``t0=5`` as needed
self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5)
self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12)
self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire")
def test_assemble_schedule_enum(self):
"""Test assembling a schedule with enum input values to assemble."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE,
)
test_dict = qobj.to_dict()
self.assertEqual(test_dict["config"]["meas_return"], "avg")
self.assertEqual(test_dict["config"]["meas_level"], 2)
def test_assemble_parametric(self):
"""Test that parametric pulses can be assembled properly into a PulseQobj."""
amp = [0.5, 0.6, 1, 0.2]
angle = [np.pi / 2, 0.6, 0, 0]
sched = pulse.Schedule(name="test_parametric")
sched += Play(
pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0)
)
sched += Play(
pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2))
sched += (
Play(
pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140),
MeasureChannel(0),
)
<< sched.duration
)
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = [
"gaussian",
"drag",
"gaussian_square",
"constant",
]
qobj = assemble(sched, backend)
self.assertEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts))
self.assertEqual(qobj_insts[0].pulse_shape, "gaussian")
self.assertEqual(qobj_insts[1].pulse_shape, "drag")
self.assertEqual(qobj_insts[2].pulse_shape, "constant")
self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square")
self.assertDictEqual(
qobj_insts[0].parameters,
{"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])},
)
self.assertDictEqual(
qobj_insts[1].parameters,
{"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4},
)
self.assertDictEqual(
qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])}
)
self.assertDictEqual(
qobj_insts[3].parameters,
{"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140},
)
self.assertEqual(
qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"],
amp[0] * np.exp(1j * angle[0]),
)
def test_assemble_parametric_unsupported(self):
"""Test that parametric pulses are translated to Waveform if they're not supported
by the backend during assemble time.
"""
sched = pulse.Schedule(name="test_parametric_to_sample_pulse")
sched += Play(
pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ["something_extra"]
qobj = assemble(sched, backend)
self.assertNotEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertFalse(hasattr(qobj_insts[0], "pulse_shape"))
def test_assemble_parametric_pulse_kwarg_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=["gaussian"])
self.assertEqual(qobj.config.parametric_pulses, ["gaussian"])
def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg as empty list over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=[])
self.assertEqual(qobj.config.parametric_pulses, [])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_assemble_backend_rep_times_delays(self):
"""Check that rep_time and rep_delay are properly set from backend values."""
# use first entry from allowed backend values
rep_times = [2.0, 3.0, 4.0] # sec
rep_delay_range = [2.5e-3, 4.5e-3]
default_rep_delay = 3.0e-3
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
# RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_time and rep_delay work."""
# set custom rep_time and rep_delay in runtime config
rep_time = 200.0e-6
rep_delay = 2.5e-6
self.config["rep_time"] = rep_time
self.config["rep_delay"] = rep_delay
# dynamic rep rates off
# RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# now remove rep_delay and enable dynamic rep rates
# RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled
del self.config["rep_delay"]
setattr(self.backend_config, "dynamic_reprate_enabled", True)
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# use ``default_rep_delay``
# ``rep_time`` comes from allowed backend rep_times
rep_times = [0.5, 1.0, 1.5] # sec
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6])
setattr(self.backend_config, "default_rep_delay", 2.2e-6)
del self.config["rep_time"]
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 2.2)
# use qobj ``default_rep_delay``
self.config["rep_delay"] = 1.5e-6
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 1.5)
# use ``rep_delay`` outside of ``rep_delay_range
self.config["rep_delay"] = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.schedule, self.backend, **self.config)
def test_assemble_with_individual_discriminators(self):
"""Test that assembly works with individual discriminators."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 2)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
self.assertEqual(qobj_discriminators[1].name, "disc_two")
self.assertEqual(qobj_discriminators[1].params["test_params"], False)
def test_assemble_with_single_discriminators(self):
"""Test that assembly works with both a single discriminator."""
disc_one = Discriminator("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 1)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
def test_assemble_with_unequal_discriminators(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_with_individual_kernels(self):
"""Test that assembly works with individual kernels."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 2)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
self.assertEqual(qobj_kernels[1].name, "disc_two")
self.assertEqual(qobj_kernels[1].params["test_params"], False)
def test_assemble_with_single_kernels(self):
"""Test that assembly works with both a single kernel."""
disc_one = Kernel("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 1)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
def test_assemble_with_unequal_kernels(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_single_instruction(self):
"""Test assembling schedules, no lo config."""
inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
self.assertIsInstance(assemble(inst, self.backend), PulseQobj)
def test_assemble_overlapping_time(self):
"""Test that assembly errors when qubits are measured in overlapping time."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
def test_assemble_meas_map_vs_insts(self):
"""Test that assembly errors when the qubits are measured in overlapping time
and qubits are not in the first meas_map list."""
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0))
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1))
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2
schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1, 2], [3]],
)
def test_assemble_non_overlapping_time_single_meas_map(self):
"""Test that assembly works when qubits are measured in non-overlapping
time within the same measurement map list."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_disjoint_time(self):
"""Test that assembly works when qubits are in disjoint meas map sets."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 2], [1, 3]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_valid_qubits(self):
"""Test that assembly works when qubits that are in the measurement map
is measured."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(2), MemorySlot(2)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(3), MemorySlot(3)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2], [3]],
)
self.assertIsInstance(qobj, PulseQobj)
class TestPulseAssemblerMissingKwargs(QiskitTestCase):
"""Verify that errors are raised in case backend is not provided and kwargs are missing."""
def setUp(self):
super().setUp()
self.schedule = pulse.Schedule(name="fake_experiment")
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.defaults = self.backend.defaults()
self.qubit_lo_freq = list(self.defaults.qubit_freq_est)
self.meas_lo_freq = list(self.defaults.meas_freq_est)
self.qubit_lo_range = self.config.qubit_lo_range
self.meas_lo_range = self.config.meas_lo_range
self.schedule_los = {
pulse.DriveChannel(0): self.qubit_lo_freq[0],
pulse.DriveChannel(1): self.qubit_lo_freq[1],
pulse.MeasureChannel(0): self.meas_lo_freq[0],
pulse.MeasureChannel(1): self.meas_lo_freq[1],
}
self.meas_map = self.config.meas_map
self.memory_slots = self.config.n_qubits
# default rep_time and rep_delay
self.rep_time = self.config.rep_times[0]
self.rep_delay = None
def test_defaults(self):
"""Test defaults work."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_qubit_lo_freq(self):
"""Test error raised if qubit_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=None,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_meas_lo_freq(self):
"""Test error raised if meas_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=None,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_memory_slots(self):
"""Test error is not raised if memory_slots are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_rep_time_and_delay(self):
"""Test qobj is valid if rep_time and rep_delay are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=None,
rep_delay=None,
)
self.assertEqual(hasattr(qobj, "rep_time"), False)
self.assertEqual(hasattr(qobj, "rep_delay"), False)
def test_missing_meas_map(self):
"""Test that assembly still works if meas_map is missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=None,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_lo_ranges(self):
"""Test that assembly still works if lo_ranges are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=None,
meas_lo_range=None,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_unsupported_meas_level(self):
"""Test that assembly raises an error if meas_level is not supported"""
backend = FakeOpenPulse2Q()
backend.configuration().meas_levels = [1, 2]
with self.assertRaises(QiskitError):
assemble(
self.schedule,
backend,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_level=0,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_single_and_deprecated_acquire_styles(self):
"""Test that acquires are identically combined with Acquires that take a single channel."""
backend = FakeOpenPulse2Q()
new_style_schedule = Schedule()
acq_dur = 1200
for i in range(2):
new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i))
deprecated_style_schedule = Schedule()
for i in range(2):
deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i))
# The Qobj IDs will be different
n_qobj = assemble(new_style_schedule, backend)
n_qobj.qobj_id = None
n_qobj.experiments[0].header.name = None
d_qobj = assemble(deprecated_style_schedule, backend)
d_qobj.qobj_id = None
d_qobj.experiments[0].header.name = None
self.assertEqual(n_qobj, d_qobj)
assembled_acquire = n_qobj.experiments[0].instructions[0]
self.assertEqual(assembled_acquire.qubits, [0, 1])
self.assertEqual(assembled_acquire.memory_slot, [0, 1])
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogAssembler(QiskitTestCase):
"""Testing the log_assembly option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertAssembleLog(self, log_msg):
"""Runs assemble and checks for logs containing specified message"""
assemble(self.circuit, shots=2000, memory=True)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
assembly_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(assembly_log_lines) == 1)
def test_assembly_log_time(self):
"""Check Total Assembly Time is logged"""
self.assertAssembleLog("Total Assembly Time")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Transpiler pulse gate pass testing."""
import ddt
from qiskit import pulse, circuit, transpile
from qiskit.providers.fake_provider import FakeAthens, FakeAthensV2
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestPulseGate(QiskitTestCase):
"""Integration test of pulse gate pass with custom backend."""
def setUp(self):
super().setUp()
self.sched_param = circuit.Parameter("P0")
with pulse.build(name="sx_q0") as custom_sx_q0:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
self.custom_sx_q0 = custom_sx_q0
with pulse.build(name="sx_q1") as custom_sx_q1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(1))
self.custom_sx_q1 = custom_sx_q1
with pulse.build(name="cx_q01") as custom_cx_q01:
pulse.play(pulse.Constant(100, 0.4), pulse.ControlChannel(0))
self.custom_cx_q01 = custom_cx_q01
with pulse.build(name="my_gate_q0") as my_gate_q0:
pulse.shift_phase(self.sched_param, pulse.DriveChannel(0))
pulse.play(pulse.Constant(120, 0.1), pulse.DriveChannel(0))
self.my_gate_q0 = my_gate_q0
with pulse.build(name="my_gate_q1") as my_gate_q1:
pulse.shift_phase(self.sched_param, pulse.DriveChannel(1))
pulse.play(pulse.Constant(120, 0.2), pulse.DriveChannel(1))
self.my_gate_q1 = my_gate_q1
def test_transpile_with_bare_backend(self):
"""Test transpile without custom calibrations."""
backend = FakeAthens()
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[0, 1])
ref_calibration = {}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_backend_target(self):
"""Test transpile without custom calibrations from target."""
backend = FakeAthensV2()
target = backend.target
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target)
ref_calibration = {}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_basis_gate(self):
"""Test transpile with custom calibrations."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0)
backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1)
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[0, 1])
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_basis_gate_in_target(self):
"""Test transpile with custom calibrations."""
backend = FakeAthensV2()
target = backend.target
target["sx"][(0,)].calibration = self.custom_sx_q0
target["sx"][(1,)].calibration = self.custom_sx_q1
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, initial_layout=[0, 1], target=target)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_instmap(self):
"""Test providing instruction schedule map."""
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("sx", (0,), self.custom_sx_q0)
instmap.add("sx", (1,), self.custom_sx_q1)
# Inst map is renewed
backend = FakeAthens()
qc = circuit.QuantumCircuit(2)
qc.sx(0)
qc.x(0)
qc.rz(0, 0)
qc.sx(1)
qc.measure_all()
transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1])
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_custom_gate(self):
"""Test providing non-basis gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
backend.defaults().instruction_schedule_map.add(
"my_gate", (1,), self.my_gate_q1, arguments=["P0"]
)
qc = circuit.QuantumCircuit(2)
qc.append(circuit.Gate("my_gate", 1, [1.0]), [0])
qc.append(circuit.Gate("my_gate", 1, [2.0]), [1])
transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1])
my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False)
my_gate_q1_2_0 = self.my_gate_q1.assign_parameters({self.sched_param: 2.0}, inplace=False)
ref_calibration = {
"my_gate": {
((0,), (1.0,)): my_gate_q0_1_0,
((1,), (2.0,)): my_gate_q1_2_0,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_parameterized_custom_gate(self):
"""Test providing non-basis gate, which is kept parameterized throughout transpile."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
param = circuit.Parameter("new_P0")
qc = circuit.QuantumCircuit(1)
qc.append(circuit.Gate("my_gate", 1, [param]), [0])
transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0])
my_gate_q0_p = self.my_gate_q0.assign_parameters({self.sched_param: param}, inplace=False)
ref_calibration = {
"my_gate": {
((0,), (param,)): my_gate_q0_p,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_multiple_circuits(self):
"""Test transpile with multiple circuits with custom gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
params = [0.0, 1.0, 2.0, 3.0]
circs = []
for param in params:
qc = circuit.QuantumCircuit(1)
qc.append(circuit.Gate("my_gate", 1, [param]), [0])
circs.append(qc)
transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0])
for param, transpiled_qc in zip(params, transpiled_qcs):
my_gate_q0_x = self.my_gate_q0.assign_parameters(
{self.sched_param: param}, inplace=False
)
ref_calibration = {"my_gate": {((0,), (param,)): my_gate_q0_x}}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_multiple_instructions_with_different_parameters(self):
"""Test adding many instruction with different parameter binding."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add(
"my_gate", (0,), self.my_gate_q0, arguments=["P0"]
)
qc = circuit.QuantumCircuit(1)
qc.append(circuit.Gate("my_gate", 1, [1.0]), [0])
qc.append(circuit.Gate("my_gate", 1, [2.0]), [0])
qc.append(circuit.Gate("my_gate", 1, [3.0]), [0])
transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0])
my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False)
my_gate_q0_2_0 = self.my_gate_q0.assign_parameters({self.sched_param: 2.0}, inplace=False)
my_gate_q0_3_0 = self.my_gate_q0.assign_parameters({self.sched_param: 3.0}, inplace=False)
ref_calibration = {
"my_gate": {
((0,), (1.0,)): my_gate_q0_1_0,
((0,), (2.0,)): my_gate_q0_2_0,
((0,), (3.0,)): my_gate_q0_3_0,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_different_qubit(self):
"""Test transpile with qubit without custom gate."""
backend = FakeAthens()
backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0)
qc = circuit.QuantumCircuit(1)
qc.sx(0)
qc.measure_all()
transpiled_qc = transpile(qc, backend, initial_layout=[3])
self.assertDictEqual(transpiled_qc.calibrations, {})
@ddt.data(0, 1, 2, 3)
def test_transpile_with_both_instmap_and_empty_target(self, opt_level):
"""Test when instmap and target are both provided
and only instmap contains custom schedules.
Test case from Qiskit/qiskit-terra/#9489
"""
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("sx", (0,), self.custom_sx_q0)
instmap.add("sx", (1,), self.custom_sx_q1)
instmap.add("cx", (0, 1), self.custom_cx_q01)
# This doesn't have custom schedule definition
target = FakeAthensV2().target
qc = circuit.QuantumCircuit(2)
qc.append(random_unitary(4, seed=123), [0, 1])
qc.measure_all()
transpiled_qc = transpile(
qc,
optimization_level=opt_level,
basis_gates=["sx", "rz", "x", "cx"],
inst_map=instmap,
target=target,
initial_layout=[0, 1],
)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
},
"cx": {
((0, 1), ()): self.custom_cx_q01,
},
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
@ddt.data(0, 1, 2, 3)
def test_transpile_with_instmap_with_v2backend(self, opt_level):
"""Test when instmap is provided with V2 backend.
Test case from Qiskit/qiskit-terra/#9489
"""
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("sx", (0,), self.custom_sx_q0)
instmap.add("sx", (1,), self.custom_sx_q1)
instmap.add("cx", (0, 1), self.custom_cx_q01)
qc = circuit.QuantumCircuit(2)
qc.append(random_unitary(4, seed=123), [0, 1])
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
optimization_level=opt_level,
inst_map=instmap,
initial_layout=[0, 1],
)
ref_calibration = {
"sx": {
((0,), ()): self.custom_sx_q0,
((1,), ()): self.custom_sx_q1,
},
"cx": {
((0, 1), ()): self.custom_cx_q01,
},
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
@ddt.data(0, 1, 2, 3)
def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level):
"""Test when instmap is provided with V2 backend.
In this test case, instmap contains a custom gate which doesn't belong to
Qiskit standard gate. Target must define a custom gete on the fly
to reflect user-provided instmap.
Test case from Qiskit/qiskit-terra/#9489
"""
with pulse.build(name="custom") as rabi12:
pulse.play(pulse.Constant(100, 0.4), pulse.DriveChannel(0))
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("rabi12", (0,), rabi12)
gate = circuit.Gate("rabi12", 1, [])
qc = circuit.QuantumCircuit(1)
qc.append(gate, [0])
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
optimization_level=opt_level,
inst_map=instmap,
initial_layout=[0],
)
ref_calibration = {
"rabi12": {
((0,), ()): rabi12,
}
}
self.assertDictEqual(transpiled_qc.calibrations, ref_calibration)
def test_transpile_with_instmap_not_mutate_backend(self):
"""Do not override default backend target when transpile with inst map.
Providing an instmap for the transpile arguments may override target,
which might be pulled from the provided backend instance.
This should not override the source object since the same backend may
be used for future transpile without intention of instruction overriding.
"""
backend = FakeAthensV2()
original_sx0 = backend.target["sx"][(0,)].calibration
instmap = FakeAthens().defaults().instruction_schedule_map
instmap.add("sx", (0,), self.custom_sx_q0)
qc = circuit.QuantumCircuit(1)
qc.sx(0)
qc.measure_all()
transpiled_qc = transpile(
qc,
FakeAthensV2(),
inst_map=instmap,
initial_layout=[0],
)
self.assertTrue(transpiled_qc.has_calibration_for(transpiled_qc.data[0]))
self.assertEqual(
backend.target["sx"][(0,)].calibration,
original_sx0,
)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
The Amplitude Estimation Algorithm.
"""
import logging
from collections import OrderedDict
import numpy as np
from qiskit import ClassicalRegister
from qiskit.aqua import AquaError
from qiskit.aqua import Pluggable, PluggableType, get_pluggable_class
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.aqua.components.iqfts import Standard
from .q_factory import QFactory
logger = logging.getLogger(__name__)
class AmplitudeEstimation(QuantumAlgorithm):
"""
The Amplitude Estimation algorithm.
"""
CONFIGURATION = {
'name': 'AmplitudeEstimation',
'description': 'Amplitude Estimation Algorithm',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'AmplitudeEstimation_schema',
'type': 'object',
'properties': {
'num_eval_qubits': {
'type': 'integer',
'default': 5,
'minimum': 1
}
},
'additionalProperties': False
},
'problems': ['uncertainty'],
'depends': [
{
'pluggable_type': 'uncertainty_problem',
'default': {
'name': 'EuropeanCallDelta'
}
},
{
'pluggable_type': 'iqft',
'default': {
'name': 'STANDARD',
}
},
],
}
def __init__(self, num_eval_qubits, a_factory, i_objective=None, q_factory=None, iqft=None):
"""
Constructor.
Args:
num_eval_qubits (int): number of evaluation qubits
a_factory (CircuitFactory): the CircuitFactory subclass object representing the problem unitary
q_factory (CircuitFactory): the CircuitFactory subclass object representing an amplitude estimation sample (based on a_factory)
iqft (IQFT): the Inverse Quantum Fourier Transform pluggable component, defaults to using a standard iqft when None
"""
self.validate(locals())
super().__init__()
# get/construct A/Q operator
self.a_factory = a_factory
if q_factory is None:
if i_objective is None:
i_objective = self.a_factory.num_target_qubits - 1
self.q_factory = QFactory(a_factory, i_objective)
else:
self.q_factory = q_factory
# get parameters
self._m = num_eval_qubits
self._M = 2 ** num_eval_qubits
# determine number of ancillas
self._num_ancillas = self.q_factory.required_ancillas_controlled()
self._num_qubits = self.a_factory.num_target_qubits + self._m + self._num_ancillas
if iqft is None:
iqft = Standard(self._m)
self._iqft = iqft
self._circuit = None
self._ret = {}
@classmethod
def init_params(cls, params, algo_input):
"""
Initialize via parameters dictionary and algorithm input instance
Args:
params: parameters dictionary
algo_input: Input instance
"""
if algo_input is not None:
raise AquaError("Input instance not supported.")
ae_params = params.get(Pluggable.SECTION_KEY_ALGORITHM)
num_eval_qubits = ae_params.get('num_eval_qubits')
# Set up uncertainty problem. The params can include an uncertainty model
# type dependent on the uncertainty problem and is this its responsibility
# to create for itself from the complete params set that is passed to it.
uncertainty_problem_params = params.get(Pluggable.SECTION_KEY_UNCERTAINTY_PROBLEM)
uncertainty_problem = get_pluggable_class(
PluggableType.UNCERTAINTY_PROBLEM,
uncertainty_problem_params['name']).init_params(params)
# Set up iqft, we need to add num qubits to params which is our num_ancillae bits here
iqft_params = params.get(Pluggable.SECTION_KEY_IQFT)
iqft_params['num_qubits'] = num_eval_qubits
iqft = get_pluggable_class(PluggableType.IQFT, iqft_params['name']).init_params(params)
return cls(num_eval_qubits, uncertainty_problem, q_factory=None, iqft=iqft)
def construct_circuit(self, measurement=False):
"""
Construct the Amplitude Estimation quantum circuit.
Args:
measurement (bool): Boolean flag to indicate if measurement should be included in the circuit.
Returns:
the QuantumCircuit object for the constructed circuit
"""
pec = PhaseEstimationCircuit(
iqft=self._iqft, num_ancillae=self._m,
state_in_circuit_factory=self.a_factory,
unitary_circuit_factory=self.q_factory
)
self._circuit = pec.construct_circuit(measurement=measurement)
return self._circuit
def _evaluate_statevector_results(self, probabilities):
# map measured results to estimates
y_probabilities = OrderedDict()
for i, probability in enumerate(probabilities):
b = "{0:b}".format(i).rjust(self._num_qubits, '0')[::-1]
y = int(b[:self._m], 2)
y_probabilities[y] = y_probabilities.get(y, 0) + probability
a_probabilities = OrderedDict()
for y, probability in y_probabilities.items():
if y >= int(self._M / 2):
y = self._M - y
a = np.power(np.sin(y * np.pi / 2 ** self._m), 2)
a_probabilities[a] = a_probabilities.get(a, 0) + probability
return a_probabilities, y_probabilities
def _run(self):
if self._quantum_instance.is_statevector:
self.construct_circuit(measurement=False)
# run circuit on statevector simlator
ret = self._quantum_instance.execute(self._circuit)
state_vector = np.asarray([ret.get_statevector(self._circuit)])
self._ret['statevector'] = state_vector
# get state probabilities
state_probabilities = np.real(state_vector.conj() * state_vector)[0]
# evaluate results
a_probabilities, y_probabilities = self._evaluate_statevector_results(state_probabilities)
else:
# run circuit on QASM simulator
self.construct_circuit(measurement=True)
ret = self._quantum_instance.execute(self._circuit)
# get counts
self._ret['counts'] = ret.get_counts()
# construct probabilities
y_probabilities = {}
a_probabilities = {}
shots = sum(ret.get_counts().values())
for state, counts in ret.get_counts().items():
y = int(state.replace(' ', '')[:self._m][::-1], 2)
p = counts / shots
y_probabilities[y] = p
a = np.power(np.sin(y * np.pi / 2 ** self._m), 2)
a_probabilities[a] = a_probabilities.get(a, 0.0) + p
# construct a_items and y_items
a_items = [(a, p) for (a, p) in a_probabilities.items() if p > 1e-6]
y_items = [(y, p) for (y, p) in y_probabilities.items() if p > 1e-6]
a_items = sorted(a_items)
y_items = sorted(y_items)
self._ret['a_items'] = a_items
self._ret['y_items'] = y_items
# map estimated values to original range and extract probabilities
self._ret['mapped_values'] = [self.a_factory.value_to_estimation(a_item[0]) for a_item in self._ret['a_items']]
self._ret['values'] = [a_item[0] for a_item in self._ret['a_items']]
self._ret['y_values'] = [y_item[0] for y_item in y_items]
self._ret['probabilities'] = [a_item[1] for a_item in self._ret['a_items']]
self._ret['mapped_items'] = [(self._ret['mapped_values'][i], self._ret['probabilities'][i]) for i in range(len(self._ret['mapped_values']))]
# determine most likely estimator
self._ret['estimation'] = None
self._ret['max_probability'] = 0
for val, prob in self._ret['mapped_items']:
if prob > self._ret['max_probability']:
self._ret['max_probability'] = prob
self._ret['estimation'] = val
return self._ret
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Amplitude Estimation Benchmark Program via Phase Estimation - QSim
"""
import copy
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"]
import execute as ex
import metrics as metrics
from qft_benchmark import inv_qft_gate
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Amplitude Estimation"
np.random.seed(0)
verbose = False
# saved subcircuits circuits for printing
A_ = None
Q_ = None
cQ_ = None
QC_ = None
QFTI_ = None
############### Circuit Definition
def AmplitudeEstimation(num_state_qubits, num_counting_qubits, a, psi_zero=None, psi_one=None):
num_qubits = num_state_qubits + 1 + num_counting_qubits
qr_state = QuantumRegister(num_state_qubits+1)
qr_counting = QuantumRegister(num_counting_qubits)
cr = ClassicalRegister(num_counting_qubits)
qc = QuantumCircuit(qr_counting, qr_state, cr, name=f"qae-{num_qubits}-{a}")
# create the Amplitude Generator circuit
A = A_gen(num_state_qubits, a, psi_zero, psi_one)
# create the Quantum Operator circuit and a controlled version of it
cQ, Q = Ctrl_Q(num_state_qubits, A)
# save small example subcircuits for visualization
global A_, Q_, cQ_, QFTI_
if (cQ_ and Q_) == None or num_state_qubits <= 6:
if num_state_qubits < 9: cQ_ = cQ; Q_ = Q; A_ = A
if QFTI_ == None or num_qubits <= 5:
if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits)
# Prepare state from A, and counting qubits with H transform
qc.append(A, [qr_state[i] for i in range(num_state_qubits+1)])
for i in range(num_counting_qubits):
qc.h(qr_counting[i])
repeat = 1
for j in reversed(range(num_counting_qubits)):
for _ in range(repeat):
qc.append(cQ, [qr_counting[j]] + [qr_state[l] for l in range(num_state_qubits+1)])
repeat *= 2
qc.barrier()
# inverse quantum Fourier transform only on counting qubits
qc.append(inv_qft_gate(num_counting_qubits), qr_counting)
qc.barrier()
# measure counting qubits
qc.measure([qr_counting[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits)))
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
return qc
# Construct A operator that takes |0>_{n+1} to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1>
def A_gen(num_state_qubits, a, psi_zero=None, psi_one=None):
if psi_zero==None:
psi_zero = '0'*num_state_qubits
if psi_one==None:
psi_one = '1'*num_state_qubits
theta = 2 * np.arcsin(np.sqrt(a))
# Let the objective be qubit index n; state is on qubits 0 through n-1
qc_A = QuantumCircuit(num_state_qubits+1, name=f"A")
# takes state to |0>_{n} (sqrt(1-a) |0> + sqrt(a) |1>)
qc_A.ry(theta, num_state_qubits)
# takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |0>_{n}|1>
qc_A.x(num_state_qubits)
for i in range(num_state_qubits):
if psi_zero[i]=='1':
qc_A.cnot(num_state_qubits,i)
qc_A.x(num_state_qubits)
# takes state to sqrt(1-a) |psi_0>|0> + sqrt(a) |psi_1>|1>
for i in range(num_state_qubits):
if psi_one[i]=='1':
qc_A.cnot(num_state_qubits,i)
return qc_A
# Construct the grover-like operator and a controlled version of it
def Ctrl_Q(num_state_qubits, A_circ):
# index n is the objective qubit, and indexes 0 through n-1 are state qubits
qc = QuantumCircuit(num_state_qubits+1, name=f"Q")
temp_A = copy.copy(A_circ)
A_gate = temp_A.to_gate()
A_gate_inv = temp_A.inverse().to_gate()
### Each cycle in Q applies in order: -S_chi, A_circ_inverse, S_0, A_circ
# -S_chi
qc.x(num_state_qubits)
qc.z(num_state_qubits)
qc.x(num_state_qubits)
# A_circ_inverse
qc.append(A_gate_inv, [i for i in range(num_state_qubits+1)])
# S_0
for i in range(num_state_qubits+1):
qc.x(i)
qc.h(num_state_qubits)
qc.mcx([x for x in range(num_state_qubits)], num_state_qubits)
qc.h(num_state_qubits)
for i in range(num_state_qubits+1):
qc.x(i)
# A_circ
qc.append(A_gate, [i for i in range(num_state_qubits+1)])
# Create a gate out of the Q operator
qc.to_gate(label='Q')
# and also a controlled version of it
Ctrl_Q_ = qc.control(1)
# and return both
return Ctrl_Q_, qc
# Analyze and print measured results
# Expected result is always the secret_int (which encodes alpha), so fidelity calc is simple
def analyze_and_print_result(qc, result, num_counting_qubits, s_int, num_shots):
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# calculate expected output histogram
a = a_from_s_int(s_int, num_counting_qubits)
correct_dist = a_to_bitstring(a, num_counting_qubits)
# print("correct_dist ====== ", correct_dist)
# generate thermal_dist for polarization calculation
thermal_dist = metrics.uniform_dist(num_counting_qubits)
# print("thermal_dist ====== ", thermal_dist)
# convert probs, expectation, and thermal_dist to app form for visibility
# app form of correct distribution is measuring amplitude a 100% of the time
app_counts = bitstring_to_a(probs, num_counting_qubits)
app_correct_dist = {a: 1.0}
app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits)
# print("app_counts ====== ", app_counts)
# print("app_correct_dist ====== ", app_correct_dist)
# print("app_thermal_dist ====== ", app_thermal_dist)
if verbose:
print(f"For amplitude {a}, expected: {correct_dist} measured: {probs}")
print(f" ... For amplitude {a} thermal_dist: {thermal_dist}")
print(f"For amplitude {a}, app expected: {app_correct_dist} measured: {app_counts}")
print(f" ... For amplitude {a} app_thermal_dist: {app_thermal_dist}")
# use polarization fidelity with rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist, thermal_dist)
#fidelity = metrics.polarization_fidelity(app_counts, app_correct_dist, app_thermal_dist)
# print("fidelity ====== ", fidelity)
hf_fidelity = metrics.hellinger_fidelity_with_expected(probs, correct_dist)
if verbose: print(f" ... fidelity: {fidelity} hf_fidelity: {hf_fidelity}")
return probs, fidelity
def a_to_bitstring(a, num_counting_qubits):
m = num_counting_qubits
# solution 1
num1 = round(np.arcsin(np.sqrt(a)) / np.pi * 2**m)
num2 = round((np.pi - np.arcsin(np.sqrt(a))) / np.pi * 2**m)
if num1 != num2 and num2 < 2**m and num1 < 2**m:
counts = {format(num1, "0"+str(m)+"b"): 0.5, format(num2, "0"+str(m)+"b"): 0.5}
else:
counts = {format(num1, "0"+str(m)+"b"): 1}
return counts
def bitstring_to_a(counts, num_counting_qubits):
est_counts = {}
m = num_counting_qubits
precision = int(num_counting_qubits / (np.log2(10))) + 2
for key in counts.keys():
r = counts[key]
num = int(key,2) / (2**m)
a_est = round((np.sin(np.pi * num) )** 2, precision)
if a_est not in est_counts.keys():
est_counts[a_est] = 0
est_counts[a_est] += r
return est_counts
def a_from_s_int(s_int, num_counting_qubits):
theta = s_int * np.pi / (2**num_counting_qubits)
precision = int(num_counting_qubits / (np.log2(10))) + 2
a = round(np.sin(theta)**2, precision)
return a
################ Benchmark Loop
# Because circuit size grows significantly with num_qubits
# limit the max_qubits here ...
MAX_QUBITS=8
# Execute program with default parameters
def run(min_qubits=4, max_qubits=7, skip_qubits=1, max_circuits=3, num_shots=100, #for dm-simulator min_qubits=4 because it requires to measure atleast 2 qubits
num_state_qubits=1, # default, not exposed to users
backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None, context=None):
print(f"{benchmark_name} Benchmark Program - QSim")
# Clamp the maximum number of qubits
if max_qubits > MAX_QUBITS:
print(f"INFO: {benchmark_name} benchmark is limited to a maximum of {MAX_QUBITS} qubits.")
max_qubits = MAX_QUBITS
# validate parameters (smallest circuit is 3 qubits)
num_state_qubits = max(1, num_state_qubits)
if max_qubits < num_state_qubits + 2:
print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run")
return
min_qubits = max(max(4, min_qubits), num_state_qubits + 2) # min_qubit=4 for AE using dm-simulator
skip_qubits = max(1, skip_qubits)
#print(f"min, max, state = {min_qubits} {max_qubits} {num_state_qubits}")
# create context identifier
if context is None: context = f"{benchmark_name} Benchmark"
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_counting_qubits = int(num_qubits) - num_state_qubits - 1
counts, fidelity = analyze_and_print_result(qc, result, num_counting_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options, context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
# reset random seed
np.random.seed(0)
# as circuit width grows, the number of counting qubits is increased
num_counting_qubits = num_qubits - num_state_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2 ** (num_counting_qubits), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
if verbose:
print(f" with num_state_qubits = {num_state_qubits} num_counting_qubits = {num_counting_qubits}")
# determine range of secret strings to loop over
if 2**(num_counting_qubits) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(num_counting_qubits), num_circuits, False)
# loop over limited # of secret strings for this
for s_int in s_range:
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
a_ = a_from_s_int(s_int, num_counting_qubits)
# print("a_ ===== ", int(a_))
qc = AmplitudeEstimation(num_state_qubits, num_counting_qubits, a_).reverse_bits()
print(qc)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time() - ts)
# collapse the 3 sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose().decompose().decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, s_int, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nControlled Quantum Operator 'cQ' ="); print(cQ_ if cQ_ != None else " ... too large!")
print("\nQuantum Operator 'Q' ="); print(Q_ if Q_ != None else " ... too large!")
print("\nAmplitude Generator 'A' ="); print(A_ if A_ != None else " ... too large!")
print("\nInverse QFT Circuit ="); print(QFTI_ if QC_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim")
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# (1) Run this cell for obtaining the suitable Grover's operator for the defined satisfiability problem
from sat_circuits_engine import SATInterface
# Defining constraints and varibales in a high-level fashion
high_level_constraints_string = (
"(x0 != x1)," \
"(x3 != x4)," \
"(x1 != x3)," \
"(x3 != x5)," \
"(x5 != x6)," \
"(x0 != x2)," \
"(x1 != x6)," \
"(x4 != x6)"
)
high_level_vars = {"x0": 1, "x1": 1, "x2": 1, "x3": 2, "x4": 1, "x5": 1, "x6": 1}
# Initialization of the interface, `save_data=True` for exporting data into a dedicated directory
demo_1 = SATInterface(
high_level_constraints_string=high_level_constraints_string,
high_level_vars=high_level_vars,
name="demo_1",
save_data=True
)
# `obtain_grover_operator()` returns a dictionary of the form: `{
# 'operator': QC_OBJ,
# 'decomposed_operator': QC_OBJ,
# 'transpiled_operator': QC_OBJ,
# 'high_level_to_bit_indexes_map': MAP_OBJ
# }`.
# Transpilation is done according to the `transpile_kwargs` arg, which by default is set to:
# {'basis_gates': ['u', 'cx'], 'optimization_level': 3}.
grover_operator_data = demo_1.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
demo_1.save_display_grover_operator(grover_operator_data, display=True)
# (2) Run this cell for obtaining the overall SAT circuit:
# A `QuantumCircuit` object that solves the satisfiability problem, ready for execution on a backend.
from qiskit_aer import AerSimulator
# The number of iterations over Grover's iterator (= operator + diffuser) depends on the number of solutions.
# If the number of solutions is known, it is best to provide it.
# If the number of solutions is unknown, `solutions_num=-1` will initiate an classical
# iterative stochastic process that looks for an adequate number of iterations for the problem.
# Needless to mention, this process add some computational overheads.
# `solutions_num=-2` will generate a dynamic circuit to overcome the need for providing the number of solutions.
# NOTE - this is a BETA feature which is currently under development. For now it failes
# to scale and works properly only for small circuits (~ < 15 qubits).
overall_circuit_data = demo_1.obtain_overall_sat_circuit(
grover_operator=grover_operator_data['operator'],
solutions_num=6,
backend=AerSimulator()
)
demo_1.save_display_overall_circuit(overall_circuit_data, display=True)
# (3) Run this cell for executing the overall SAT circuit and obtaining the results.
results_data = demo_1.run_overall_sat_circuit(
circuit=overall_circuit_data['circuit'],
backend=AerSimulator(),
shots=300
)
demo_1.save_display_results(results_data, display=True)
# (1) Run this cell to obtain Grover's operator for the defined constraints
from sat_circuits_engine import SATInterface
# Initialization of the interface, `save_data=False` = not saving and exporting data
demo_2 = SATInterface(
constraints_string="([4][3][2] == [0]),([2] == [3]),([3] == [4]),([0] != [1]),([8][7] == [3][2])",
num_input_qubits=9,
name="demo_2",
save_data=False
)
# Obtaining Grover's operator objects
grover_operator_data = demo_2.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
operator = grover_operator_data['operator']
decomposed_operator = grover_operator_data['decomposed_operator']
transpiled_operator = grover_operator_data['transpiled_operator']
# Displaying results
print("The high level operator circuit diagram:")
display(operator.draw('mpl', fold=-1))
print("The decomposed operator circuit diagram:")
display(decomposed_operator.draw('mpl', fold=-1))
print(f"Gates count in the transpiled operator: {transpiled_operator.count_ops()}")
# Run this cell to initiate an interactive user interface
from sat_circuits_engine import SATInterface
SATInterface()
# (1) Run this cell for obtaining the suitable Grover's operator for the defined satisfiability problem
from sat_circuits_engine import SATInterface
# Defining constraints and varibales in a high-level fashion
high_level_constraints_string = (
"(x0 != x1)," \
"(x2 + 2 != x3)," \
"(x3 != x4)," \
"(x3 != x1)," \
"(x5 != x6)," \
"(x0 != x2)," \
"(x1 != x5)," \
"(x4 != x6)," \
"(x3 == 2)," \
"(x2 + x4 + x3 == 3)"
)
high_level_vars = {"x0": 1, "x1": 1, "x2": 1, "x3": 2, "x4": 1, "x5": 1, "x6": 1}
# Initialization of the interface, `save_data=True` for exporting data into a dedicated directory
benchmark_demo = SATInterface(
high_level_constraints_string=high_level_constraints_string,
high_level_vars=high_level_vars,
name="benchmark_demo",
save_data=True
)
grover_operator_data = benchmark_demo.obtain_grover_operator(
transpile_kwargs={'basis_gates': ['u', 'cx'], 'optimization_level': 3}
)
benchmark_demo.save_display_grover_operator(grover_operator_data, display=True)
# (2) Run this cell for obtaining the overall SAT circuit:
# a `QuantumCircuit` object that solves the satisfiability problem, ready for execution on a backend.
from qiskit_aer import AerSimulator
overall_circuit_data = benchmark_demo.obtain_overall_sat_circuit(
grover_operator=grover_operator_data['operator'],
solutions_num=1,
backend=AerSimulator()
)
benchmark_demo.save_display_overall_circuit(overall_circuit_data, display=True)
# (3) Run this cell for executing the overall SAT circuit and obtaining the results.
# WARNING: this specific circuit is heavy for a classical computer to simualte, it might take a while.
results_data = benchmark_demo.run_overall_sat_circuit(
circuit=overall_circuit_data['circuit'],
backend=AerSimulator(),
shots=50
)
benchmark_demo.save_display_results(results_data, display=True)
from sat_circuits_engine import SATInterface
SATInterface()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 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.
"""CircuitStateFn Class"""
from typing import Dict, List, Optional, Set, Union, cast
import numpy as np
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, transpile
from qiskit.circuit import Instruction, ParameterExpression
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.library import IGate, StatePreparation
from qiskit.opflow.exceptions import OpflowError
from qiskit.opflow.list_ops.composed_op import ComposedOp
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.list_ops.summed_op import SummedOp
from qiskit.opflow.list_ops.tensored_op import TensoredOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops.circuit_op import CircuitOp
from qiskit.opflow.primitive_ops.matrix_op import MatrixOp
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn
from qiskit.quantum_info import Statevector
from qiskit.utils.deprecation import deprecate_func
class CircuitStateFn(StateFn):
r"""
Deprecated: A class for state functions and measurements which are defined by the action of a
QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class.
"""
primitive: QuantumCircuit
# TODO allow normalization somehow?
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
primitive: Union[QuantumCircuit, Instruction] = None,
coeff: Union[complex, ParameterExpression] = 1.0,
is_measurement: bool = False,
from_operator: bool = False,
) -> None:
"""
Args:
primitive: The ``QuantumCircuit`` (or ``Instruction``, which will be converted) which
defines the behavior of the underlying function.
coeff: A coefficient multiplying the state function.
is_measurement: Whether the StateFn is a measurement operator.
from_operator: if True the StateFn is derived from OperatorStateFn. (Default: False)
Raises:
TypeError: Unsupported primitive, or primitive has ClassicalRegisters.
"""
if isinstance(primitive, Instruction):
qc = QuantumCircuit(primitive.num_qubits)
qc.append(primitive, qargs=range(primitive.num_qubits))
primitive = qc
if not isinstance(primitive, QuantumCircuit):
raise TypeError(
"CircuitStateFn can only be instantiated "
"with QuantumCircuit, not {}".format(type(primitive))
)
if len(primitive.clbits) != 0:
raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.")
super().__init__(primitive, coeff=coeff, is_measurement=is_measurement)
self.from_operator = from_operator
@staticmethod
def from_dict(density_dict: dict) -> "CircuitStateFn":
"""Construct the CircuitStateFn from a dict mapping strings to probability densities.
Args:
density_dict: The dict representing the desired state.
Returns:
The CircuitStateFn created from the dict.
"""
# If the dict is sparse (elements <= qubits), don't go
# building a statevector to pass to Qiskit's
# initializer, just create a sum.
if len(density_dict) <= len(list(density_dict.keys())[0]):
statefn_circuits = []
for bstr, prob in density_dict.items():
qc = QuantumCircuit(len(bstr))
# NOTE: Reversing endianness!!
for (index, bit) in enumerate(reversed(bstr)):
if bit == "1":
qc.x(index)
sf_circuit = CircuitStateFn(qc, coeff=prob)
statefn_circuits += [sf_circuit]
if len(statefn_circuits) == 1:
return statefn_circuits[0]
else:
return cast(CircuitStateFn, SummedOp(cast(List[OperatorBase], statefn_circuits)))
else:
sf_dict = StateFn(density_dict)
return CircuitStateFn.from_vector(sf_dict.to_matrix())
@staticmethod
def from_vector(statevector: np.ndarray) -> "CircuitStateFn":
"""Construct the CircuitStateFn from a vector representing the statevector.
Args:
statevector: The statevector representing the desired state.
Returns:
The CircuitStateFn created from the vector.
"""
normalization_coeff = np.linalg.norm(statevector)
normalized_sv = statevector / normalization_coeff
return CircuitStateFn(StatePreparation(normalized_sv), coeff=normalization_coeff)
def primitive_strings(self) -> Set[str]:
return {"QuantumCircuit"}
@property
def settings(self) -> Dict:
"""Return settings."""
data = super().settings
data["from_operator"] = self.from_operator
return data
@property
def num_qubits(self) -> int:
return self.primitive.num_qubits
def add(self, other: OperatorBase) -> OperatorBase:
if not self.num_qubits == other.num_qubits:
raise ValueError(
"Sum over operators with different numbers of qubits, "
"{} and {}, is not well "
"defined".format(self.num_qubits, other.num_qubits)
)
if isinstance(other, CircuitStateFn) and self.primitive == other.primitive:
return CircuitStateFn(self.primitive, coeff=self.coeff + other.coeff)
# Covers all else.
return SummedOp([self, other])
def adjoint(self) -> "CircuitStateFn":
try:
inverse = self.primitive.inverse()
except CircuitError as missing_inverse:
raise OpflowError(
"Failed to take the inverse of the underlying circuit, the circuit "
"is likely not unitary and can therefore not be inverted."
) from missing_inverse
return CircuitStateFn(
inverse, coeff=self.coeff.conjugate(), is_measurement=(not self.is_measurement)
)
def compose(
self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False
) -> OperatorBase:
if not self.is_measurement and not front:
raise ValueError(
"Composition with a Statefunctions in the first operand is not defined."
)
new_self, other = self._expand_shorter_operator_and_permute(other, permutation)
new_self.from_operator = self.from_operator
if front:
return other.compose(new_self)
if isinstance(other, (PauliOp, CircuitOp, MatrixOp)):
op_circuit_self = CircuitOp(self.primitive)
# Avoid reimplementing compose logic
composed_op_circs = cast(CircuitOp, op_circuit_self.compose(other.to_circuit_op()))
# Returning CircuitStateFn
return CircuitStateFn(
composed_op_circs.primitive,
is_measurement=self.is_measurement,
coeff=self.coeff * other.coeff,
from_operator=self.from_operator,
)
if isinstance(other, CircuitStateFn) and self.is_measurement:
# pylint: disable=cyclic-import
from ..operator_globals import Zero
return self.compose(CircuitOp(other.primitive)).compose(
(Zero ^ self.num_qubits) * other.coeff
)
return ComposedOp([new_self, other])
def tensor(self, other: OperatorBase) -> Union["CircuitStateFn", TensoredOp]:
r"""
Return tensor product between self and other, overloaded by ``^``.
Note: You must be conscious of Qiskit's big-endian bit printing convention.
Meaning, Plus.tensor(Zero)
produces a \|+⟩ on qubit 0 and a \|0⟩ on qubit 1, or \|+⟩⨂\|0⟩, but would produce
a QuantumCircuit like:
\|0⟩--
\|+⟩--
Because Terra prints circuits and results with qubit 0 at the end of the string or circuit.
Args:
other: The ``OperatorBase`` to tensor product with self.
Returns:
An ``OperatorBase`` equivalent to the tensor product of self and other.
"""
if isinstance(other, CircuitStateFn) and other.is_measurement == self.is_measurement:
# Avoid reimplementing tensor, just use CircuitOp's
c_op_self = CircuitOp(self.primitive, self.coeff)
c_op_other = CircuitOp(other.primitive, other.coeff)
c_op = c_op_self.tensor(c_op_other)
if isinstance(c_op, CircuitOp):
return CircuitStateFn(
primitive=c_op.primitive,
coeff=c_op.coeff,
is_measurement=self.is_measurement,
)
return TensoredOp([self, other])
def to_density_matrix(self, massive: bool = False) -> np.ndarray:
"""
Return numpy matrix of density operator, warn if more than 16 qubits to
force the user to set
massive=True if they want such a large matrix. Generally big methods like this
should require the use of a
converter, but in this case a convenience method for quick hacking and access
to classical tools is
appropriate.
"""
OperatorBase._check_massive("to_density_matrix", True, self.num_qubits, massive)
# Rely on VectorStateFn's logic here.
return VectorStateFn(self.to_matrix(massive=massive) * self.coeff).to_density_matrix()
def to_matrix(self, massive: bool = False) -> np.ndarray:
OperatorBase._check_massive("to_matrix", False, self.num_qubits, massive)
# Need to adjoint to get forward statevector and then reverse
if self.is_measurement:
return np.conj(self.adjoint().to_matrix(massive=massive))
qc = self.to_circuit(meas=False)
statevector_backend = BasicAer.get_backend("statevector_simulator")
transpiled = transpile(qc, statevector_backend, optimization_level=0)
statevector = statevector_backend.run(transpiled).result().get_statevector()
from ..operator_globals import EVAL_SIG_DIGITS
return np.round(statevector * self.coeff, decimals=EVAL_SIG_DIGITS)
def __str__(self) -> str:
qc = cast(CircuitStateFn, self.reduce()).to_circuit()
prim_str = str(qc.draw(output="text"))
if self.coeff == 1.0:
return "{}(\n{}\n)".format(
"CircuitStateFn" if not self.is_measurement else "CircuitMeasurement", prim_str
)
else:
return "{}(\n{}\n) * {}".format(
"CircuitStateFn" if not self.is_measurement else "CircuitMeasurement",
prim_str,
self.coeff,
)
def assign_parameters(self, param_dict: dict) -> Union["CircuitStateFn", ListOp]:
param_value = self.coeff
qc = self.primitive
if isinstance(self.coeff, ParameterExpression) or self.primitive.parameters:
unrolled_dict = self._unroll_param_dict(param_dict)
if isinstance(unrolled_dict, list):
return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict])
if isinstance(self.coeff, ParameterExpression) and self.coeff.parameters <= set(
unrolled_dict.keys()
):
param_instersection = set(unrolled_dict.keys()) & self.coeff.parameters
binds = {param: unrolled_dict[param] for param in param_instersection}
param_value = float(self.coeff.bind(binds))
# & is set intersection, check if any parameters in unrolled are present in circuit
# This is different from bind_parameters in Terra because they check for set equality
if set(unrolled_dict.keys()) & self.primitive.parameters:
# Only bind the params found in the circuit
param_instersection = set(unrolled_dict.keys()) & self.primitive.parameters
binds = {param: unrolled_dict[param] for param in param_instersection}
qc = self.to_circuit().assign_parameters(binds)
return self.__class__(qc, coeff=param_value, is_measurement=self.is_measurement)
def eval(
self,
front: Optional[
Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector]
] = None,
) -> Union[OperatorBase, complex]:
if front is None:
vector_state_fn = self.to_matrix_op().eval()
return vector_state_fn
if not self.is_measurement and isinstance(front, OperatorBase):
raise ValueError(
"Cannot compute overlap with StateFn or Operator if not Measurement. Try taking "
"sf.adjoint() first to convert to measurement."
)
if isinstance(front, ListOp) and front.distributive:
return front.combo_fn(
[self.eval(front.coeff * front_elem) for front_elem in front.oplist]
)
# Composable with circuit
if isinstance(front, (PauliOp, CircuitOp, MatrixOp, CircuitStateFn)):
new_front = self.compose(front)
return new_front.eval()
return self.to_matrix_op().eval(front)
def to_circuit(self, meas: bool = False) -> QuantumCircuit:
"""Return QuantumCircuit representing StateFn"""
if meas:
meas_qc = self.primitive.copy()
meas_qc.add_register(ClassicalRegister(self.num_qubits))
meas_qc.measure(qubit=range(self.num_qubits), cbit=range(self.num_qubits))
return meas_qc
else:
return self.primitive
def to_circuit_op(self) -> OperatorBase:
"""Return ``StateFnCircuit`` corresponding to this StateFn."""
return self
def to_instruction(self):
"""Return Instruction corresponding to primitive."""
return self.primitive.to_instruction()
# TODO specify backend?
def sample(
self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False
) -> dict:
"""
Sample the state function as a normalized probability distribution. Returns dict of
bitstrings in order of probability, with values being probability.
"""
OperatorBase._check_massive("sample", False, self.num_qubits, massive)
qc = self.to_circuit(meas=True)
qasm_backend = BasicAer.get_backend("qasm_simulator")
transpiled = transpile(qc, qasm_backend, optimization_level=0)
counts = qasm_backend.run(transpiled, shots=shots).result().get_counts()
if reverse_endianness:
scaled_dict = {bstr[::-1]: (prob / shots) for (bstr, prob) in counts.items()}
else:
scaled_dict = {bstr: (prob / shots) for (bstr, prob) in counts.items()}
return dict(sorted(scaled_dict.items(), key=lambda x: x[1], reverse=True))
# Warning - modifying primitive!!
def reduce(self) -> "CircuitStateFn":
if self.primitive.data is not None:
# Need to do this from the end because we're deleting items!
for i in reversed(range(len(self.primitive.data))):
gate = self.primitive.data[i].operation
# Check if Identity or empty instruction (need to check that type is exactly
# Instruction because some gates have lazy gate.definition population)
# pylint: disable=unidiomatic-typecheck
if isinstance(gate, IGate) or (
type(gate) == Instruction and gate.definition.data == []
):
del self.primitive.data[i]
return self
def _expand_dim(self, num_qubits: int) -> "CircuitStateFn":
# this is equivalent to self.tensor(identity_operator), but optimized for better performance
# just like in tensor method, qiskit endianness is reversed here
return self.permute(list(range(num_qubits, num_qubits + self.num_qubits)))
def permute(self, permutation: List[int]) -> "CircuitStateFn":
r"""
Permute the qubits of the circuit.
Args:
permutation: A list defining where each qubit should be permuted. The qubit at index
j of the circuit should be permuted to position permutation[j].
Returns:
A new CircuitStateFn containing the permuted circuit.
"""
new_qc = QuantumCircuit(max(permutation) + 1).compose(self.primitive, qubits=permutation)
return CircuitStateFn(new_qc, coeff=self.coeff, is_measurement=self.is_measurement)
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
import numpy as np
###########################################
# Amplitude damping channel on IBMQ_VIGO #
###########################################
# Quantum register
q = QuantumRegister(5, name='q')
# Quantum circuit
ad = QuantumCircuit(q)
# Amplitude damping channel acting on system qubit
## Qubit identification
system = 1
environment = 2
# Define rotation angle
theta = 0.0
# Construct circuit
ad.x(q[system])
# Notice the extra factor 2 due to how qiskit defines the unitary angles
ad.cu(theta, 0.0, 0.0, 0.0, q[system], q[environment])
ad.cx(q[environment], q[system])
# Draw circuit
ad.draw(output='mpl')
def c1(R,t):
"""Returns the coherence factor in the amplitude damping channel
Args:
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A float number
"""
def amplitude_damping_channel(q, c, sys, env, R, t):
"""Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system qubit
sys (int): index for the system qubit
env (int): index for the environment qubit
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A QuantumCircuit object
"""
#######################################
# Amplitude damping channel #
# with non-M. witness on IBMQ_VIGO #
#######################################
# Quantum and classical register
q = QuantumRegister(5, name='q')
c = ClassicalRegister(2, name='c')
# Quantum circuit
ad = QuantumCircuit(q, c)
# Amplitude damping channel acting on system qubit
# with non-Markovianity witness
## Qubit identification
system = 1
environment = 2
ancilla = 3
# Define rotation angle
theta = 0.0
# Construct circuit
## Bell state between system and ancilla
ad.h(q[system])
ad.cx(q[system], q[ancilla])
## Channel acting on system qubit
ad.cu3(theta, 0.0, 0.0, q[system], q[environment])
ad.cx(q[environment], q[system])
## Local measurement for the witness
### Choose observable
observable = 'YY'
### Change to the corresponding basis
if observable == 'XX':
ad.h(q[system])
ad.h(q[ancilla])
elif observable == 'YY':
ad.sdg(q[system])
ad.h(q[system])
ad.sdg(q[ancilla])
ad.h(q[ancilla])
### Measure
ad.measure(q[system], c[0])
ad.measure(q[ancilla], c[1])
# Draw circuit
ad.draw(output='mpl')
def amplitude_damping_channel_witness(q, c, sys, env, anc, observable, R, t):
"""Returns a QuantumCircuit implementing the amplitude damping channel on the system qubit with non-Markovianity witness
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system and ancilla qubits
sys (int): index for the system qubit
env (int): index for the environment qubit
anc (int): index for the ancillary qubit
observable (str): the observable to be measured. Possible values "XX", "YY", "ZZ"
R (float): value of R = \gamma_0/\lambda
t (float): value of the time variable
Returns:
A QuantumCircuit object
"""
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.applications.vertex_cover import VertexCover
import networkx as nx
seed = 123
algorithm_globals.random_seed = seed
graph = nx.random_regular_graph(d=3, n=6, seed=seed)
pos = nx.spring_layout(graph, seed=seed)
prob = VertexCover(graph)
prob.draw(pos=pos)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# Numpy Eigensolver
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
prob.draw(result, pos=pos)
# QAOA
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA()))
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
print("\ntime:", result.min_eigen_solver_result.optimizer_time)
prob.draw(result, pos=pos)
from qiskit_optimization.applications import Knapsack
prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# Numpy Eigensolver
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
# QAOA
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA()))
result = meo.solve(qp)
print(result.prettyprint())
print("\nsolution:", prob.interpret(result))
print("\ntime:", result.min_eigen_solver_result.optimizer_time)
from qiskit_optimization.converters import QuadraticProgramToQubo
# the same knapsack problem instance as in the previous section
prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10)
qp = prob.to_quadratic_program()
print(qp.prettyprint())
# intermediate QUBO form of the optimization problem
conv = QuadraticProgramToQubo()
qubo = conv.convert(qp)
print(qubo.prettyprint())
# qubit Hamiltonian and offset
op, offset = qubo.to_ising()
print(f"num qubits: {op.num_qubits}, offset: {offset}\n")
print(op)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
def digit_sum(n):
num_str = str(n)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
return sum
# CZ (Controlled-Z)
# control qubit: q0
# target qubit: q1
def CZ(qp,q0,q1):
qp.h(q1)
qp.cx(q0,q1)
qp.h(q1)
# f-SWAP
# taking into account the one-directionality of CNOT gates in the available devices
def fSWAP(qp,q0,q1):
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
CZ(qp,q0,q1)
# CH (Controlled-Haddamard)
# control qubit: q1
# target qubit: q0
def CH2(qp,q0,q1):
qp.sdg(q0)
qp.h(q0)
qp.tdg(q0)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.t(q0)
qp.h(q0)
qp.s(q0)
# Fourier transform gates
def F2(qp,q0,q1):
qp.cx(q0,q1)
CH2(qp,q0,q1)
qp.cx(q0,q1)
CZ(qp,q0,q1)
def F0(qp,q0,q1):
F2(qp,q0,q1)
def F1(qp,q0,q1):
F2(qp,q0,q1)
qp.sdg(q0)
from math import pi
# ROTATIONAL GATES
def RZ(qp,th,q0):
qp.u1(-th,q0)
def RY(qp,th,q0):
qp.u3(th,0.,0.,q0)
def RX(qp,th,q0):
qp.u3(th,0.,pi,q0)
# CRX (Controlled-RX)
# control qubit: q0
# target qubit: q1
def CRX(qp,th,q0,q1):
RZ(qp,pi/2.0,q1)
RY(qp,th/2.0,q1)
qp.cx(q0,q1)
RY(qp,-th/2.0,q1)
qp.cx(q0,q1)
RZ(qp,-pi/2.0,q1)
# Bogoliubov B_1
def B(qp,thk,q0,q1):
qp.x(q1)
qp.cx(q1,q0)
CRX(qp,thk,q0,q1)
qp.cx(q1,q0)
qp.x(q1)
# This circuit can be implemented in ibmqx5 using qubits (q0,q1,q2,q3)=(6,7,11,10)
# It can also be implemented between other qubits or in ibqmx2 and ibqmx4 using fermionic SWAPS
# For instance, the lines commented correspond to the implementations:
# ibmqx2 (q0,q1,q2,q3)=(4,2,0,1)
# ibmqx4 (q0,q1,q2,q3)=(3,2,1,0)
def Udisg(qc,lam,q0,q1,q2,q3):
k=1
n=4
th1=-np.arccos((lam-np.cos(2*pi*k/n))/np.sqrt((lam-np.cos(2*pi*k/n))**2+np.sin(2*pi*k/n)**2))
B(Udis,th1,q0,q1)
F1(Udis,q0,q1)
F0(Udis,q2,q3)
#fSWAP(Udis,q2,q1) # for ibmqx2
#fSWAP(Udis,q1,q2) # for ibmqx4
F0(Udis,q0,q2)
F0(Udis,q1,q3)
#fSWAP(Udis,q2,q1) # for ibmqx2
#fSWAP(Udis,q1,q2) # for ibmqx4
def Initial(qc,lam,q0,q1,q2,q3):
if lam <1:
qc.x(q3)
def Ising(qc,ini,udis,mes,lam,q0,q1,q2,q3,c0,c1,c2,c3):
Initial(ini,lam,q0,q1,q2,q3)
Udisg(udis,lam,q0,q1,q2,q3)
mes.measure(q0,c0)
mes.measure(q1,c1)
mes.measure(q2,c2)
mes.measure(q3,c3)
qc.add_circuit("Ising",ini+udis+mes)
#import sys
#sys.path.append("../../")
# importing the QISKit
from qiskit import QuantumCircuit,QuantumProgram
#import Qconfig
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from scipy import linalg as la
# Simulator
shots = 1024
backend ='ibmqx_qasm_simulator'
coupling_map = None
mag_sim = []
for i in range(8):
Isex = QuantumProgram()
q = Isex.create_quantum_register("q",4)
c = Isex.create_classical_register("c", 4)
Udis = Isex.create_circuit("Udis", [q], [c])
ini = Isex.create_circuit("ini",[q],[c])
mes = Isex.create_circuit("mes",[q],[c])
lam=i*0.25
Ising(Isex,ini,Udis,mes,lam,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3])
# Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
result = Isex.execute(["Ising"], backend=backend,
coupling_map=coupling_map, shots=shots,timeout=240000)
res=result.get_counts("Ising")
r1=list(res.keys())
r2=list(res.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag_sim.append(M/4)
# Real device
shots = 1024
#backend ='ibmqx5'
max_credits = 5
mag=[]
for i in range(8):
Isex = QuantumProgram()
q = Isex.create_quantum_register("q",12)
c = Isex.create_classical_register("c", 4)
Udis = Isex.create_circuit("Udis", [q], [c])
ini = Isex.create_circuit("ini",[q],[c])
mes = Isex.create_circuit("mes",[q],[c])
lam=i*0.25
Ising(Isex,ini,Udis,mes,lam,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3])
# Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
result = Isex.execute(["Ising"], backend=backend,
max_credits=max_credits, wait=10, shots=shots,timeout=240000)
res=result.get_counts("Ising")
r1=list(res.keys())
r2=list(res.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag.append(M/4)
# As it is a system of only 4 particles, we can easily compute the exact result
def exact(lam):
if lam <1:
return lam/(2*np.sqrt(1+lam**2))
if lam >1:
return 1/2+lam/(2*np.sqrt(1+lam**2))
return None
vexact = np.vectorize(exact)
l=np.arange(0.0,2.0,0.01)
l1=np.arange(0.0,2.0,0.25)
plt.figure(figsize=(9,5))
plt.plot(l,vexact(l),'k',label='exact')
plt.plot(l1, mag_sim, 'bo',label='simulation')
plt.plot(l1, mag, 'r*',label='ibmqx5')
plt.xlabel('$\lambda$')
plt.ylabel('$<\sigma_{z}>$')
plt.legend()
plt.title('Magnetization of the ground state of n=4 Ising spin chain')
plt.show()
#This was the result when the real device is used:
def Initial_time(qc,t,lam,q0,q1,q2,q3):
qc.u3(np.arccos(lam/np.sqrt(1+lam**2)),pi/2.+4*t*np.sqrt(1+lam**2),0.,q0)
qc.cx(q0,q1)
def Ising_time(qc,ini,udis,mes,lam,t,q0,q1,q2,q3,c0,c1,c2,c3):
Initial_time(ini,t,lam,q0,q1,q2,q3)
Udisg(udis,lam,q0,q1,q2,q3)
mes.measure(q0,c0)
mes.measure(q1,c1)
mes.measure(q2,c2)
mes.measure(q3,c3)
qc.add_circuit("Ising_time",ini+udis+mes)
#Simulation
shots = 1024
backend = 'ibmqx_qasm_simulator'
coupling_map = None
# We compute the time evolution for lambda=0.5,0.9 and 1.8
nlam=3
magt_sim=[[] for _ in range(nlam)]
lam0=[0.5,0.9,1.8]
for j in range(nlam):
lam=lam0[j]
for i in range(9):
Isex_time = QuantumProgram()
q = Isex_time.create_quantum_register("q",4)
c = Isex_time.create_classical_register("c", 4)
Udis = Isex_time.create_circuit("Udis", [q], [c])
ini = Isex_time.create_circuit("ini",[q],[c])
mes = Isex_time.create_circuit("mes",[q],[c])
t=i*0.25
Ising_time(Isex_time,ini,Udis,mes,lam,t,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3])
Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"])
result = Isex_time.execute(["Ising_time"], backend=backend,
coupling_map=coupling_map, shots=shots,timeout=240000)
res=result.get_counts("Ising_time")
r1=list(res.keys())
r2=list(res.values())
M=0
for k in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots
magt_sim[j].append(M/4)
shots = 1024
backend = 'ibmqx5'
max_credits = 5
# We compute the time evolution for lambda=0.5,0.9 and 1.8
nlam=3
magt=[[] for _ in range(nlam)]
lam0=[0.5,0.9,1.8]
for j in range(nlam):
lam=lam0[j]
for i in range(9):
Isex_time = QuantumProgram()
q = Isex_time.create_quantum_register("q",12)
c = Isex_time.create_classical_register("c", 4)
Udis = Isex_time.create_circuit("Udis", [q], [c])
ini = Isex_time.create_circuit("ini",[q],[c])
mes = Isex_time.create_circuit("mes",[q],[c])
t=i*0.25
Ising_time(Isex_time,ini,Udis,mes,lam,t,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3])
Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"])
result = Isex_time.execute(["Ising_time"], backend=backend,
max_credits=max_credits, wait=10, shots=shots,timeout=240000)
res=result.get_counts("Ising_time")
r1=list(res.keys())
r2=list(res.values())
M=0
for k in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots
magt[j].append(M/4)
def exact_time(lam,tt):
Mt=(1 + 2*lam**2 + np.cos(4*tt*np.sqrt(1 + lam**2)))/(2 + 2*lam**2)
return Mt
vexact_t = np.vectorize(exact_time)
t=np.arange(0.0,2.0,0.01)
tt=np.arange(0.0,2.25,0.25)
plt.figure(figsize=(10,5))
plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$')
plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$')
plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$')
#plt.plot(tt, magt_sim[0], 'bo',label='simulation')
#plt.plot(tt, magt_sim[1], 'ro')
#plt.plot(tt, magt_sim[2], 'go')
plt.plot(tt, magt[0], 'b*',label='ibmqx5')
plt.plot(tt, magt[1], 'r*')
plt.plot(tt, magt[2], 'g*')
plt.plot(tt, magt[0], 'b--')
plt.plot(tt, magt[1], 'r--')
plt.plot(tt, magt[2], 'g--')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.legend()
plt.title('Time evolution |↑↑↑↑> state')
plt.show()
plt.figure(figsize=(13,3))
plt.subplot(1,3,1)
plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$')
plt.plot(tt, magt[0], 'b*',label='ibmqx5')
plt.plot(tt, magt[0], 'b--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=0.5$')
plt.subplot(132)
plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$')
plt.plot(tt, magt[1], 'r*',label='ibmqx5')
plt.plot(tt, magt[1], 'r--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=0.9$')
plt.subplot(133)
plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$')
plt.plot(tt, magt[2], 'g*',label='ibmqx5')
plt.plot(tt, magt[2], 'g--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=1.8$')
plt.tight_layout()
plt.show()
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 19:13:26 2023
@author: abdullahalshihry
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 19:15:12 2023
@author: abdullahalshihry
"""
import qiskit as qs
import qiskit.visualization as qv
import random
import qiskit.circuit as qf
def Deutsch_Jozsa(circuit):
qr = qs.QuantumRegister(5,'q')
cr = qs.ClassicalRegister(4,'c')
qc = qs.QuantumCircuit(qr,cr)
qc.x(qr[4])
qc.barrier(range(5))
qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])
qc.h(qr[4])
qc.barrier(range(5))
qc = qc.compose(circuit)
qc.barrier(range(5))
qc.h(qr[0])
qc.h(qr[1])
qc.h(qr[2])
qc.h(qr[3])
qc.barrier(range(5))
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024)
output1 = job1.result().get_counts()
print(output1)
qc.draw('mpl')
def Oracle():
qr = qs.QuantumRegister(5,'q')
cr = qs.ClassicalRegister(4,'c')
qc = qs.QuantumCircuit(qr,cr)
qq = qs.QuantumCircuit(5,name='Uf')
v = random.randint(1, 2)
if v == 1:
qc.cx(0,4)
qc.cx(1,4)
qc.cx(2,4)
qc.cx(3,4)
print('Balanced (1)')
elif v == 2:
qq.i(qr[0])
qq.i(qr[1])
qq.i(qr[2])
qq.i(qr[3])
print('Constant (0)')
qq =qq.to_gate()
qc.append(qq,[0,1,2,3,4])
return qc
Deutsch_Jozsa(Oracle())
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn import datasets
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
X_train, Y_train = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4)
X_test, Y_test = datasets.make_circles(n_samples=50, noise=0.09, factor=0.4)
print('Training Data:')
print(X_train[:10])
print('\nTraining Label:')
print(Y_train[:10])
plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train)
plt.show()
print(f'Total datas: {len(X_train)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5
temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1))
temp[:, :-1] = X_train
temp[:, -1] = Z_train
X_train2 = temp
Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5
temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1))
temp[:, :-1] = X_test
temp[:, -1] = Z_test
X_test2 = temp
print('Solved Training Data:')
print(X_train2[:10])
def plot3D(X, Y):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(
X[:, 0], X[:, 1], X[:, 2],
zdir='z', s=30, c=Y, depthshade=True
)
plt.show()
plot3D(X_train2, Y_train)
print(f'Total datas: {len(X_train2)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
qubits_num = 3
layers_num = 2
dev = qml.device("default.qubit", wires=qubits_num)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
self.params = (0.05 * np.random.randn(layers_num, qubits_num, 3))
params = [-1.18991246e-01, -8.69694713e-01, 1.43722811e-03]
self.params = [
[params, [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00], [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
[params, [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00], [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
]
self.params = [
[-0.09117728, -1.11137259, -1.33992893, -1.49234722, -1.64223525,
-1.63931865, -1.75914568, -1.78395664, -1.64893105],
(0.05 * np.random.randn(1, 9))[0]
]
self.bestparams = self.params
self.bestcost = 10
self.opt = AdamOptimizer(0.1)
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, epoch=300):
batch_size = 20
for turn in range(epoch):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn + 1, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *params[0, i], wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[0, 2])
for i in range(qubits_num):
qml.Rot( *params[1, i], wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
import qiskit
import numpy as np
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
vqc = VQC()
vqc = VQC()
vqc.fit(X_train2, Y_train, epoch=50)
vqc.bestparams = [[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03],
[ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00],
[ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
[[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03],
[-1.71552299e-02, 2.46283604e-03, -1.03805722e-02],
[-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]]
print(cost(vqc.bestparams, X_train2, Y_train))
print(cost(vqc.bestparams, X_test2, Y_test))
vqc.score(X_test2, Y_test)
def createCircuit(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
qcircuit = createCircuit(vqc.bestparams, X_train2[0])
qcircuit.draw(output='mpl')
def measure(qcircuit, label):
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
print(f'simulation results: \n{counts}')
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots
print(f'p1: {p1}')
print(f'Expected label: {label}')
example = [0, 30, 35, 70]
for index in example:
qcircuit = createCircuit(vqc.bestparams, X_train2[index])
measure(qcircuit, Y_train[index])
print()
# origin data
plt.scatter(X_train2[:, 0], X_train2[:, 1], c=Y_train)
plt.show()
predictions = [ predict(vqc.bestparams, data) for data in X_test2 ]
Y_ = [ Y_test[i] if Y_test[i] == predictions[i] else 2 for i in range(len(Y_test)) ]
plt.scatter(X_test2[:, 0], X_test2[:, 1], c=Y_)
plt.show()
print(X_train2[9])
print(Y_train[9])
print(X_train2[7])
print(Y_train[7])
params = [[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03],
[ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00],
[ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
[[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03],
[-1.71552299e-02, 2.46283604e-03, -1.03805722e-02],
[-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]]
params = [[
[1.571, 1.571, 1.571],[1.571, 1.571, 1.571],[1.571, 1.571, 1.571],
],[
[1.571, 1.571, 1.571],[1.571, 1.571, 1.571],[1.571, 1.571, 1.571],
]]
def getCircuits(a, b):
circuit0 = QuantumCircuit(3, 3)
qubits = circuit0.qubits
for i, d in enumerate(X_train2[a]):
circuit0.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
circuit0.u3(*params[0][i], qubits[i])
circuit1 = QuantumCircuit(3, 3)
qubits = circuit1.qubits
for i, d in enumerate(X_train2[b]):
circuit1.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
circuit1.u3(*params[0][i], qubits[i])
return circuit0, circuit1
circuit0, circuit1 = getCircuits(12, 60)
circuit0.draw(output='mpl')
circuit1.draw(output='mpl')
from scipy.linalg import sqrtm
def D(rou, sigma):
A = rou - sigma
A_ = sqrtm( np.dot( A.conj().T, A ) )
return 0.5 * np.linalg.norm( np.trace(A_) )
from qiskit.quantum_info import DensityMatrix, Statevector
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
def getStatevector(circuit):
return Statevector(circuit).data
print(X_train2[3])
print(Y_train[3])
print(X_train2[15])
print(Y_train[15])
circuit0, circuit1 = getCircuits(3,15)
matrix_0 = getDensityMatrix(circuit0)
matrix_1 = getDensityMatrix(circuit1)
print(D(matrix_0, matrix_1))
def params_loss(params, data1, data2, label1, label2):
circuit1 = QuantumCircuit(3, 3)
qubits = circuit1.qubits
for i, d in enumerate(data1):
circuit1.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
circuit1.u3(*params[i*3: (i+1)*3], qubits[i])
circuit2 = QuantumCircuit(3, 3)
qubits = circuit2.qubits
for i, d in enumerate(data1):
circuit1.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
circuit1.u3(*params[i*3: (i+1)*3], qubits[i])
matrix_1 = getDensityMatrix(circuit1)
matrix_2 = getDensityMatrix(circuit2)
d = D(matrix_1, matrix_2)
if label1 == label2:
return d ** 2
else:
return (1 - d) ** 2
print(Y_train[10:30])
def train_params(datas, labels):
params = (0.01 * np.random.randn(1, 9))[0]
length = len(params)
momentum, s = 0, 0
alpha = 0.1
belta1 = 0.9; belta2 = 0.999
e = 1e-8
for epoch in range(40):
loss_origin = 0
derivates = np.zeros(len(params))
for t in range(10):
a, b = t, t + 10
loss_origin += params_loss(params, datas[a], datas[b], labels[a], labels[b])
for i in range(len(params)):
params[i] += 0.01
loss = 0
for t in range(10):
a, b = t, t + 10
loss += params_loss(params, datas[a], datas[b], labels[a], labels[b])
derivates[i] = (loss - loss_origin) / 0.01
grad = derivates
# Adam Optimizer
momentum = belta1 * momentum + (1 - belta1) * grad
s = belta2 * s + (1 - belta2) * (grad ** 2)
m_ = momentum / (1 - belta1 ** t)
s_ = s / (1 - belta2 ** t)
# update parameters
params = params - alpha * (m_ / ( s_ ** 0.5 + e ))
return loss_origin, params
train_params(X_train2[10:50], Y_train[10:50])
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
theta = Parameter('theta')
qc = QuantumCircuit(3)
qc.cx(0,2)
qc.cx(0,1)
qc.rx(theta,0)
qc.cx(0,1)
qc.cx(0,2)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.cx(0,2)
qc.cx(0,1)
qc.rx(theta,0)
qc.cx(0,1)
qc.cx(0,2)
qc.h(2)
qc.h(1)
qc.h(0)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from matplotlib.pyplot import bar
labels = []
L = []
for i in range(8):
labels = labels + [i+1]
L = L + [1]
# visualize the values of elements in the list
bar(labels,L)
#
# 1st step - query
#
# flip the sign of the marked element
L[3] = -1 * L[3]
# visualize the values of elements in the list
bar(labels,L)
#
# 1st step - inversion
#
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over the mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# visualize the values of elements in the list
bar(labels,L)
#
# 2nd step - query
#
# flip the sign of the marked element
L[3] = -1 * L[3]
# visualize the values of elements in the list
bar(labels,L)
#
# 2nd step - inversion
#
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# visualize the values of elements in the list
bar(labels,L)
for i in range(3):
# flip the sign of the marked element
L[3] = -1 * L[3]
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# visualize the values of elements in the list
bar(labels,L)
from matplotlib.pyplot import bar
labels = []
L = []
for i in range(16):
labels = labels + [i+1]
L = L + [1]
for i in range(20):
print((i+1),"th iteration:")
# flip the sign of the marked element
L[11] = -1 * L[11]
# print after query phase
print(L[11])
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# print after inversion phase
print(L[11])
print()
N = 8
marked = 1
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
print("mean = ",round(mean,3))
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
N = 16
marked_elements = [0,2,9]
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
for marked in marked_elements:
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
N = 16
marked_elements = range(12)
L = []
for i in range(N):
L = L + [1/(N**0.5)]
# print the elements of a given list with a given precision
def print_list(L,precision):
output = ""
for i in range(len(L)):
output = output + str(round(L[i],precision))+" "
print(output)
print_list(L,3)
for i in range(10):
print((i+1),"th iteration:")
# flip the sign of the marked element
for marked in marked_elements:
L[marked] = -1 * L[marked]
# print after query phase
print_list(L,3)
# summation of all values
sum = 0
for i in range(len(L)):
sum += L[i]
# mean of all values
mean = sum / len(L)
# reflection over mean
for i in range(len(L)):
value = L[i]
new_value = mean - (L[i]-mean)
L[i] = new_value
# calculate the length of the list
length_of_list = 0
for j in range(len(L)):
length_of_list += L[j]*L[j]
print("length of list is",round(length_of_list,3))
# print after inversion phase
print_list(L,3)
print()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests ClassicalFunction as a gate."""
import unittest
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates import XGate
from qiskit.utils.optionals import HAS_TWEEDLEDUM
if HAS_TWEEDLEDUM:
from . import examples
from qiskit.circuit.classicalfunction import classical_function as compile_classical_function
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestOracleDecomposition(QiskitTestCase):
"""Tests ClassicalFunction.decomposition."""
def test_grover_oracle(self):
"""grover_oracle.decomposition"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = QuantumCircuit(5)
quantum_circuit.append(oracle, [2, 1, 0, 3, 4])
expected = QuantumCircuit(5)
expected.append(XGate().control(4, ctrl_state="1010"), [2, 1, 0, 3, 4])
self.assertEqual(quantum_circuit.decompose(), expected)
|
https://github.com/BP-2/SimonsAlgorithm
|
BP-2
|
# importing Qiskit
from qiskit import Aer
from qiskit.providers.aer import AerSimulator
from qiskit.providers.ibmq import least_busy
from qiskit import *
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
from IPython.display import display
# This will be our bitstring key
b = input("input the bitstring key")
n = len(b)
#this is because we need double bits to act as both registers
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()
arr = []
counter = 0
while counter < n*2:
arr.append(counter)
counter += 1
print (arr)
#append the black box to the circuit
simon_circuit.append(simon_oracle(b), arr)
# 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))
display(simon_circuit.draw())
# use local simulator
sim = Aer.get_backend('qasm_simulator')
result = execute(simon_circuit, backend = sim, shots = 1024).result()
counts = result.get_counts()
print(counts)
display(plot_histogram(counts))
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
def dec2den(j,N,d):
den = [0 for k in range(0,N)]
jv = j
for k in range(0,N):
if jv >= d**(N-1-k):
den[k] = jv//(d**(N-1-k))
jv = jv - den[k]*d**(N-1-k)
return den
def den2dec(local,d):
# local = list with the local computational base state values
# d = individual qudit dimension
N = len(local)
j = 0
for k in range(0,N):
j += local[k]*d**(N-1-k)
return j # value of the global computational basis index
def dec2den_opt(j,N,d): # optimized version
den = [0 for k in range(0,N)]
if j < d:
den[N-1] = j; return den
rem = [] # list for the remainder
k = j
while k >= d:
rem.append(k%d)
k = k//d
rem.append(k%d)
for j in range(0,len(rem)):
den[N-1-j] = rem[j]
return den
import numpy as np
def swap_qudits(d,N,t,c):
# d = qudit dimension; N = No. of qudits; t = target qudit (0,...,N-1); c = control qudit (0,...,N-1)
D = d**N; swap = np.zeros((D,D), dtype=int) # set all d^2N elements to 0
for k in range (0,d**N):
localr = dec2den_opt(k,N,d) # sequence of values for the local basis
#locall = [0 for k in range(0,N)]
#for s in range(0,N):
# locall[s] = localr[s]
locall = localr.copy()
#rt = localr[t];
locall[c] = localr[t]
#rc = localr[c];
locall[t] = localr[c]
globall = den2dec(locall,d)
swap[globall,k] = 1
return swap
d=2; N=2; t=0; c=1; print(swap_qudits(d,N,t,c)) # ok
d=3; N=2; t=0; c=1; print(swap_qudits(d,N,t,c)) # ok
d=2; N=3; t=0; c=2; print(swap_qudits(d,N,t,c)) # ok
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Quadratic-depth Multicontrolled Special Unitary
"""
from typing import Union, List
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Qubit
from qiskit.circuit import Gate
from numpy import sqrt, outer
from numpy.linalg import eig
from .mcx import LinearMcx
from .util import check_u2
# pylint: disable=protected-access
class Qdmcu(Gate):
"""
Quandratic Depth Multi-Controlled Unitary
-----------------------------------------
Implements gate decomposition of a munticontrolled operator in U(2) according to
Theorem 4 of Iten et al. (2016) arXiv:1501.06911.
"""
def __init__(
self,
unitary,
num_controls,
ctrl_state: str=None
):
"""
Parameters
----------
unitary : numpy.ndarray 2 x 2 unitary matrix
controls : Either qiskit.QuantumRegister or list of qiskit.Qubit containing the
qubits to be used as control gates.
target : qiskit.Qubit on wich the unitary operation is to be applied
ctrl_state : String of binary digits describing the basis state used as control
"""
check_u2(unitary)
self.unitary = unitary
self.controls = QuantumRegister(num_controls)
self.target = QuantumRegister(1)
self.num_qubits = num_controls + 1
self.ctrl_state = ctrl_state
super().__init__("qdmcu", self.num_qubits, [], "qdmcu")
def _define(self):
self.definition = QuantumCircuit(self.controls, self.target)
num_ctrl = len(self.controls)
if num_ctrl == 1:
u_gate = QuantumCircuit(1)
u_gate.unitary(self.unitary, 0)
self.definition.append(
u_gate.control(
num_ctrl_qubits=num_ctrl,
ctrl_state=self.ctrl_state
),
[*self.controls, self.target]
)
else:
if self.ctrl_state is None:
self.ctrl_state = '1' * num_ctrl
# Notice that `ctrl_state`` is reversed with respect to `controls``.
v_op = Qdmcu.custom_sqrtm(self.unitary)
v_gate = QuantumCircuit(1, name="V")
v_gate.unitary(v_op, 0)
v_gate_dag = QuantumCircuit(1, name="V^dag")
v_gate_dag.unitary(v_op.T.conj(), 0)
linear_mcx_gate = LinearMcx(
num_controls=num_ctrl-1,
ctrl_state=self.ctrl_state[1:],
action_only=True
).definition
self.definition.append(
v_gate.control(1, ctrl_state=self.ctrl_state[:1]),
[self.controls[-1], self.target]
)
self.definition.append(
linear_mcx_gate,
[*self.controls[:-1], self.controls[-1], self.target]
)
self.definition.append(
v_gate_dag.control(1, ctrl_state=self.ctrl_state[:1]),
[self.controls[-1], self.target]
)
self.definition.append(
linear_mcx_gate.inverse(),
[*self.controls[:-1], self.controls[-1], self.target]
)
self.qdmcu(
self.definition,
v_op,
self.controls[:-1],
self.target,
self.ctrl_state[1:]
)
@staticmethod
def custom_sqrtm(unitary):
eig_vals, eig_vecs = eig(unitary)
first_eig = sqrt(eig_vals[0]) * outer(eig_vecs[:, 0], eig_vecs[:, 0].conj())
second_eig = sqrt(eig_vals[1]) * outer(eig_vecs[:, 1], eig_vecs[:, 1].conj())
return first_eig + second_eig
@staticmethod
def qdmcu(
circuit,
unitary,
controls: Union[QuantumRegister, List[Qubit]],
target: Qubit,
ctrl_state: str=None
):
circuit.append(
Qdmcu(unitary, len(controls), ctrl_state=ctrl_state),
[*controls, target]
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ACDuriez/Ising-VQE
|
ACDuriez
|
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.optimize import minimize
from dataclasses import dataclass
from qiskit.providers.fake_provider import FakeManila,FakeQuito,FakeLima,FakeKolkata,FakeNairobi
from qiskit.transpiler import CouplingMap
from qiskit.circuit import QuantumCircuit,ParameterVector,Parameter
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
#from qiskit.opflow import PauliSumOp
from qiskit.primitives import Estimator,Sampler,BackendEstimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SLSQP,COBYLA,L_BFGS_B,QNSPSA,SPSA
from qiskit_aer.noise import NoiseModel
from qiskit_ibm_runtime import Session,Options,QiskitRuntimeService
from qiskit_ibm_runtime import Estimator as IBM_Estimator
from qiskit_ibm_runtime import Sampler as IBM_Sampler
from qiskit_aer.primitives import Estimator as AerEstimator
J = 1
h = 0.5
n_qubits = 4
def get_line_graph(n_qubits):
"""This function creates a linear lattice with
open boundary conditions for a given number of qubits"""
graph_line = nx.Graph()
graph_line.add_nodes_from(range(n_qubits))
edge_list = []
for i in graph_line.nodes:
if i < n_qubits-1:
edge_list.append((i,i+1))
# Generate graph from the list of edges
graph_line.add_edges_from(edge_list)
return graph_line
graph = get_line_graph(n_qubits)
nx.draw_networkx(graph) #plotting the graph
def get_h_op(graph,J=1.,hx=0.5,hz=0.,ap=0.):
"""Creates a general Ising hamiltonian for
given values of the coupling, transverse field,
longitudinal field and antiparallel field
Args:
graph: networkx graph of the lattice
J: uniform coupling between first neighbors
hx: transverse field parameter
hz: longitudinal field parameter
ap: antiparallel field at the boundaries"""
num_qubits = len(graph.nodes())
sparse_list = []
# Uniform Z and X fields
for qubit in graph.nodes():
# X field
coeff = ('X',[qubit],-1*hx)
sparse_list.append(coeff)
# Z field
coeff = ('Z',[qubit],-1*hz)
sparse_list.append(coeff)
# Anti-paralel field at the borders
coeff = ('Z',[0],ap) #this is the positive field (order reversed)
sparse_list.append(coeff)
coeff = ('Z',[num_qubits-1],-1*ap)
sparse_list.append(coeff)
#Interaction field (ZZ)
for i,j in graph.edges():
coeff = ('ZZ',[i,j],-1*J)
sparse_list.append(coeff)
hamiltonian = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=num_qubits).simplify()
return hamiltonian
def get_kk_op(graph):
"""Creates the number of kinks operator"""
sparse_list = []
for i,j in graph.edges():
coeff = ('II',[i,j],0.5)
sparse_list.append(coeff)
coeff = ('ZZ',[i,j],-0.5)
sparse_list.append(coeff)
kk_op = SparsePauliOp.from_sparse_list(sparse_list,num_qubits=len(graph.nodes))
return kk_op
# We show the Hamiltonian with the crittical boundary field as well as
# the number of kinks
print(get_h_op(graph,J,h,ap=np.sqrt(1-h)))
print(get_kk_op(graph))
exact_steps = 70
g_i = 0.
g_f = 1.6
exact_g_values = np.linspace(g_i,g_f,exact_steps)
def get_numpy_results(graph,J,h,g_values):
"""Returns the exact values of the energy and number of kinks
for a given lattice, coupling, transverse field and values of
the boundary field"""
n_qubits = len(graph.nodes())
numpy_solver = NumPyMinimumEigensolver()
E_values = []
kk_values = []
kk_op = get_kk_op(graph) #getting the (g-independent) number of kinks operator
for g in g_values:
h_op = get_h_op(graph,J,h,ap=g) #getting the hamiltonian operator for each g value
result = numpy_solver.compute_minimum_eigenvalue(operator=h_op,aux_operators=[kk_op])
E_values.append(result.eigenvalue)
kk_values.append(np.real(result.aux_operators_evaluated[0][0]))
return E_values,kk_values
exact_E,exact_kk = get_numpy_results(graph,J,h,exact_g_values) # getting the exact energy and number of kinks
#Plotting
f,ax = plt.subplots()
plt.plot(exact_g_values,exact_E)
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
inset_ax = f.add_axes([0.25, 0.3, 0.27, 0.27])# [left, bottom, width, height]
inset_ax.plot(exact_g_values,exact_kk)
inset_ax.set_ylabel('$<N_k>$')
inset_ax.set_xlabel('boundary field')
inset_ax.axvline(x=np.sqrt(1-h), color='red', linestyle='dashed') #indicating the critical boundary field
plt.show()
#Initialize runtime
service = QiskitRuntimeService(
channel='ibm_quantum',
instance='ibm-q/open/main',
token='your_token'
)
backend = service.backend("ibmq_qasm_simulator")
shots = 2**14 # shots for noisy simulations
def get_ansatz_hva(graph, theta_list):
"""Creates the hamiltonian variaitonal ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 3*n_layers, and must have a form (coupling_i,transverse_i,boundary_i)
Args:
graph: lattice graph
theta_list: list of parameters
"""
n_qubits = len(graph.nodes())
n_layers = len(theta_list)//3
qc = QuantumCircuit(n_qubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
# initial_state
qc.h(range(n_qubits))
for layer_index in range(n_layers):
# Coupling term
for pair in even_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
for pair in odd_edges:
qc.rzz(2 * theta_list[3*layer_index],pair[0],pair[1])
# boundary field term
qc.rz(2 *theta_list[3*layer_index+2],0)
qc.rz(-2 * theta_list[3*layer_index+2], n_qubits-1)
# transverse field term
qc.rx(2 * theta_list[3*layer_index+1], range(n_qubits))
return qc
layers_hva = 4
theta_list_hva = ParameterVector('θ',3*layers_hva)
ansatz_hva = get_ansatz_hva(graph,theta_list_hva)
ansatz_hva.draw('mpl',style='iqx')
def get_ansatz_hea(graph,theta_list):
"""Creates the hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
for pair in even_edges:
qc.cnot(pair[0],pair[1])
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
def get_ansatz_hea_ZNE(graph,theta_list):
"""Creates the folded version of hardware efficient ansatz for a given
lattice graph and list of parameters. The parameters list must have a
lenght of 2*n_qubits_n_layers. Used in the ZNE error mitigation protocol
Args:
graph: lattice graph
theta_list: list of parameters
"""
nqubits = len(graph.nodes())
n_layers = len(theta_list)//(2*nqubits)
assert len(theta_list)==2*n_qubits*n_layers, "The list of parameters does not have the correct size"
qc = QuantumCircuit(nqubits)
even_edges = [edge for edge in graph.edges() if edge[0]%2==0]
odd_edges = [edge for edge in graph.edges() if edge[0]%2!=0]
reversed_edges = [edge for edge in graph.edges()][::-1]
for layer_index in range(n_layers):
for qubit in range(nqubits):
qc.ry(theta_list[2*(nqubits)*layer_index+qubit], qubit)
# for pair in reversed_edges:
# qc.cnot(pair[0],pair[1])
#folding even edges
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in even_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
#folding odd edges
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for pair in odd_edges:
qc.cnot(pair[0],pair[1])
qc.barrier()
for qubit in range(nqubits):
qc.ry(theta_list[nqubits+2*(nqubits)*layer_index+qubit], qubit)
return qc
# Here we define and show the circuit for the HEA
layers_hea = 1
theta_list = ParameterVector('t',2*n_qubits*layers_hea) # The list of parameters must
ansatz_hea = get_ansatz_hea(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
# Here is the folded version of the HEA ansatz for the ZNE
ansatz_hea = get_ansatz_hea_ZNE(graph,theta_list)
ansatz_hea.draw('mpl', style="iqx")
def get_estimator(session,
server='qasm',
shots=2**14,
device=FakeKolkata(),
options_rtm=Options(),
seed=170):
"""Defines an estimator. Set 'qasm' for noiseless, 'noisy' for
backend estimator and 'rtm' for the runtime estimator"""
if server =='qasm':
estimator = Estimator(options={'shots':shots,'seed':seed})
elif server == 'noisy':
estimator = BackendEstimator(device,options={'shots':shots,'seed':seed})
elif server == 'rtm':
estimator = IBM_Estimator(session=session,options=options_rtm)
return estimator
def get_extrapolation(value_k1,value_k2,extrap='lin'):
"""Returns the exponential extrapolation given the
values for k=1 and k=2 noise factors"""
k_values = [1.,2.]
if extrap =='lin':
y_values = [value_k1,value_k2]
# Fit a linear regression model (polynomial of degree 1)
coefficients = np.polyfit(k_values, y_values, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope, intercept = coefficients
extrapolation = intercept
if extrap == 'exp':
y_values = [np.abs(value_k1/value_k2),1.]
ln_y = np.log(y_values)
# Fit a linear regression model (polynomial of degree 1)
coefficients_exp = np.polyfit(k_values, ln_y, 1)
# The coefficients represent the slope (m) and y-intercept (b) of the line
slope_exp, intercept_exp = coefficients_exp
extrapolation = np.exp(intercept_exp)*value_k2
return extrapolation
def vqe_opt_scipy(graph,
service,
backend,
g=0.7071067811865476,
h=0.5,
ansatz_str='hea',
layers=1,
optimizer='SLSQP',
maxiter=50,
ftol=0.,
reps=1,
zne=False,
extrap='exp',
shots=None,
server='qasm',
device=FakeNairobi(),
options=Options()):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
optimizer: optimization algorithm, as string for scipy
maxiter: maximum iterations for the optimization
ftol: tolerance for convergence, for scipy
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=h,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
extrapolation = get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
return extrapolation
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
random_point = np.random.random(ansatz.num_parameters)
iter_list = []
result_sample = minimize(cost_function_vqe,
x0=random_point,
method=optimizer,
callback=lambda xk: iter_list.append(list(xk)),
options={'maxiter':maxiter,'disp':False,'ftol':ftol})
iters = len(iter_list)
energy_list = estimator.run(iters*[ansatz],iters*[cost_operator],iter_list).result().values
nfev_list.append(int(result_sample.nfev))
log_list.append(list(energy_list))
session.close()
max_length = max(len(sublist) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist.extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0])):
values_list = [l[i] for l in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
g_mag = 0.2
g_knk = 1.2
E_mag = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_mag)).eigenvalue
E_knk = NumPyMinimumEigensolver().compute_minimum_eigenvalue(get_h_op(graph,ap=g_knk)).eigenvalue
reps = 5 # we define the number of initial parameters samplings
logs_hva_mag,avgs_hva_mag,stds_hva_mag,nfevs_hva_mag = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_mag,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_mag
stds_list = stds_hva_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hva_knk,avgs_hva_knk,stds_hva_knk,nfevs_hva_knk = vqe_opt_scipy(graph=graph,
service=service,
backend=backend,
server='qasm',
g=g_knk,
layers=layers_hva,
ansatz_str='hva',
reps=reps,
maxiter=300,
shots=None,
ftol=1e-16)
avgs_list = avgs_hva_knk
stds_list = stds_hva_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlim((0,40))
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -10, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
# Here we define a different callback which is suited for the SPSA implementation of qiskit
intermediate_info = {
'nfev': [],
'parameters': [],
'energy': [],
'step_size': [],
'step_sucesss': []
}
def callback(nfev, parameters, energy, step_size,step_sucess):
intermediate_info['nfev'].append(nfev)
intermediate_info['parameters'].append(parameters)
intermediate_info['energy'].append(energy)
intermediate_info['step_size'].append(step_size)
intermediate_info['step_sucess'].append(step_sucess)
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, step_size, step_sucess):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count}", end="\r", flush=True)
# Here is the main function
def vqe_critical_spsa(graph,
service,
backend,
device=FakeKolkata(),
g=0.7071067811865476,
layers=1,
server='qasm',
learning_rate=0.07,
perturbation=0.1,
maxiter=200,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe for the Ising model with boundary fields for
a single value of the boundary field, using the scipy optimization function.
It gives data for the convergence of the optimization, which is the logs for
each sampling, the mean and standart deviation of these samplings, and also the
number of function evaluations
Args:
graph: networkx lattice graph
service: service for runtime
backend: backend for runtime (can include quantum backends)
g: value of the boundary field
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: number of layers for the ansatz
maxiter: maximum iterations for the optimization
learning_rate: learning rate for the SPSA optimizer
perturbation: perturbation for the SPSA optimizer
reps: (int) number of initial parameters samplings
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
log_list = []
nfev_list = []
with Session(service=service,backend=backend) as session:
# estimator = BackendEstimator(FakeNairobiV2(),options={'shots':shots})
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
for i in tqdm(range(reps)):
log = VQELog([], [])
spsa = SPSA(maxiter=maxiter,
trust_region=True,
learning_rate=learning_rate,
perturbation=perturbation,
callback=log.update)
random_point = np.random.random(ansatz.num_parameters)
result_sample = spsa.minimize(cost_function_vqe,x0=random_point)
log_list.append(log)
nfev_list.append(result_sample.nfev)
session.close()
max_length = max(len(sublist.values) for sublist in log_list) # Finding the length of the largest list
for sublist in log_list:
if len(sublist.values) < max_length:
last_element = sublist[-1] # Extracting the last element
sublist = list(sublist)[:].extend([last_element] * (max_length - len(sublist))) # Filling with the last element
mean_list = []
std_list = []
for i in range(len(log_list[0].values)):
values_list = [log.values[i] for log in log_list]
mean_list.append(np.mean(values_list))
std_list.append(np.std(values_list))
return log_list,mean_list,std_list,nfev_list
logs_hea_noisy_mag,avgs_hea_noisy_mag,stds_hea_noisy_mag,nfevs_hea_noisy_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=5,
zne=False,
shots = shots
)
avgs_list = avgs_hea_noisy_mag
stds_list = stds_hea_noisy_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_mag,avgs_hea_zne_mag,stds_hea_zne_mag,nfevs_hea_zne_mag = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_mag,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_mag
stds_list = stds_hea_zne_mag
g_value = g_mag
exact_energy = E_mag
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
logs_hea_noisy_knk,avgs_hea_noisy_knk,stds_hea_noisy_knk,nfevs_hea_noisy_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=False,
shots=shots
)
avgs_list = avgs_hea_noisy_knk
stds_list = stds_hea_noisy_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
x_lim = 60
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization noisy g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
reps = 3
logs_hea_zne_knk,avgs_hea_zne_knk,stds_hea_zne_knk,nfevs_hea_zne_knk = vqe_critical_spsa(graph=graph,
service=service,
backend=backend,
device=FakeKolkata(),
g=g_knk,
server='noisy',
layers=1,
maxiter=170,
ansatz_str='hea',
reps=reps,
zne=True,
extrap='exp',
shots=shots
)
avgs_list = avgs_hea_zne_knk
stds_list = stds_hea_zne_knk
g_value = g_knk
exact_energy = E_knk
#Plots
x_values = np.arange(len(avgs_list))
f, ax = plt.subplots()
plt.plot(avgs_list)
# Calculating upper and lower bounds for the confidence interval
upper_bound = np.array(avgs_list) + 3 * np.array(stds_list) # 3 sigmas
lower_bound = np.array(avgs_list) - 3 * np.array(stds_list) # 3 sigmas
plt.fill_between(x_values, lower_bound, upper_bound, color='skyblue', alpha=0.4)
plt.axhline(y=exact_energy, color="tab:red", ls="--", label="exact")
# plt.xlim(0,60)
plt.xlabel("iteration")
plt.ylabel("cost function")
plt.title(f"VQE optimization mitigated g = {np.round(g_value,3)} {reps} samplings")
inset_ax = f.add_axes([0.6,0.6,0.25,0.25]) # [left, bottom, width, height]
inset_ax.plot([(exact_energy-avg)/exact_energy for avg in avgs_list])
inset_ax.set_yscale('log')
y_ticks = [10**i for i in range(-0, -3, -1)] # Change the range to suit your needs
inset_ax.set_yticks(y_ticks)
inset_ax.set_xlabel("iteration")
inset_ax.set_ylabel("relative error")
plt.show()
def vqe_phase_diagram(graph,
g_values,
optimizer,
init_optimizer,
service,
backend,
server='qasm',
device=FakeNairobi(),
angles_dict = {},
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='exp',
init_reps=1,
shots=2**14,
ansatz_str='hea'):
"""Runs the vqe to simulate the antiparallel model in
the hardware efficient ansatz for different values of
the antiparallel field. Returns the list of energies as
well as a dictionary with the optimal angles for each
value of the boundary field.
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_dict: dictionary of angles
optimizer: qiskit optimizer class
init_optimizer: optimizer for the first point
layers: layers for the ansatz
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
"""
n_qubits = len(graph.nodes())
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
E_values = []
rev_g_values = g_values[::-1]
for i,g in enumerate(tqdm(rev_g_values)):
cost_operator = get_h_op(graph,hx=hx,ap=g) #Defining Hamiltonian
# Now we set the cost function, with no mitigation, linear or exp extrapolation
if zne == False:
def cost_function_vqe(theta):
job = estimator.run(ansatz, cost_operator, theta)
values = job.result().values[0]
return values
if zne == True:
def cost_function_vqe(theta):
job = estimator.run([ansatz,ansatz_k2], 2*[cost_operator], 2*[theta])
value_k1 = job.result().values[0]
value_k2 = job.result().values[1]
return get_extrapolation(value_k1=value_k1,value_k2=value_k2,extrap=extrap)
if i == 0:
sample = 0.
for j in range(init_reps): #Performs sampling of initial parameters for the first point
initial_point = np.random.uniform(0., 2*np.pi, size=ansatz.num_parameters)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_sample = init_optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
if result_sample.fun < sample:
sample = result_sample.fun
result = result_sample
initial_point = result.x
else:
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result = optimizer.minimize(fun=cost_function_vqe,
x0=initial_point)
session.close()
E_values.append(result.fun)
#optimal angles storage
angles = list(result.x)
angles_dict[str(round(g,5))] = angles
return E_values,angles_dict
def vqe_optimal(graph,
service,
backend,
angles_opt,
server='qasm',
device=FakeNairobi(),
layers=1,
hx=0.5,
options=Options(),
zne=False,
extrap='lin',
shots=2**14,
ansatz_str='hea'):
""" Receives the optimal parameters for each value of
the boundary field and runs the circuits to compute the
energy as well as the number of kinks
Args:
graph: networkx lattice graph
g_values: list of values for the boundary field
angles_opt: dictionary of optimal angles
service: service for runtime
backend: backend for runtime (can include quantum backends)
h: value of the transverse field
ansatz_str: choice of ansatz, 'hea' for HEA and 'hva' for HVA
layers: layers for the ansatz
reps: number of initial parameters samplings for the first point
zne: (bool) zne option
extrap: type of extrapolation
shots: number of shots, set to None for statevector simulations
server: 'qasm' for noiseless, 'noisy' for aer, 'rtm' for runtime
device: noise model for noisy simulations
options: Options() class for runtime
Returns:
The values of the energy, number of kinks, and the associated values
of g to facilitate plotting
"""
n_qubits = len(graph.nodes())
g_values = [float(k) for k in angles_opt.keys()]
n_points = len(g_values)
# Setting the ansatz
if ansatz_str == 'hea':
theta_list = ParameterVector('θ',2*n_qubits*layers)
ansatz = get_ansatz_hea(graph,theta_list)
ansatz_k2 = get_ansatz_hea_ZNE(graph,theta_list)
elif ansatz_str == 'hva':
theta_list = ParameterVector('θ',3*layers)
ansatz = get_ansatz_hva(graph,theta_list)
ansatz_k2 = get_ansatz_hva(graph,theta_list)
# Getting the list of angles and hamiltonians
angles_list = []
h_list = []
g_list = []
kk_op = get_kk_op(graph)
E_values = []
kk_values = []
for g_str,angles in angles_opt.items():
g = float(g_str)
g_list.append(g)
h_list.append(get_h_op(graph,hx=hx,ap=g))
angles_list.append(angles)
with Session(service=service,backend=backend) as session:
estimator = get_estimator(server=server,
shots=shots,
device=device,
session=session,
options_rtm=options)
result_h = estimator.run(n_points*[ansatz],h_list,angles_list).result()
result_kk = estimator.run(n_points*[ansatz],n_points*[kk_op],angles_list).result()
if zne == False:
E_values = list(result_h.values)
kk_values = list(result_kk.values)
else:
result_h_k2 = estimator.run(n_points*[ansatz_k2],h_list,angles_list).result()
result_kk_k2 = estimator.run(n_points*[ansatz_k2],n_points*[kk_op],angles_list).result()
for i in range(n_points):
E_values.append(get_extrapolation(result_h.values[i],result_h_k2.values[i],extrap))
kk_values.append(get_extrapolation(result_kk.values[i],result_kk_k2.values[i],extrap))
session.close()
return E_values,kk_values,g_list
# We define the range of values of g used for the VQE implentation
g_values = np.linspace(g_i,g_f,25)
init_reps = 5
slsqp = SLSQP(150)
init_slsqp = SLSQP(150) # We consider more iterations for the first point
E_hva,angles_hva = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hva',
backend=backend,
layers=layers_hva,
optimizer=slsqp,
init_optimizer=init_slsqp,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_hva,kk_hva,g_hva = vqe_optimal(graph=graph,
service=service,
server='qasm',
angles_opt=angles_hva,
ansatz_str='hva',
layers=layers_hva,
backend=backend)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hva,E_hva,'ro',label='VQE')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hva,kk_hva,'ro',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
init_reps = 2
spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1)
init_spsa = SPSA(maxiter=300,trust_region=True,learning_rate=0.07,perturbation=0.1) # We consider more iterations for the first point
# To perform the whole optimization using ZNE, just set zne = True
# This step took 207 minutes to run on my machine
E_hea_noisy,angles_hea_noisy = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='noisy',
device=FakeKolkata(),
zne=False,
shots=shots,
init_reps=init_reps)
# Now we run the circuits one last time with the optimal parameters
E_opt_hea_noisy,kk_opt_hea_noisy,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=False,
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# Now we run the circuits now using ZNE
E_opt_hea_mitigated,kk_opt_hea_mitigated,g_hea = vqe_optimal(graph=graph,
service=service,
server='noisy',
angles_opt=angles_hea_noisy,
device=FakeKolkata(),
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated,'o',label='mitigated')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
# First we get the optimal parameters with statevector simulations
E_hea_noiseless,angles_hea_noiseless = vqe_phase_diagram(graph=graph,
g_values=g_values,
ansatz_str='hea',
backend=backend,
layers=layers_hea,
optimizer=spsa,
init_optimizer=init_spsa,
service=service,
server='qasm',
shots=None,
init_reps=init_reps)
# Setting options for runtime
# Noisy options
fake_device = FakeKolkata()
noise_model = NoiseModel.from_backend(fake_device)
options_noisy = Options()
options_noisy.execution.shots = shots
options_noisy.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map,
"seed_simulator": 42
}
options_noisy.optimization_level = 3 # no optimization
options_noisy.resilience_level = 0 # M3 for Sampler and T-REx for Estimator
# Mitigated options
options_mitigated = Options()
options_mitigated.execution.shots = shots
options_mitigated.simulator = {
"noise_model": noise_model,
"basis_gates": fake_device.configuration().basis_gates,
"coupling_map": fake_device.configuration().coupling_map
}
# Set number of shots, optimization_level and resilience_level
options_mitigated.optimization_level = 3
options_mitigated.resilience_level = 1 # setting T-REX
# Now we run the circuits in runtime with the optimal parameters
# To run on runtime we set server = 'rtm'
# First we run the unmitigated results
E_opt_hea_noisy_rtm,kk_opt_hea_noisy_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=False,
extrap='exp',
backend=backend,
shots=shots)
# Now we run using ZNE and ZNE+T-REX
# ZNE
E_opt_hea_mitigated1_rtm,kk_opt_hea_mitigated1_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_noisy,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
# ZNE + T-REX
E_opt_hea_mitigated2_rtm,kk_opt_hea_mitigated2_rtm,g_hea = vqe_optimal(graph=graph,
service=service,
server='rtm',
options = options_mitigated,
angles_opt=angles_hea_noiseless,
ansatz_str='hea',
layers=layers_hea,
zne=True,
extrap='exp',
backend=backend,
shots=shots)
#Plotting
f,ax = plt.subplots()
#plt.plot(g_values,E_3,'ro')
plt.plot(exact_g_values,exact_E,label='exact')
plt.plot(g_hea,E_opt_hea_noisy_rtm,'o',label='noisy')
plt.plot(g_hea,E_opt_hea_mitigated1_rtm,'o',label='ZNE')
plt.plot(g_hea,E_opt_hea_mitigated2_rtm,'o',label='ZNE+T-REX')
plt.xlabel('boundary field')
plt.ylabel('groundstate energy')
plt.legend()
inset_ax = f.add_axes([0.24, 0.22, 0.3, 0.3]) # [left, bottom, width, height]
plt.plot(exact_g_values,exact_kk)
plt.plot(g_hea,kk_opt_hea_noisy_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated1_rtm,'o',markersize=4)
plt.plot(g_hea,kk_opt_hea_mitigated2_rtm,'o',markersize=4)
inset_ax.set_xlabel('boundary field')
inset_ax.set_ylabel("$<N_k>$")
plt.show()
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import hashlib
from typing import Dict, Iterable, List, NamedTuple, Sequence, Tuple, Union
import numpy as np
import qiskit
import sympy
from orquestra.quantum.circuits import (
_builtin_gates,
_circuit,
_gates,
_operations,
_wavefunction_operations,
)
from orquestra.quantum.circuits.symbolic.sympy_expressions import (
SYMPY_DIALECT,
expression_from_sympy,
)
from orquestra.quantum.circuits.symbolic.translations import translate_expression
from ._qiskit_expressions import QISKIT_DIALECT, expression_from_qiskit
QiskitTriplet = Tuple[
qiskit.circuit.Instruction, List[qiskit.circuit.Qubit], List[qiskit.circuit.Clbit]
]
def _import_qiskit_qubit(qubit: qiskit.circuit.Qubit) -> int:
return qubit._index
def _qiskit_expr_from_orquestra(expr):
intermediate = expression_from_sympy(expr)
return translate_expression(intermediate, QISKIT_DIALECT)
def _orquestra_expr_from_qiskit(expr):
intermediate = expression_from_qiskit(expr)
return translate_expression(intermediate, SYMPY_DIALECT)
ORQUESTRA_QISKIT_GATE_MAP = {
_builtin_gates.X: qiskit.circuit.library.XGate,
_builtin_gates.Y: qiskit.circuit.library.YGate,
_builtin_gates.Z: qiskit.circuit.library.ZGate,
_builtin_gates.S: qiskit.circuit.library.SGate,
_builtin_gates.SX: qiskit.circuit.library.SXGate,
_builtin_gates.T: qiskit.circuit.library.TGate,
_builtin_gates.H: qiskit.circuit.library.HGate,
_builtin_gates.I: qiskit.circuit.library.IGate,
_builtin_gates.CNOT: qiskit.circuit.library.CXGate,
_builtin_gates.CZ: qiskit.circuit.library.CZGate,
_builtin_gates.SWAP: qiskit.circuit.library.SwapGate,
_builtin_gates.ISWAP: qiskit.circuit.library.iSwapGate,
_builtin_gates.RX: qiskit.circuit.library.RXGate,
_builtin_gates.RY: qiskit.circuit.library.RYGate,
_builtin_gates.RZ: qiskit.circuit.library.RZGate,
_builtin_gates.PHASE: qiskit.circuit.library.PhaseGate,
_builtin_gates.CPHASE: qiskit.circuit.library.CPhaseGate,
_builtin_gates.XX: qiskit.circuit.library.RXXGate,
_builtin_gates.YY: qiskit.circuit.library.RYYGate,
_builtin_gates.ZZ: qiskit.circuit.library.RZZGate,
_builtin_gates.U3: qiskit.circuit.library.U3Gate,
_builtin_gates.Delay: qiskit.circuit.Delay,
}
def _make_gate_instance(gate_ref, gate_params) -> _gates.Gate:
"""Returns a gate instance that's applicable to qubits.
For non-parametric gate refs like X, returns just the `X`
For parametric gate factories like `RX`, returns the produced gate, like `RX(0.2)`
"""
if _gates.gate_is_parametric(gate_ref, gate_params):
return gate_ref(*gate_params)
else:
return gate_ref
def _make_controlled_gate_prototype(wrapped_gate_ref, num_control_qubits=1):
def _factory(*gate_params):
return _gates.ControlledGate(
_make_gate_instance(wrapped_gate_ref, gate_params), num_control_qubits
)
return _factory
QISKIT_ORQUESTRA_GATE_MAP = {
**{q_cls: z_ref for z_ref, q_cls in ORQUESTRA_QISKIT_GATE_MAP.items()},
qiskit.extensions.SXdgGate: _builtin_gates.SX.dagger,
qiskit.extensions.SdgGate: _builtin_gates.S.dagger,
qiskit.extensions.TdgGate: _builtin_gates.T.dagger,
qiskit.circuit.library.CSwapGate: _builtin_gates.SWAP.controlled(1),
qiskit.circuit.library.CRXGate: _make_controlled_gate_prototype(_builtin_gates.RX),
qiskit.circuit.library.CRYGate: _make_controlled_gate_prototype(_builtin_gates.RY),
qiskit.circuit.library.CRZGate: _make_controlled_gate_prototype(_builtin_gates.RZ),
}
def export_to_qiskit(circuit: _circuit.Circuit) -> qiskit.QuantumCircuit:
q_circuit = qiskit.QuantumCircuit(circuit.n_qubits)
q_register = qiskit.circuit.QuantumRegister(circuit.n_qubits, "q")
gate_op_only_circuit = _circuit.Circuit(
[op for op in circuit.operations if isinstance(op, _gates.GateOperation)]
)
custom_names = {
gate_def.gate_name
for gate_def in gate_op_only_circuit.collect_custom_gate_definitions()
}
q_triplets = []
for gate_op in circuit.operations:
if isinstance(gate_op, _gates.GateOperation):
q_triplet = _export_gate_to_qiskit(
gate_op.gate,
applied_qubit_indices=gate_op.qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
elif isinstance(gate_op, _wavefunction_operations.ResetOperation):
q_triplet = (
qiskit.circuit.library.Reset(),
[q_register[gate_op.qubit_indices[0]]],
[],
)
q_triplets.append(q_triplet)
for q_gate, q_qubits, q_clbits in q_triplets:
q_circuit.append(q_gate, q_qubits, q_clbits)
return q_circuit
def _export_gate_to_qiskit(gate, applied_qubit_indices, q_register, custom_names):
try:
return _export_gate_via_mapping(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_dagger_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_controlled_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_custom_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
raise NotImplementedError(f"Exporting gate {gate} to Qiskit is unsupported")
def _export_gate_via_mapping(gate, applied_qubit_indices, q_register, custom_names):
try:
qiskit_cls = ORQUESTRA_QISKIT_GATE_MAP[
_builtin_gates.builtin_gate_by_name(gate.name)
]
except KeyError:
raise ValueError(f"Can't export gate {gate} to Qiskit via mapping")
qiskit_params = [_qiskit_expr_from_orquestra(param) for param in gate.params]
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return qiskit_cls(*qiskit_params), qiskit_qubits, []
def _export_dagger_gate(
gate: _gates.Dagger,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.Dagger):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a dagger gate")
target_gate, qiskit_qubits, qiskit_clbits = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=applied_qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
return target_gate.inverse(), qiskit_qubits, qiskit_clbits
def _export_controlled_gate(
gate: _gates.ControlledGate,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a controlled gate")
target_indices = applied_qubit_indices[gate.num_control_qubits :]
target_gate, _, _ = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=target_indices,
q_register=q_register,
custom_names=custom_names,
)
controlled_gate = target_gate.control(gate.num_control_qubits)
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return controlled_gate, qiskit_qubits, []
def _export_custom_gate(
gate: _gates.MatrixFactoryGate,
applied_qubit_indices,
q_register,
custom_names,
):
if gate.name not in custom_names:
raise ValueError(
f"Can't export gate {gate} as a custom gate, the circuit is missing its "
"definition"
)
if gate.params:
raise ValueError(
f"Can't export parametrized gate {gate}, Qiskit doesn't support "
"parametrized custom gates"
)
# At that time of writing it Qiskit doesn't support parametrized gates defined with
# a symbolic matrix.
# See https://github.com/Qiskit/qiskit-terra/issues/4751 for more info.
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
qiskit_matrix = np.array(gate.matrix)
return (
qiskit.extensions.UnitaryGate(qiskit_matrix, label=gate.name),
qiskit_qubits,
[],
)
class AnonGateOperation(NamedTuple):
gate_name: str
matrix: sympy.Matrix
qubit_indices: Tuple[int, ...]
ImportedOperation = Union[_operations.Operation, AnonGateOperation]
def _apply_custom_gate(
anon_op: AnonGateOperation, custom_defs_map: Dict[str, _gates.CustomGateDefinition]
) -> _gates.GateOperation:
gate_def = custom_defs_map[anon_op.gate_name]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
gate_params: Tuple[sympy.Symbol, ...] = tuple()
gate = gate_def(*gate_params)
return gate(*anon_op.qubit_indices)
def import_from_qiskit(circuit: qiskit.QuantumCircuit) -> _circuit.Circuit:
q_ops = [_import_qiskit_triplet(triplet) for triplet in circuit.data]
anon_ops = [op for op in q_ops if isinstance(op, AnonGateOperation)]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
params_ordering: Tuple[sympy.Symbol, ...] = tuple()
custom_defs = {
anon_op.gate_name: _gates.CustomGateDefinition(
gate_name=anon_op.gate_name,
matrix=anon_op.matrix,
params_ordering=params_ordering,
)
for anon_op in anon_ops
}
imported_ops = [
_apply_custom_gate(op, custom_defs) if isinstance(op, AnonGateOperation) else op
for op in q_ops
]
return _circuit.Circuit(
operations=imported_ops,
n_qubits=circuit.num_qubits,
)
def _import_qiskit_triplet(qiskit_triplet: QiskitTriplet) -> ImportedOperation:
qiskit_op, qiskit_qubits, _ = qiskit_triplet
return _import_qiskit_op(qiskit_op, qiskit_qubits)
def _import_qiskit_op(qiskit_op, qiskit_qubits) -> ImportedOperation:
# We always wanna try importing via mapping to handle complex gate structures
# represented by a single class, like CNOT (Control + X) or CSwap (Control + Swap).
try:
return _import_qiskit_op_via_mapping(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_controlled_qiskit_op(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_custom_qiskit_gate(qiskit_op, qiskit_qubits)
except AttributeError:
raise ValueError(f"Conversion of {qiskit_op.name} from Qiskit is unsupported.")
def _import_qiskit_op_via_mapping(
qiskit_gate: qiskit.circuit.Instruction,
qiskit_qubits: Iterable[qiskit.circuit.Qubit],
) -> _operations.Operation:
qubit_indices = [_import_qiskit_qubit(qubit) for qubit in qiskit_qubits]
if isinstance(qiskit_gate, qiskit.circuit.library.Reset):
return _wavefunction_operations.ResetOperation(qubit_indices[0])
try:
gate_ref = QISKIT_ORQUESTRA_GATE_MAP[type(qiskit_gate)]
except KeyError:
raise ValueError(f"Conversion of {qiskit_gate} from Qiskit is unsupported.")
# values to consider:
# - gate matrix parameters (only parametric gates)
# - gate application indices (all gates)
orquestra_params = [
_orquestra_expr_from_qiskit(param) for param in qiskit_gate.params
]
gate = _make_gate_instance(gate_ref, orquestra_params)
return _gates.GateOperation(gate=gate, qubit_indices=tuple(qubit_indices))
def _import_controlled_qiskit_op(
qiskit_gate: qiskit.circuit.ControlledGate,
qiskit_qubits: Sequence[qiskit.circuit.Qubit],
) -> _gates.GateOperation:
if not isinstance(qiskit_gate, qiskit.circuit.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't import gate {qiskit_gate} as a controlled gate")
wrapped_qubits = qiskit_qubits[qiskit_gate.num_ctrl_qubits :]
wrapped_op = _import_qiskit_op(qiskit_gate.base_gate, wrapped_qubits)
qubit_indices = map(_import_qiskit_qubit, qiskit_qubits)
if isinstance(wrapped_op, _gates.GateOperation):
return wrapped_op.gate.controlled(qiskit_gate.num_ctrl_qubits)(*qubit_indices)
else:
raise NotImplementedError(
"Importing of controlled anonymous gates not yet supported."
)
def _hash_hex(bytes_):
return hashlib.sha256(bytes_).hexdigest()
def _custom_qiskit_gate_name(gate_label: str, gate_name: str, matrix: np.ndarray):
matrix_hash = _hash_hex(matrix.tobytes())
target_name = gate_label or gate_name
return f"{target_name}.{matrix_hash}"
def _import_custom_qiskit_gate(
qiskit_op: qiskit.circuit.Gate, qiskit_qubits: Iterable[qiskit.circuit.Qubit]
) -> AnonGateOperation:
value_matrix = qiskit_op.to_matrix()
return AnonGateOperation(
gate_name=_custom_qiskit_gate_name(
qiskit_op.label, qiskit_op.name, value_matrix
),
matrix=sympy.Matrix(value_matrix),
qubit_indices=tuple(_import_qiskit_qubit(qubit) for qubit in qiskit_qubits),
)
|
https://github.com/Quantum-Ducks/QuBayes
|
Quantum-Ducks
|
# These are versions of some of our important functions
# that were duplicates or non-generalized forms that I
# am retiring to here in case something goes wrong
import pandas as pd
import numpy as np
def get_probabilities_2state_sys(states):
num_total = np.shape(states)[0] * np.shape(states)[1]
num_ones = np.shape(np.where(states == 1))[1]
num_zeros = num_total - num_ones
prob_one = num_ones/num_total
prob_zero = num_zeros/num_total
assert round(prob_one+prob_zero, 3) == 1.
return prob_one, prob_zero
def get_conditional_probability_2parent_2state(Astates, Bstates, Cstates): #I'm in progress of generalizing this in probabilities.ipynb, but feel free to pick up where I left off
"""A and B are parent nodes. C is child node"""
num111, num101, num011, num001, num110, num100, num010, num000 = 0, 0, 0, 0, 0, 0, 0, 0
num11, num01, num10, num00 = 0,0,0,0
#Add up cases where C=1
indC_one_row = np.where(Cstates == 1)[0] #index of row with a 1
indC_one_col = np.where(Cstates == 1)[1] #index of corresponding coln with a 1
for i in range(len(indC_one_col)): # loop through all times C=1
A = Astates.iloc[indC_one_row[i], indC_one_col[i]]
B = Bstates.iloc[indC_one_row[i], indC_one_col[i]]
if A == 1:
if B == 1:
num111 += 1 #C=1, B=1, A=1
num11 += 1 #B=1, A=1
elif B == 0:
num101 += 1 #C=1, B=0, A=1
num01 += 1 #B=0, A=1
elif A == 0:
if B == 1:
num110 += 1 #C=1, B=1, A=0
num10 += 1 #B=1, A=0
elif B == 0:
num100 += 1 #C=1, B=0, A=0
num00 += 1 #B=0, A=0
# Add up states where C=0
indC_zero_row = np.where(Cstates == 0)[0]
indC_zero_col = np.where(Cstates == 0)[1]
for i in range(len(indC_zero_col)): # loop through all times C=0
A = Astates.iloc[indC_zero_row[i], indC_zero_col[i]]
B = Bstates.iloc[indC_zero_row[i], indC_zero_col[i]]
if A == 1:
if B == 1:
num011 += 1 #C=0, B=1, A=1
num11 += 1 #B=1, A=1
elif B == 0:
num001 += 1 #C=0, B=0, A=1
num01 += 1 #B=0, A=1
elif A == 0:
if B == 1:
num010 += 1 #C=0, B=1, A=0
num10 += 1 #B=1, A=0
elif B == 0:
num000 += 1 #C=0, B=0, A=0
num00 += 1 #B=0, A=0
# Calculate conditional probabilities
num_total = np.shape(Astates)[0] * np.shape(Astates)[1]
"""The variable names are in the order CBA (cases, testing, stay at home). """
P111 = num111/num11
P101 = num101/num01
P110 = num110/num10
P100 = num100/num00
P011 = num011/num11
P001 = num001/num01
P010 = num010/num10
P000 = num000/num00
states = np.array(['0|00','1|00','0|01','1|01','0|10','1|10','0|11','1|11']) #I believe this is the order Matt was talking about with top to bottom, left to right in the table from the paper
conditional_probabilities = np.array([P000,P100,P001,P101,P010,P110,P011,P111]) #in this order, the first two, second two, etc. should each add to 1 as pairs (columns in the paper's table)
# Make graph for circuit input
ProbA1, ProbA0 = get_probabilities_2state_sys(Astates)
ProbB1, ProbB0 = get_probabilities_2state_sys(Bstates)
graph = { 'StayAtHome': ([], [ProbA0, ProbA1]), # P(A = 0), P(A = 1)
'Testing': ([], [ProbB0, ProbB1]), #P(B = 0), P(B = 1)
#P(C=0|A=0,B=0), P(C=1|A=0,B=0), P(C=0|A=0,B=1), P(C=1|A=0,B=1), P(C=0|A=1,B=0), P(C=1|A=1,B=0), P(C=0|A=1,B=1), P(C=1|A=1,B=1)
'Cases': (['StayAtHome','Testing'], [P000, P100, P010, P110, P001, P101, P011, P111])
}
return states, conditional_probabilities, graph
def Margies_marginal_probabilities(ntwk_results): #a combined version of this with Ella's is kept in the real code
#ntwk_results: dict, counts resulting from network run (should have 2^n entries)
#marg_probs: array of length n, marginal probabilities that each qubit is 0,
#from most significant to least significant
n = len(list(ntwk_results.keys())[0])
prob = np.zeros(n)
total = sum(ntwk_results.values())
for i in range(n):
for key in ntwk_results:
if int(key[i]) == 0:
prob[i] += ntwk_results[key]
prob[i] = prob[i]/total
return prob
def Ella_3qubit_marginal_probabilities(pstates_dict):
# Works for 3 qubits only
C0, B0, A0, numtot = 0, 0, 0, 0
for key in pstates_dict:
Cstate=key[0]
Bstate=key[1]
Astate=key[2]
numtot += pstates_dict[key]
if Cstate == '0':
C0 += pstates_dict[key]
if Bstate == '0':
B0 += pstates_dict[key]
if Astate == '0':
A0 += pstates_dict[key]
ProbC0 = C0/numtot
ProbB0 = B0/numtot
ProbA0 = A0/numtot
return ProbC0, ProbB0, ProbA0
def Ella_marginal_probabilities_general(pstates_dict):
"""Works for n qubits"""
n = len(list(pstates_dict.keys())[0]) #number of qubits in state
Probs = np.empty(n)
numZeros, numtot = np.zeros(n), 0
for key in pstates_dict:
numtot += pstates_dict[key]
for i in range(n):
#print(i)
state=key[i]
if state == '0':
numZeros[i] += pstates_dict[key]
for i in range(n):
Probs[i] = numZeros[i]/numtot
return Probs
# Test the marginal prob functions with some simulated output from our 3 qubit run!
#pick the function to use (comment others out)
funct = Ella_marginal_probabilities_general
#funct = Ella_3qubit_marginal_probabilities
#funct = Margies_marginal_probabilities
result1 = {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260}
print(funct(result1))
def get_lesser_model_states():
statedataStayHome = {'MarHome' : data['MarHome'], 'AprHome' : data['AprHome'], 'MayHome' : data['MayHome'], 'JunHome' : data['JunHome']}
statesStayHome = pd.DataFrame(data=statedataStayHome)
statedataTests = {'MarTest' : data['MarTest'], 'AprTest' : data['AprTest'], 'MayTest' : data['MayTest'], 'JunTest' : data['JunTest']}
statesTests = pd.DataFrame(data=statedataTests)
statedataCases = {'MarCases' : data['MarCases'], 'AprCases' : data['AprCases'], 'MayCases' : data['MayCases'], 'JunCases' : data['JunCases']}
statesCases = pd.DataFrame(data=statedataCases) # 0 = increasing. 1 = flat or decreasing
return statesStayHome, statesTests, statesCases
data = pd.read_csv('data/lesser_model_data.csv')
Astates, Bstates, Cstates = get_lesser_model_states()
print(get_conditional_probability_2parent_2state(Astates, Bstates, Cstates))
""" # ALTERNATE SECTION OF GENERALIZED CONDITIONAL PROBABILITY CODE TO CONSIDER SHORTENING BY LIKE 3 LINES
def f(c, *ps):
for key in keys:
num_c, tot_c = 0, 0
n = len(c)
for i in range(n):
all_ps = all([ps[j][i] == key[j] for j in range(len(ps))])
if all_ps:
tot_c += 1
if c[i] == thing before |:
num_c += 1
"""
def generate_cond_keys_old(s_0, s_i):
##############################################
#THIS FUNCTION WILL GENERATE A LIST OF STRINGS TO USE AS KEYS FOR CONDITIONAL PROBABILITIES
### INPUT ###
# s_0 int number of states of the child node
# s_i list number of states for each parent node, from most to least significant
### OUTPUT ###
# list of strings to use as keys for conditional probabilities (included commas in case there is ever an >11-state node!)
##############################################
ranges = [range(0, elem) for elem in list([s_0])+list(s_i)]
enumed = product(*ranges)
cond_keys = []
for enum in enumed:
enum = list(enum)
parent_str = ",".join(str(x) for x in enum[1:])
cond_keys.append("%s|%s"%(str(enum[0]), parent_str))
return cond_keys
|
https://github.com/LauraGentini/QRL
|
LauraGentini
|
__author__ = 'QRL_team'
from qiskit import *
from qiskit.circuit.library import GroverOperator
from qiskit.quantum_info import Statevector
import numpy as np
from math import ceil
class GroverMazeLearner:
"""
Inits a quantum QLearner object for given environment.
Environment must be discrete and of "maze type", with the last state as the goal
"""
def __init__(self, env):
self.env = env # gym.make("FrozenLake-v0", is_slippery=False)
# state and action spaces dims
self.obs_dim = self.env.observation_space.n
self.acts_dim = self.env.action_space.n
# dim of qubits register needed to encode all actions
self.acts_reg_dim = ceil(np.log2(self.acts_dim))
# optimal number of steps in original Grover's algorithm
self.max_grover_steps = int(round(
np.pi / (4 * np.arcsin(1. / np.sqrt(2 ** self.acts_reg_dim))) - 0.5))
# quality values
self.state_vals = np.zeros(self.obs_dim)
# grover steps taken
self.grover_steps = np.zeros((self.obs_dim, self.acts_dim), dtype=int)
# boolean flags to signal maximum amplitude amplification reached
self.grover_steps_flag = np.zeros((self.obs_dim, self.acts_dim), dtype=bool)
# learner hyperparms (eps still not used)
self.hyperparams = {'k': -1, 'alpha': 0.05, 'gamma': 0.99, 'eps': 0.01, 'max_epochs': 1000, 'max_steps': 100
, 'graphics': True}
# current state
self.state = self.env.reset()
# current action
self.action = 0
# list of grover oracles
self.grover_ops = self._init_grover_ops()
# list of state-action circuits
self.acts_circs = self._init_acts_circs()
# qiskit simulator
self.SIM = Aer.get_backend('qasm_simulator')
def set_hyperparams(self, hyperdict):
"""
Set learner's hyperparameters
:param hyperdict: a dict with same keys as self's
:return:
"""
self.hyperparams = hyperdict
def _init_acts_circs(self):
"""
Inits state-action circuits
:return: list of qiskit circuits, initialized in full superposition
"""
circs = [QuantumCircuit(self.acts_reg_dim, name='|as_{}>'.format(i)) for i in range(self.obs_dim)]
for c in circs:
c.h(list(range(self.acts_reg_dim)))
return circs
def _update_statevals(self, reward, new_state):
"""
Bellman equation for state values update
:param reward: instantaneous reward received by the agent
:param new_state: state reached upon taking previous action
:return:
"""
self.state_vals[self.state] += self.hyperparams['alpha']*(reward
+ self.hyperparams['gamma']*self.state_vals[new_state]
- self.state_vals[self.state])
def _eval_grover_steps(self, reward, new_state):
"""
Choose how many grover step to take based on instantaneous reward and value of new state
:param reward: the instantaneous reward received by the agent
:param new_state: the new state visited by the agent
:return: number of grover steps to be taken,
if it exceeds the theoretical optimal number the latter is returned instead
"""
steps_num = int(self.hyperparams['k']*(reward + self.state_vals[new_state]))
return min(steps_num, self.max_grover_steps)
def _init_grover_ops(self):
"""
Inits grover oracles for the actions set
:return: a list of qiskit instructions ready to be appended to circuit
"""
states_binars = [format(i, '0{}b'.format(self.acts_reg_dim)) for i in range(self.acts_dim)]
targ_states = [Statevector.from_label(s) for s in states_binars]
grops = [GroverOperator(oracle=ts) for ts in targ_states]
return [g.to_instruction() for g in grops]
def _run_grover(self):
"""
DEPRECATED
:return:
"""
# deploy grover ops on acts_circs
gsteps = self.grover_steps[self.state, self.action]
circ = self.acts_circs[self.state]
op = self.grover_ops[self.action]
for _ in range(gsteps):
circ.append(op, list(range(self.acts_reg_dim)))
self.acts_circs[self.state] = circ
def _run_grover_bool(self):
"""
Update state-action circuits based on evaluated steps
:return:
"""
flag = self.grover_steps_flag[self.state, :]
gsteps = self.grover_steps[self.state, self.action]
circ = self.acts_circs[self.state]
op = self.grover_ops[self.action]
if not flag.any():
for _ in range(gsteps):
circ.append(op, list(range(self.acts_reg_dim)))
if gsteps >= self.max_grover_steps and not flag.any():
self.grover_steps_flag[self.state, self.action] = True
self.acts_circs[self.state] = circ
def _take_action(self):
"""
Measures the state-action circuit corresponding to current state and decides next action
:return: action to be taken, int
"""
circ = self.acts_circs[self.state]
circ_tomeasure = circ.copy()
circ_tomeasure.measure_all()
# circ_tomeasure = transpile(circ_tomeasure)
# print(circ.draw())
job = execute(circ_tomeasure, backend=self.SIM, shots=1)
result = job.result()
counts = result.get_counts()
action = int((list(counts.keys()))[0], 2)
return action
def train(self):
"""
groverize and measure action qstate -> take corresp action
obtain: newstate, reward, terminationflag
update stateval, grover_steps
for epoch in epochs until max_epochs is reached
:return:
dictionary of trajectories
"""
traj_dict = {}
# set initial max_steps
optimal_steps = self.hyperparams['max_steps']
for epoch in range(self.hyperparams['max_epochs']):
if epoch % 10 == 0:
print("Processing epoch {} ...".format(epoch))
# reset env
self.state = self.env.reset()
# init list for traj
traj = [self.state]
if self.hyperparams['graphics']:
self.env.render()
for step in range(optimal_steps):
print('Taking step {0}/{1}'.format(step, optimal_steps), end='\r')
# print('STATE: ', self.state)
# Select action
self.action = self._take_action()
# take action
new_state, reward, done, _ = self.env.step(self.action)
if new_state == self.state:
reward -= 10
done = True
if new_state == self.obs_dim - 1:
reward += 99
# update optimal traj len
optimal_steps = step + 1
elif not done:
reward -= 1
# print('REWARD: ', reward)
# update statevals and grover steps
self._update_statevals(reward, new_state)
self.grover_steps[self.state, self.action] = self._eval_grover_steps(reward, new_state)
# amplify amplitudes with grover
# self._run_grover()
self._run_grover_bool()
# render if curious
if self.hyperparams['graphics']:
self.env.render()
# save transition
traj.append(new_state)
# quit epoch if done
if done:
break
# move to new state
self.state = new_state
# print('STATE_VALS: ', self.state_vals)
# print('GROVER_STEPS: ', self.grover_steps)
traj_dict['epoch_{}'.format(epoch)] = traj
# return trajectories
return traj_dict
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
!pip install qutip
import numpy as np
from qutip import *
# Define the system parameters
omega = 1.0 # Frequency of the external potential
interaction_strength = 0.5 # Strength of the interaction
time_points = np.linspace(0, 10, 1000) # Time points for simulation
# Define the Hamiltonian for the system
H0 = omega * tensor(sigmax(), identity(2)) # External potential
Hint = interaction_strength * (tensor(sigmax(), sigmax()) + tensor(sigmay(), sigmay())) # Interaction term
H = H0 + Hint # Total Hamiltonian
# Define the initial state of the system
psi0 = tensor(basis(2, 0), basis(2, 1)) # Example initial state: |0⟩⨂|1⟩
# Simulate the time evolution of the system
result = mesolve(H, psi0, time_points, [], [])
# Extract the desired state from the result list
states = result.states
# Calculate the concurrence at each time point
concurrence = [concurrence(state) for state in states]
# Plot the concurrence as a function of time
import matplotlib.pyplot as plt
plt.plot(time_points, concurrence)
plt.xlabel('Time')
plt.ylabel('Concurrence')
plt.title('Effect of External Potential on Concurrence')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import qiskit
import numpy as np
import math
import random
import pandas as pd
from qiskit import IBMQ
IBMQ.save_account('3ccb2d17a0f19c3ce64cf44b3e1c90d3369ea562672f7315624ee8d92bb4350e10b643e3b2af92eef73c029e051518c2a833fb0ffa2e600b2c6c65ed5dd29d40')
IBMQ.load_account()
from qiskit import *
import math as m
import time
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.quantum_info import state_fidelity
#simulators
S_simulator = Aer.backends(name = 'statevector_simulator')[0]
M_simulator = Aer.backends(name = 'qasm_simulator')[0]
U_simulator = Aer.backends(name = 'unitary_simulator')[0]
#provider = IBMQ.get_provider(hub = 'ibm-q-research')
csv_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
# using the attribute information as the column names
col_names = ['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width','Class']
iris = pd.read_csv(csv_url, names = col_names)
#amplitude encoding
# total amplitudes to be encoded = features*total_instances = 600
# total computatuional basis states available = 2**10 = 1024
# redundant states = 1024 - 600 = 424
features = 4
total_instances = 150
num_qubits = int(math.log(features*total_instances,2)) +1
redundant_basis_states = 2**num_qubits - features*total_instances
redundant_basis_states_list = list(np.zeros(redundant_basis_states,dtype = int))
q = QuantumRegister(num_qubits)
qc = QuantumCircuit(q)
Vector = []
for i in range(total_instances):
vector = [iris['Sepal_Length'][i],iris['Sepal_Width'][i],iris['Petal_Length'][i],iris['Petal_Length'][i] ]
#Vector = list(np.concatenate(vector))
Vector.append(vector)
#Vector = Vector.append(redundant_basis_states_list)
final_state = list(np.concatenate(Vector))
Final_state = final_state + redundant_basis_states_list
normalized_state = (Final_state / np.linalg.norm(Final_state))
qc.initialize(normalized_state)
qc.draw('mpl')
# the corresponding state contains all 600 amplitudes
# angle encoding
Vector
circuit = QuantumCircuit(features, 4)
for j in range(total_instances):
for i in range(features):
circuit.ry(Vector[j][i],i)
#qc.ry(Vector[i],i)
circuit.measure(range(4), range(4))
circuit.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(circuit, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts()
counts
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
n = 5
m = 4
states_of_qubits = [] # we trace the state of each qubit also by ourselves
qreg1 = QuantumRegister(n) # quantum register with n qubits
creg1 = ClassicalRegister(n) # classical register with n bits
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# set each qubit to |1>
for i in range(n):
mycircuit1.x(qreg1[i]) # apply x-gate (NOT operator)
states_of_qubits.append(1) # the state of each qubit is set to 1
# randomly pick m pairs of qubits
for i in range(m):
controller_qubit = randrange(n)
target_qubit = randrange(n)
# controller and target qubits should be different
while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again
target_qubit = randrange(n)
# print our picked qubits
print("the indices of the controller and target qubits are",controller_qubit,target_qubit)
# apply cx-gate (CNOT operator)
mycircuit1.cx(qreg1[controller_qubit],qreg1[target_qubit])
# we also trace the results
if states_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1,
states_of_qubits[target_qubit] = 1 - states_of_qubits[target_qubit] # then flips the value of the target qubit
# remark that 1-x gives the negation of x
# measure the quantum register
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit
mycircuit1.draw(output='mpl')
# re-execute this cell if you DO NOT see the circuit diagram
# execute the circuit 100 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit1)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
# the states of the qubits should be as follows based on our own calculation
print(states_of_qubits)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg2 = QuantumRegister(2) # quantum register with 2 qubits
creg2 = ClassicalRegister(2) # classical register with 2 bits
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit2.x(qreg2[0]) # set the state of the first qubit to |1>
if input[1]=='1':
mycircuit2.x(qreg2[1]) # set the state of the second qubit to |1>
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# apply cx(first-qubit,second-qubit)
mycircuit2.cx(qreg2[0],qreg2[1])
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# measure both qubits
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit2)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,": ",reverse_outcome,"is observed",counts[outcome],"times")
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg3 = QuantumRegister(2) # quantum register with 2 qubits
creg3 = ClassicalRegister(2) # classical register with 2 bits
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit3.x(qreg3[0]) # set the value of the first qubit to |1>
if input[1]=='1':
mycircuit3.x(qreg3[1]) # set the value of the second qubit to |1>
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
# apply cx(second-qubit,first-qubit)
mycircuit3.cx(qreg3[1],qreg3[0])
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit3)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,": ",reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
# Importing Packages
import matplotlib.pyplot as plt
import numpy as np
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile, assemble
from qiskit.visualization import plot_histogram
# Input Secret Number
s = input("Input the secret number:\n")
n=len(s)
qc = QuantumCircuit(n+1, n)
# Putting states in superposition
qc.x(n)
for i in range(n+1):
qc.h(i)
qc.barrier()
# Apply the inner-product oracle
s=s[::-1] # reverse s to fit qiskit's qubit ordering
print(s)
for k in range(n):
if s[k] == '1':
qc.cx(k, n)
qc.barrier()
# Measuring
for m in range(n):
qc.h(m)
qc.barrier()
for b in range(n):
qc.measure(b,b)
qc.draw(output="mpl")
# Simulating on local simulator
aer_sim = Aer.get_backend('aer_simulator')
shots = 1024
qobj = assemble(qc)
results = aer_sim.run(qobj).result()
count = results.get_counts()
plot_histogram(count)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import GaussianForcesDriver
# if you ran Gaussian elsewhere and already have the output file
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
# if you want to run the Gaussian job from Qiskit
# driver = GaussianForcesDriver(
# ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight',
# '',
# 'CO2 geometry optimization B3LYP/6-31g',
# '',
# '0 1',
# 'C -0.848629 2.067624 0.160992',
# 'O 0.098816 2.655801 -0.159738',
# 'O -1.796073 1.479446 0.481721',
# '',
# ''
from qiskit_nature.second_q.problems import HarmonicBasis
basis = HarmonicBasis([2, 2, 2, 2])
from qiskit_nature.second_q.problems import VibrationalStructureProblem
from qiskit_nature.second_q.mappers import DirectMapper
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
print(main_op)
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
basis = HarmonicBasis([3, 3, 3, 3])
vibrational_problem = driver.run(basis=basis)
vibrational_problem.hamiltonian.truncation_order = 2
main_op, aux_ops = vibrational_problem.second_q_ops()
qubit_mapper = DirectMapper()
qubit_op = qubit_mapper.map(main_op)
print(qubit_op)
# for simplicity, we will use the smaller basis again
vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2]))
vibrational_problem.hamiltonian.truncation_order = 2
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
solver = GroundStateEigensolver(
qubit_mapper,
NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()),
)
result = solver.solve(vibrational_problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.