repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
import numpy as np
def NOT(input):
q = QuantumRegister(1) # a qubit in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if input=='1':
qc.x( q[0] )
# Now we've encoded the input, we can do a NOT on it using x
qc.x( q[0] )
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure( q[0], c[0] )
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1)
output = next(iter(job.result().get_counts()))
return output
def XOR(input1,input2):
q = QuantumRegister(2) # two qubits in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def AND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def NAND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def OR(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
print('\nResults for the NOT gate')
for input in ['0','1']:
print(' Input',input,'gives output',NOT(input))
print('\nResults for the XOR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',XOR(input1,input2))
print('\nResults for the AND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',AND(input1,input2))
print('\nResults for the NAND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',NAND(input1,input2))
print('\nResults for the OR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',OR(input1,input2))
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
# Python imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit import BasicAer
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.circuit.library import TwoLocal
# VOLTA
from volta.vqd import VQD
from volta.utils import classical_solver
from volta.hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
EPSILONS = [3, 3]
V = -2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, eigenvectors = classical_solver(hamiltonian)
print(f"Eigenvalues: {eigenvalues}")
from tqdm import tqdm
from qiskit.aqua import QuantumInstance
# Parameters Variables
n_trials = 50
# Auxiliary Variables
solution_dict = {}
# Define Optimizer
optimizers = [COBYLA(),
SPSA(maxiter=250, c1=.7, last_avg=25),
#L_BFGS_B(),
]
optimizer_names = ['COBYLA',
'SPSA',
#'L_BFGS_B'
]
# Define Backend
backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
shots=10_000)
# Ansatz with diferent depth
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3)
for i, optimizer in enumerate(optimizers):
es_1 = []
es_2 = []
for _ in tqdm(range(n_trials), desc=f"Optimizer {optimizer_names[i]}"):
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=2,
beta=10.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
vqd_energies = Algo.energies
es_1.append(vqd_energies[1])
es_2.append(vqd_energies[2])
es_1 = np.array(es_1)
es_2 = np.array(es_2)
# Maybe use a pd.dataframe
solution_dict[i] = {'mean': np.mean(es_2 - es_1),
'std':np.std(es_2 - es_1),
}
solution_dict
mean = []
std = []
for i in range(len(optimizers)):
mean.append(solution_dict[i]['mean'])
std.append(solution_dict[i]['std'])
import seaborn as sns
sns.set()
from matplotlib.ticker import MaxNLocator
x_axis = optimizer_names
plt.errorbar(x_axis,
np.array(mean)/2,
yerr=np.array(std)/2,
fmt='ro', ecolor='green')
plt.hlines(y=2, xmin=0., xmax=len(optimizers)+ 0.25,
label='Expected value',color='b')
plt.title('Optimizers', size=18)
plt.xlabel('Optimizer', size= 14)
plt.ylabel('Gap', size=14)
plt.xticks(x_axis)
plt.legend()
plt.show()
|
https://github.com/qiskit-fall-fest-hackathon-france/qiskit-fall-fest-hackathon-france
|
qiskit-fall-fest-hackathon-france
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.draw()
qc.h(qr[0])
qc.draw()
qc = QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw()
from qiskit import execute
from qiskit import Aer
print(Aer.backends()) #, nicer printout below:
backend_list = Aer.backends()
for be in backend_list:
print(be)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend,shots=100000)
print(job)
my_results = job.result()
print(my_results)
print(my_results.get_counts())
# with shots=1, you will get a count of 1 either on 00 or on 11
job = execute(qc,backend, shots=111)
my_results = job.result()
print(my_results.get_counts(qc))
from qiskit.tools.visualization import plot_histogram
plot_histogram(my_results.get_counts(qc))
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.x(qr[0])
qc.id(qr[1])
qc.measure(qr,cr)
qc.draw()
# with shots=1, you will get a count of 1 either on 00 or on 11
job = execute(qc,backend, shots=1024)
my_results = job.result()
print(my_results.get_counts(qc))
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
qc.draw(output='latex')
# how to use the machines and simulator in the cloud
from qiskit import IBMQ
MY_API_TOKEN= 'e5f5ed26c560465a044adb6bbbad67743cd41365ff700fe7ab7104ef83518ccff6b28b4b52ecd827de2df397aba6a6e8eb88cc154842ab203f1aadfbdff3f024'
IBMQ.save_account(MY_API_TOKEN, overwrite=True)
IBMQ.load_account()
sp = IBMQ.get_provider(hub='ibm-q')
# list backends available for this provider
print(sp.backends())
sp = IBMQ.get_provider(hub='ibm-q') # selected provider
backends_set = set()
for b in selected_provider.backends():
backends_set.add(str(b))
print("backend name queue qubits operational status message")
print("------------------------------- ----- ------ ----------- --------------")
for b in backends_set:
be = sp.get_backend(b)
pj = be.status().pending_jobs
qb = be.configuration().n_qubits
op = be.status().operational
sm = be.status().status_msg
print(f"{b:32} {pj:4} {qb:6}{op:12} {sm:6}")
print("------------------------------ ----- ------ ----------- --------------")
backend = selected_provider.get_backend('simulator_statevector')
# IBMQ for access to online devices and helps manage your IBM Q account data from your workstation.
from qiskit import IBMQ
MY_API_TOKEN= 'e5f5ed26c560465a044adb6bbbad67743cd41365ff700fe7ab7104ef83518ccff6b28b4b52ecd827de2df397aba6a6e8eb88cc154842ab203f1aadfbdff3f024'
IBMQ.save_account(MY_API_TOKEN, overwrite=True)
IBMQ.load_account()
# choose one available provider
selected_provider = IBMQ.get_provider(hub='ibm-q')
# list backends available for this provider
selected_provider.backends()
# small program to get backends configs and status
# using least_busy() is more straightforward, this is to show
# how we get info from the provider's backends
sp = IBMQ.get_provider(hub='ibm-q') # selected provider
backends_set = set()
for b in selected_provider.backends():
backends_set.add(str(b))
print("backend name queue qubits operational status message")
print("------------------------------- ----- ------ ----------- --------------")
for b in backends_set:
be = sp.get_backend(b)
pj = be.status().pending_jobs
qb = be.configuration().n_qubits
op = be.status().operational
sm = be.status().status_msg
print(f"{b:32} {pj:4} {qb:6}{op:12} {sm:6}")
print("------------------------------ ----- ------ ----------- --------------")
backend = sp.get_backend('ibmq_belem')
backend.name()
# we want more than 1 qubit (we need 2), on an operationnal backend which is not a simulator
from qiskit.providers.ibmq import least_busy
backend = least_busy(sp.backends(filters = lambda x: x.configuration().n_qubits >= 2 and
not x.configuration().simulator and x.status().operational == True))
print("least busy backend: ", backend)
# execution
from qiskit.tools.monitor import job_monitor
job = execute(qc,backend)
print(job.job_id())
job_monitor(job)
res = job.result()
from qiskit.tools.visualization import plot_histogram
d = (res.get_counts(qc))
d
plot_histogram(d)
import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.visualization import plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector
from IPython.display import display, Math, Latex
# 1
def create_circuit():
qc = QuantumCircuit(1)
#
# FILL YOUR CODE IN HERE
#
#
return qc
# check solution
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 2
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 3
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 4
def create_circuit():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('0')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 5
def create_circuit():
qc = QuantumCircuit(2)
#
#
# FILL YOUR CODE IN HERE
qc.h(0)
qc.cx(0,1)
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 6
def create_circuit():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
#
#
# FILL YOUR CODE IN HERE
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
print(sv)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 7
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
# 8
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
# 9
def create_circuit():
qc = QuantumCircuit(2)
## initializing part
qc.rx(np.pi/3,0)
qc.x(1)
## end of initializing
#
#
# FILL YOUR CODE IN HERE
#
#
return qc
qc = create_circuit()
sv = Statevector.from_label('00')
sv = sv.evolve(qc)
print(sv)
plot_state_qsphere(sv.data, show_state_labels=True, show_state_phases=True)
# 10
#
#
# FILL YOUR CODE IN HERE
#
#
#
#
# FILL YOUR CODE IN HERE
#
#
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ, BasicAer
from qiskit.tools.jupyter import *
import matplotlib.pyplot as plt
%matplotlib inline
####
backend = BasicAer.get_backend('qasm_simulator')
shots_sim = 10
job_sim = execute(qc, backend, shots=shots_sim)
stats_sim = job_sim.result().get_counts()
def plot_letter (stats, shots):
### code from the qiskit.org smiley demo
for bitString in stats:
char = chr(int( bitString[0:7] ,2)) # get string of the leftmost 7 bits and convert to an ASCII character
prob = stats[bitString] / shots # fraction of shots for which this result occurred
# create plot with all characters on top of each other with alpha given by how often it turned up in the output
plt.annotate( char, (0.5,0.5), va="center", ha="center", color = (0,0,0, prob ), size = 300)
if (prob>0.05): # list prob and char for the dominant results (occurred for more than 5% of shots)
print(str(prob)+"\t"+char)
plt.axis('off')
plt.show()
print(shots_sim)
print(stats_sim)
plot_letter(stats_sim, shots_sim)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
from sklearn.datasets import make_blobs
features, labels = make_blobs(
n_samples=20,
centers=2,
center_box=(-1, 1),
cluster_std=0.1,
random_state=algorithm_globals.random_seed,
)
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
sv_qi = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
from qiskit.circuit.library import ZZFeatureMap
from qiskit_machine_learning.kernels import QuantumKernel
feature_map = ZZFeatureMap(2)
previous_kernel = QuantumKernel(feature_map=feature_map, quantum_instance=sv_qi)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=previous_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit.algorithms.state_fidelities import ComputeUncompute
from qiskit.primitives import Sampler
fidelity = ComputeUncompute(sampler=Sampler())
from qiskit_machine_learning.kernels import FidelityQuantumKernel
feature_map = ZZFeatureMap(2)
new_kernel = FidelityQuantumKernel(feature_map=feature_map, fidelity=fidelity)
from qiskit_machine_learning.algorithms import QSVC
qsvc = QSVC(quantum_kernel=new_kernel)
qsvc.fit(features, labels)
qsvc.score(features, labels)
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
num_inputs = 2
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
def parity(x):
return "{:b}".format(x).count("1") % 2
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit_machine_learning.neural_networks import CircuitQNN
circuit_qnn = CircuitQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import COBYLA
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
classifier = NeuralNetworkClassifier(
neural_network=circuit_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
from qiskit.primitives import Sampler
sampler = Sampler()
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=2,
sampler=sampler,
)
classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn,
loss="cross_entropy",
one_hot=True,
optimizer=COBYLA(maxiter=40),
initial_point=initial_point,
)
classifier.fit(features, labels)
classifier.score(features, labels)
import numpy as np
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
features = (ub - lb) * np.random.rand(num_samples, 1) + lb
labels = np.sin(features[:, 0]) + eps * (2 * np.random.rand(num_samples) - 1)
from qiskit.circuit import Parameter
num_inputs = 1
feature_map = QuantumCircuit(1)
feature_map.ry(Parameter("input"), 0)
ansatz = QuantumCircuit(1)
ansatz.ry(Parameter("weight"), 0)
circuit = QuantumCircuit(num_inputs)
circuit.compose(feature_map, inplace=True)
circuit.compose(ansatz, inplace=True)
initial_point = algorithm_globals.random.random(ansatz.num_parameters)
from qiskit.opflow import PauliSumOp, StateFn
from qiskit_machine_learning.neural_networks import OpflowQNN
observable = PauliSumOp.from_list([("Z", 1)])
operator = StateFn(observable, is_measurement=True) @ StateFn(circuit)
opflow_qnn = OpflowQNN(
operator=operator,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
quantum_instance=sv_qi,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import NeuralNetworkRegressor
regressor = NeuralNetworkRegressor(
neural_network=opflow_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=circuit,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
estimator=estimator,
)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit_machine_learning.algorithms import VQR
regressor = NeuralNetworkRegressor(
neural_network=estimator_qnn,
optimizer=L_BFGS_B(maxiter=5),
initial_point=initial_point,
)
regressor.fit(features, labels)
regressor.score(features, labels)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
# Apply a single H gate
qc.h(qr)
qc.measure(qr, cr)
circuit_drawer(qc)
import os
from qiskit import Aer
# Print the local simulator backends
print("Local simulator backends: ")
Aer.backends()
from qiskit import IBMQ
# Save your credeintials on disk. Need to be done only once.
IBMQ.save_account(os.getenv('QX_API_TOKEN'))
#IBMQ.save_account("PUT_YOUR_API_TOKEN_HERE")
# Alternatively, you can only "enable" the credentials, for this session only:
# IBMQ.enable_account("PUT_YOUR_API_TOKEN_HERE")
IBMQ.load_accounts()
print("Available online backends: ")
IBMQ.backends()
# Run the circuit using local simulator
local_simulator = Aer.get_backend("qasm_simulator")
job = execute(qc, backend=local_simulator, shots=100)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
# Run the circuit using the cloud simulator
online_simulator = IBMQ.get_backend("ibmq_qasm_simulator")
job = execute(qc, backend=online_simulator)
result_cloud = job.result()
counts = result.get_counts()
plot_histogram(counts)
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit import user_config
from qiskit.visualization import exceptions
from qiskit.visualization import latex as _latex
from qiskit.visualization import text as _text
from qiskit.visualization import utils
from qiskit.visualization import matplotlib as _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. By
default the 'text' drawer is used unless a user config file has
an alternative backend set as the default. If the output is passed
in that backend will always be used.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'id': 'id',
'u0': 'U_0',
'u1': 'U_1',
'u2': 'U_2',
'u3': 'U_3',
'x': 'X',
'y': 'Y',
'z': 'Z',
'h': 'H',
's': 'S',
'sdg': 'S^\\dagger',
't': 'T',
'tdg': 'T^\\dagger',
'rx': 'R_x',
'ry': 'R_y',
'rz': 'R_z',
'reset': '\\left|0\\right\\rangle'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
config = user_config.get_config()
# Get default from config file else use text
default_output = 'text'
if config:
default_output = config.get('circuit_drawer', 'text')
if output is None:
output = default_output
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reverse_bits=reverse_bits,
plotbarriers=plot_barriers,
justify=justify)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"id": "id",
"u0": "U_0",
"u1": "U_1",
"u2": "U_2",
"u3": "U_3",
"x": "X",
"y": "Y",
"z": "Z",
"h": "H",
"s": "S",
"sdg": "S^\\dagger",
"t": "T",
"tdg": "T^\\dagger",
"rx": "R_x",
"ry": "R_y",
"rz": "R_z",
"reset": "\\left|0\\right\\rangle"
},
"displaycolor": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False,
plotbarriers=True, justify=None, vertically_compressed=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reverse_bits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
vertically_compressed (bool): Default is `True`. It merges the lines so the
drawing will take less vertical room.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
text_drawing.vertically_compressed = vertically_compressed
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits, justify=justify)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True, justify=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qregs, cregs, ops = utils._get_layered_instructions(circuit,
reverse_bits=reverse_bits,
justify=justify)
qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
return qcd.draw(filename)
|
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
"""
#!/usr/bin/env python
# coding: utf-8
print("Loading Qiskit...")
from qiskit import QuantumCircuit, IBMQ
from qiskit.compiler import transpile
from qiskit.providers.ibmq import least_busy
from IPython.core.display import display
# Load account and find an available 5-qubit backend
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
print("Getting backend...")
backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
# Uncomment to set the backend to a simulator
#backend = provider.get_backend('ibmq_qasm_simulator')
print("Ch 6: Transpiling circuits")
print("--------------------------")
# Print the basis gates and coupling map for the selected backend
print("Basis gates for:", backend)
print(backend.configuration().basis_gates)
print("Coupling map for:", backend)
print(backend.configuration().coupling_map)
def build_circuit(choice):
# Create the circuit
qc = QuantumCircuit(5,5)
if choice=="1":
# Simple X
qc.x(0)
elif choice=="2":
# Add H
qc.x(0)
qc.h(0)
elif choice=="3":
# H + Barrier
qc.x(0)
qc.barrier(0)
qc.h(0)
elif choice=="4":
# Controlled Y (CY)
qc.cy(0,1)
elif choice=="5":
# Non-conforming CX
qc.cx(0,4)
else:
# Multi qubit circuit
qc.h(0)
qc.h(3)
qc.cx(0,4)
qc.cswap(3,1,2)
# Show measurement targets
#qc.barrier([0,1,2,3,4])
#qc.measure([0,1,2,3,4],[0,1,2,3,4])
return(qc)
def main():
choice="1"
while choice !="0":
choice=input("Pick a circuit: \n1. Simple X\n2. Add H\n3. H + Barrier\n4. Controlled-Y\n5. Non-conforming CX\n6. Multi-gate\n")
qc=build_circuit(choice)
# Create the transpiled circuit
trans_qc = transpile(qc, backend)
# Print the original and transpiled circuits
print("Circuit:")
display(qc.draw())
print("Transpiled circuit:")
display(trans_qc.draw())
# Print the original and transpiled circuit depths
print("Circuit depth:")
print("---------------")
print("Circuit:", qc.depth())
print("Transpiled circuit:", trans_qc.depth())
# Print the original and transpiled circuit sizes
print("\nCircuit size:")
print("---------------")
print("Circuit:", qc.size())
print("Transpiled circuit:", trans_qc.size())
if __name__ == '__main__':
main()
|
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.
"""Tests for visualization tools."""
import unittest
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.visualization.circuit import _utils
from qiskit.visualization import array_to_latex
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
class TestVisualizationUtils(QiskitTestCase):
"""Tests for circuit drawer utilities."""
def setUp(self):
super().setUp()
self.qr1 = QuantumRegister(2, "qr1")
self.qr2 = QuantumRegister(2, "qr2")
self.cr1 = ClassicalRegister(2, "cr1")
self.cr2 = ClassicalRegister(2, "cr2")
self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2)
self.circuit.cx(self.qr2[0], self.qr2[1])
self.circuit.measure(self.qr2[0], self.cr2[0])
self.circuit.cx(self.qr2[1], self.qr2[0])
self.circuit.measure(self.qr2[1], self.cr2[1])
self.circuit.cx(self.qr1[0], self.qr1[1])
self.circuit.measure(self.qr1[0], self.cr1[0])
self.circuit.cx(self.qr1[1], self.qr1[0])
self.circuit.measure(self.qr1[1], self.cr1[1])
def test_get_layered_instructions(self):
"""_get_layered_instructions without reverse_bits"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],))],
[("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs)
self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_reverse_bits(self):
"""_get_layered_instructions with reverse_bits=True"""
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(
self.circuit, reverse_bits=True
)
exp = [
[("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())],
[("measure", (self.qr2[0],), (self.cr2[0],))],
[("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())],
[("cx", (self.qr1[1], self.qr1[0]), ())],
[("measure", (self.qr2[1],), (self.cr2[1],))],
[("measure", (self.qr1[1],), (self.cr1[1],))],
]
self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs)
self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_remove_idle_wires(self):
"""_get_layered_instructions with idle_wires=False"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.cx(qr2[0], qr2[1])
circuit.measure(qr2[0], cr2[0])
circuit.cx(qr2[1], qr2[0])
circuit.measure(qr2[1], cr2[1])
circuit.cx(qr1[0], qr1[1])
circuit.measure(qr1[0], cr1[0])
circuit.cx(qr1[1], qr1[0])
circuit.measure(qr1[1], cr1[1])
(qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False)
exp = [
[("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())],
[("measure", (qr2[0],), (cr2[0],))],
[("measure", (qr1[0],), (cr1[0],))],
[("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())],
[("measure", (qr2[1],), (cr2[1],))],
[("measure", (qr1[1],), (cr1[1],))],
]
self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs)
self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs)
self.assertEqual(
exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_simple(self):
"""Test _get_layered_instructions left justification simple since #2802
q_0: |0>───────■──
┌───┐ │
q_1: |0>┤ H ├──┼──
├───┤ │
q_2: |0>┤ H ├──┼──
└───┘┌─┴─┐
q_3: |0>─────┤ X ├
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_simple(self):
"""Test _get_layered_instructions right justification simple since #2802
q_0: |0>──■───────
│ ┌───┐
q_1: |0>──┼──┤ H ├
│ ├───┤
q_2: |0>──┼──┤ H ├
┌─┴─┐└───┘
q_3: |0>┤ X ├─────
└───┘
"""
qc = QuantumCircuit(4)
qc.h(1)
qc.h(2)
qc.cx(0, 3)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())],
[
("h", (Qubit(QuantumRegister(4, "q"), 1),), ()),
("h", (Qubit(QuantumRegister(4, "q"), 2),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_left_justification_less_simple(self):
"""Test _get_layered_instructions left justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘└────────────┘ ║ └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left")
l_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_right_justification_less_simple(self):
"""Test _get_layered_instructions right justification
less simple example since #2802
┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
└────────────┘ └────────────┘ ║ └────────────┘ └────────────┘
q_2: |0>──────────────────────────────────╫──────────────────────────────────
║
q_3: |0>──────────────────────────────────╫──────────────────────────────────
║
q_4: |0>──────────────────────────────────╫──────────────────────────────────
║
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
"""
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
"""
qc = QuantumCircuit.from_qasm_str(qasm)
(_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right")
r_exp = [
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[
(
"measure",
(Qubit(QuantumRegister(5, "q"), 0),),
(Clbit(ClassicalRegister(1, "c1"), 0),),
)
],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
[("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())],
[
("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()),
("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()),
],
]
self.assertEqual(
r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
def test_get_layered_instructions_op_with_cargs(self):
"""Test _get_layered_instructions op with cargs right of measure
┌───┐┌─┐
q_0: |0>┤ H ├┤M├─────────────
└───┘└╥┘┌───────────┐
q_1: |0>──────╫─┤0 ├
║ │ add_circ │
c_0: 0 ══════╩═╡0 ╞
└───────────┘
c_1: 0 ═════════════════════
"""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
qc_2 = QuantumCircuit(1, 1, name="add_circ")
qc_2.h(0).c_if(qc_2.cregs[0], 1)
qc_2.measure(0, 0)
qc.append(qc_2, [1], [0])
(_, _, layered_ops) = _utils._get_layered_instructions(qc)
expected = [
[("h", (Qubit(QuantumRegister(2, "q"), 0),), ())],
[
(
"measure",
(Qubit(QuantumRegister(2, "q"), 0),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
[
(
"add_circ",
(Qubit(QuantumRegister(2, "q"), 1),),
(Clbit(ClassicalRegister(2, "c"), 0),),
)
],
]
self.assertEqual(
expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops]
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode(self):
"""Test generate latex label default."""
self.assertEqual("abc", _utils.generate_latex_label("abc"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_nomathmode_utf8char(self):
"""Test generate latex label utf8 characters."""
self.assertEqual(
"{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_utf8char(self):
"""Test generate latex label mathtext with utf8."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc_$∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_mathmode_underscore_outside(self):
"""Test generate latex label with underscore outside mathmode."""
self.assertEqual(
"abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label("$abc$_∭X∀Y"),
)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_signs(self):
"""Test generate latex label with escaped dollarsign."""
self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$"))
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self):
"""Test generate latex label with escaped dollar sign in mathmode."""
self.assertEqual(
"a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y",
_utils.generate_latex_label(r"$a$bc$_∭X∀Y"),
)
def test_array_to_latex(self):
"""Test array_to_latex produces correct latex string"""
matrix = [
[np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j],
[1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2],
]
matrix = np.array(matrix)
exp_str = (
"\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&"
"\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\"
"\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-"
"\\frac{9}{2}\\\\\\end{bmatrix}"
)
result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "")
self.assertEqual(exp_str, result)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
from qiskit.visualization import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.x(0) # Xゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(1) # 1量子ビット回路を用意
# Xゲートを0番目の量子ビットに操作します。
q.x(0)
# 次にHゲートを0番目の量子ビットに操作します。
q.h(0)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
q.h(0) # Hゲートを0番目の量子ビットに操作します。
q.h(1) # Hゲートを1番目の量子ビットに操作します。
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0=1, q1=0の場合:q0を1にします。
q.x(0)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0とq1をそれぞれ|+⟩にします
q.h(0)
q.h(1)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(2) # 2量子ビット回路を用意
# q0を|+⟩、q1を|−⟩にします
q.h(0)
q.x(1)
q.h(1)
# CXゲートの制御ビットをq0、目標ビットをq1にセットします。
q.cx(0,1)
q.draw(output="mpl") # 回路を描画
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
plot_bloch_multivector(result) # ブロッホ球の表示
q = QuantumCircuit(4) # 4量子ビット回路を用意
# q0、q1、q2をそれぞれ|1⟩にします
q.x(0)
q.x(1)
q.x(2)
# cxゲートを3つ追加します。制御/目標のペアは、q0/q3、q1/q3、q2/q3です。
q.cx(0,3)
q.cx(1,3)
q.cx(2,3)
q.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
backend = Aer.get_backend('statevector_simulator')
result = execute(q, backend).result().get_statevector(q, decimals=3)
print(result)
# ブロッホ球の表示
plot_bloch_multivector(result)
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
'''
This program implements the quantum Fourier transform (QFT)
'''
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ
from qiskit.visualization import circuit_drawer as drawer
from qiskit.tools.visualization import plot_histogram
from qiskit import execute
from qiskit import Aer
import numpy as np
import time, os, shutil
from matplotlib.pyplot import plot, draw, show
def QFT(q, c, n):
qc = QuantumCircuit(q,c)
# First get the most significant bit
for k in range(n):
j = n - k
# now add the Hadamard transform to qubit j-1
qc.h(q[j-1])
# now each qubit from the lowest significance
# takes one conditional phase shift
for i in reversed(range(j-1)):
qc.cp(2*np.pi/2**(j-i), q[i], q[j-1])
# Finally swap the qubits
for i in range(n//2):
qc.swap(q[i], q[n-i-1])
return qc
# QFT is represented in a matrix form with 2^n rows and columns
# where n represents the number of qubits
def QFTmatrix(n):
qft = np.zeros([2**n,2**n], dtype=complex)
for i in range(2**n):
for k in range(2**n):
qft[i,k] = np.exp(i*k*2*2j*np.pi/(2**n))
return(1/np.sqrt(2**n)*qft)
def QFTcircuit(n):
q = QuantumRegister(n, "q")
c = ClassicalRegister(n, "c")
qc = QFT(q, c, n)
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
actual = job.result().get_unitary()
np.around(actual, 2)
expected = QFTmatrix(n)
delta = actual - expected
print("Deviation: ", round(np.linalg.norm(delta), 10))
return qc
LaTex_folder_QFT = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Fourier_transform/'
if not os.path.exists(LaTex_folder_QFT):
os.makedirs(LaTex_folder_QFT)
else:
shutil.rmtree(LaTex_folder_QFT)
os.makedirs(LaTex_folder_QFT)
n=4
qc = QFTcircuit(n)
# create a LaTex file for the algorithm
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Quantum_Four_transform_'+str(n)+'qubits.tex'
with open(LaTex_folder_QFT+f_name, 'w') as f:
f.write(LaTex_code)
n = 4
q = QuantumRegister(n, "x")
c = ClassicalRegister(n, "c")
qftCircuit = QFT(q, c, n)
initCircuit = QuantumCircuit(q, c)
for qubit in q:
initCircuit.h(qubit)
initCircuit.barrier(q)
qc = QuantumCircuit.compose(initCircuit, qftCircuit)
qc.barrier(q)
qc.measure(q, c)
# on simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend)
k = job.result().get_counts()
print(k)
# on a real quantum computer
provider = IBMQ.load_account()
backend = provider.backend.ibmq_lima
print("Status of backened: ", backend.status())
job = execute(qc, backend=backend, shots = 1024)
lapse = 0
print("This step might take some time.")
time.sleep(3)
interval = 60
while((job.status().name != 'DONE')
and (job.status().name != 'Cancelled')
and (job.status().name != 'ERROR')):
print('Status @ {} seconds'.format(interval * lapse))
print(job.status())
print(job.queue_position())
time.sleep(interval)
lapse +=1
print(job.status())
plt = plot_histogram(job.result().get_counts())
|
https://github.com/kosakhro/QAOA-for-exact-cover
|
kosakhro
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 20:22:29 2020
@author: Arttu Huikuri
"""
from qiskit import *
from qiskit.visualization import plot_bloch_multivector
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Making the quantum circuit
def circuitI(gamma, beta, J, h1, h2):
qc = QuantumCircuit(2, 2)
qc.h([0, 1])
qc.h(1)
qc.cz(0,1)
qc.rx(2*gamma*J, 1)
qc.cz(0,1)
qc.h(1)
qc.i(0)
qc.rz(2*gamma*h1, 0)
qc.rz(2*gamma*h2, 1)
qc.rx(2*beta, 0)
qc.rx(2*beta, 1)
qc.measure([0,1], [0,1])
return qc
simulator = Aer.get_backend('qasm_simulator')
# Initializing the variables
h1 = 0
h2 = 0
J = 1
#Setting the dimesions of the pasephase. The amount of simulated points = n**2
n = 61
p = np.pi/(n-1)
res = np.zeros([n, n, 4])
# Running a simulation for each point
for i in range(n):
gamma = i*p
for j in range(n):
beta = j*p
qc = circuitI(gamma, beta, J, h1, h2)
counts = execute(qc, backend = simulator, shots=1000).result().get_counts()
res[i][j][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)),
int(counts.get('11', 0))])
# Making the heatmap plots
sns.heatmap(res[:, :, 0])
plt.xlabel('\u03B2, [0,\u03C0]')
plt.ylabel('\u03B3, [0,\u03C0]')
plt.title('00')
plt.figure(2)
sns.heatmap(res[:, :, 1])
plt.xlabel('\u03B2, [0,\u03C0]')
plt.ylabel('\u03B3, [0,\u03C0]')
plt.title('01')
plt.figure(3)
sns.heatmap(res[:, :, 2])
plt.xlabel('\u03B2, [0,\u03C0]')
plt.ylabel('\u03B3, [0,\u03C0]')
plt.title('10')
plt.figure(4)
sns.heatmap(res[:, :, 3])
plt.xlabel('\u03B2, [0,\u03C0]')
plt.ylabel('\u03B3, [0,\u03C0]')
plt.title('11')
plt.figure(5)
sns.heatmap(res[:, :, 2]+ res[:, :, 1])
plt.xlabel('\u03B2, [0,\u03C0]')
plt.ylabel('\u03B3, [0,\u03C0]')
plt.title('11 + 01')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
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 for core modules of pulse drawer."""
from qiskit import pulse, circuit
from qiskit.test import QiskitTestCase
from qiskit.visualization.pulse_v2 import events
class TestChannelEvents(QiskitTestCase):
"""Tests for ChannelEvents."""
def test_parse_program(self):
"""Test typical pulse program."""
test_pulse = pulse.Gaussian(10, 0.1, 3)
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.Play(test_pulse, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.Play(test_pulse, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
# check waveform data
waveforms = list(ch_events.get_waveforms())
inst_data0 = waveforms[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertEqual(inst_data0.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
inst_data1 = waveforms[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, 1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertEqual(inst_data1.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
# check frame data
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertListEqual(inst_data0.inst, [pulse.SetPhase(3.14, pulse.DriveChannel(0))])
inst_data1 = frames[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, -1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertListEqual(inst_data1.inst, [pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))])
def test_multiple_frames_at_the_same_time(self):
"""Test multiple frame instruction at the same time."""
# shift phase followed by set phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 3.14)
# set phase followed by shift phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 1.57)
def test_frequency(self):
"""Test parse frequency."""
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftFrequency(1.0, pulse.DriveChannel(0)))
sched = sched.insert(5, pulse.SetFrequency(5.0, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
ch_events.set_config(dt=0.1, init_frequency=3.0, init_phase=0)
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.freq, 1.0)
inst_data1 = frames[1]
self.assertAlmostEqual(inst_data1.frame.freq, 1.0)
def test_parameterized_parametric_pulse(self):
"""Test generating waveforms that are parameterized."""
param = circuit.Parameter("amp")
test_waveform = pulse.Play(pulse.Constant(10, param), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform}, frames={}, channel=pulse.DriveChannel(0)
)
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.inst, test_waveform)
def test_parameterized_frame_change(self):
"""Test generating waveforms that are parameterized.
Parameterized phase should be ignored when calculating waveform frame.
This is due to phase modulated representation of waveforms,
i.e. we cannot calculate the phase factor of waveform if the phase is unbound.
"""
param = circuit.Parameter("phase")
test_fc1 = pulse.ShiftPhase(param, pulse.DriveChannel(0))
test_fc2 = pulse.ShiftPhase(1.57, pulse.DriveChannel(0))
test_waveform = pulse.Play(pulse.Constant(10, 0.1), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform},
frames={0: [test_fc1, test_fc2]},
channel=pulse.DriveChannel(0),
)
# waveform frame
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertFalse(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, 1.57)
# framechange
pulse_inst = list(ch_events.get_frame_changes())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, param + 1.57)
def test_zero_duration_delay(self):
"""Test generating waveforms that contains zero duration delay.
Zero duration delay should be ignored.
"""
ch = pulse.DriveChannel(0)
test_sched = pulse.Schedule()
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(0, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(1, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
ch_events = events.ChannelEvents.load_program(test_sched, ch)
self.assertEqual(len(list(ch_events.get_waveforms())), 4)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
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("./")
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="lq")
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"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
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-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/euler16/Distinguishing-Unitary-Gates-on-IBM-Quantum-Processor
|
euler16
|
import sys, time
sys.path.append("../")
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
# Imports
import qiskit as qk
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, least_busy
from qiskit.tools.visualization import plot_histogram
from qiskit import IBMQ
from qiskit import Aer
from math import pi
print(qk.__version__)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr,cr)
# circuit construction
# preparing the wavefunction
qc.h(qr[0])
qc.barrier()
qc.cx(qr[0], qr[1])
qc.barrier()
qc.u3(1.2309,0,0,qr[0])
qc.barrier()
# if we apply phase shift gate
qc.u1((2.0/3)*pi,qr[0])
qc.u1((2.0/3)*pi,qr[1])
qc.barrier()
# rotating the axis for measurement
#qc.cx(qr[0],qr[1]) # THE IMPLEMENTATION PROVIDED BY THE AUTHORS SKIPS THIS CNOT APPLICATION!!! it shouldn't be
# it shouldn't be there. Improves accuracy
#qc.barrier()
qc.u3(2.1862,6.5449,pi,qr[0])
qc.u3(0.9553,2*pi,pi,qr[1])
qc.barrier()
qc.measure(qr,cr)
# Running locally IBM backends respond too slowly
print(Aer.backends())
backend = Aer.get_backend('qasm_simulator')
job = execute(qc,backend)
job.status
result = job.result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
performance = {
'success':(counts['01']+counts['10'])/1024,
'failure':1 - (counts['01']+counts['10'])/1024
}
plot_histogram(performance)
IBMQ.load_accounts()
# checking the backends
large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()['n_qubits'] > 1 and not x.configuration()['simulator'])
print(large_enough_devices)
backend = IBMQ.get_backend('ibmqx4')
job = execute(qc,backend,max_credits=3)
job.status
result = job.result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
performance = {
'success':(counts['01']+counts['10'])/1024,
'failure':(counts['00']+counts['11'])/1024
}
plot_histogram(performance)
sqr = QuantumRegister(1)
scr = ClassicalRegister(1)
sqc = QuantumCircuit(sqr,scr)
# constructing the circuit
sqc.u3(1.1503,6.4850,2.2555,sqr[0])
sqc.barrier()
# unidentified gate -- now assumed to be R2pi3. if identity then use qc.u1(0,q[0])
sqc.u1((2.0/3)*pi,sqr[0])
sqc.barrier()
sqc.u3(1.231,0,0,sqr[0]) # X
sqc.barrier()
sqc.u1((2.0/3)*pi,sqr[0]) # U (unidentified gate)
sqc.barrier()
# measurement
sqc.u3(0.7854,6.0214,6.1913,sqr[0])
sqc.barrier()
sqc.measure(sqr,scr)
# Running on local simulator
backend = Aer.get_backend('qasm_simulator')
job = execute(sqc,backend)
result = job.result()
counts = result.get_counts(sqc)
print(counts)
plot_histogram(counts)
# Running on IBM
backend = IBMQ.get_backend('ibmqx4')
job = execute(sqc,backend,max_credits=3)
result = job.result()
counts = result.get_counts(sqc)
print(counts)
plot_histogram(counts)
|
https://github.com/PaulaGarciaMolina/QNLP_Qiskit_Hackathon
|
PaulaGarciaMolina
|
import numpy as np
import pickle
from discopy import Ty, Word # Import the classes for the type of word and for the word
s, n = Ty('s'), Ty('n') # Define the types s and n
# Define the words
# Nouns
man, woman, kid = Word('man', n), Word('woman', n), Word('kid', n)
# Adjectives
morose, irascible = Word('morose', n @ n.l), Word('irascible', n @ n.l)
frightened, cheerful = Word('frightened', n @ n.l), Word('cheerful', n @ n.l)
gloomy, furious = Word('gloomy', n @ n.l), Word('furious', n @ n.l)
terrified, joyful = Word('terrified', n @ n.l), Word('joyful', n @ n.l)
downcast, miserable = Word('downcast', n @ n.l), Word('miserable', n @ n.l)
old, young = Word('old', n @ n.l), Word('young', n @ n.l)
# Intransitive verbs
cries, shouts = Word('cries', n.r @ s), Word('shouts', n.r @ s)
laughs, snaps = Word('laughs', n.r @ s), Word('snaps', n.r @ s)
# Transitive verbs
grieves, startles = Word('grieves', n.r @ s @ n.l), Word('startles', n.r @ s @ n.l)
entertains, irritates = Word('entertains', n.r @ s @ n.l), Word('irritates', n.r @ s @ n.l)
nouns = [man, woman, kid]
adjectives = [morose, irascible, frightened, cheerful, gloomy, furious, terrified, joyful, downcast, miserable, old, young]
int_verbs = [cries, shouts, laughs, snaps]
t_verbs = [grieves, startles, entertains, irritates]
vocab = nouns + int_verbs + t_verbs + adjectives
from discopy import Cup, Id, pregroup
grammar = Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s)
sentence = joyful @ woman @ laughs >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n)
sentence = woman @ grieves @ kid >> grammar
pregroup.draw(sentence)
grammar = Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s)
sentence = morose @ woman @ grieves @ kid >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)
sentence = man @ grieves @ morose @ man >> grammar
pregroup.draw(sentence)
# Store the grammatical structures in a dictionary
grammar_dict = {
'ADJ_N_IV' : Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s),
'N_TV_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n),
'ADJ_N_TV_N': Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s),
'N_TV_ADJ_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)}
# Create parsing (grammatical analysis) dictionary where the grammatical sentences
# are the keys and the associated values are the diagrams (words + grammar)
data_psr = {}
# Intransitive sentences
parsing_int = {"{} {} {}.".format(adj, noun, int_verb): adj @ noun @ int_verb >> grammar_dict['ADJ_N_IV']
for adj in adjectives for noun in nouns for int_verb in int_verbs}
sentences_int = list(parsing_int.keys())
for sentence in sentences_int:
diagram = parsing_int[sentence]
data_psr[sentence] = parsing_int[sentence]
# Transitive sentences (without adjective)
parsing_tra = {"{} {} {}.".format(subj, t_verb, obj): subj @ t_verb @ obj >> grammar_dict['N_TV_N']
for subj in nouns for t_verb in t_verbs for obj in nouns}
# Transitive sentences (with adjective)
parsing_tra_ladj = {"{} {} {} {}.".format(adj, subj, t_verb, obj): adj @ subj @ t_verb @ obj >> grammar_dict['ADJ_N_TV_N']
for adj in adjectives for subj in nouns for t_verb in t_verbs for obj in nouns}
parsing_tra_radj = {"{} {} {} {}.".format(subj, t_verb, adj, obj): subj @ t_verb @ adj @ obj >> grammar_dict['N_TV_ADJ_N']
for subj in nouns for t_verb in t_verbs for adj in adjectives for obj in nouns}
parsing_tra.update(parsing_tra_ladj) #merges transitive adjectives into original dict
parsing_tra.update(parsing_tra_radj)
sentences_tra = list(parsing_tra.keys())
for sentence in sentences_tra:
diagram = parsing_tra[sentence]
data_psr[sentence] = parsing_tra[sentence]
with open('../sentiment_analysis_dataset.txt') as f:
data = f.readlines()
labels_dict = {} # Dictionary with the labels for each sentence
data_psr_dict = {} # Dictionary with the parsing for each sentence
sent_type = {} # Dictionary with the sentence type for each sentence
adjective_words = [a.name for a in adjectives]
for sentence in data:
sentstr = sentence[:-7] #seperates the sentence string from the data at the end
if sentence[-6:-3] == 'int':
diagram = parsing_int[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
sent_type[sentstr] = 'int'
elif sentence[-6:-3] == 'tra':
diagram = parsing_tra[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
if len(sentstr.split()) == 4:
if sentstr.split()[0] in adjective_words:
sent_type[sentstr] = 'tra_' + 'l' #adjective on the left
else:
sent_type[sentstr] = 'tra_' + 'r' #adjective on the right
else:
sent_type[sentstr] = 'tra' #the simple transitive verb sentence type
c0 = 0
c1 = 0
c2 = 0
c3 = 0
for value in labels_dict.values():
if value == '0':
c0 +=1
elif value == '1':
c1 += 1
elif value == '2':
c2 += 1
elif value == '3':
c3 += 1
print('Number of elements for each sentiment')
print('Happy: ', c0)
print('Sad: ', c1)
print('Angry: ', c2)
print('Scared: ', c3)
print('Total: ', len(data_psr_dict))
from discopy import Cap, Box
# Code of this cell addapted from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
data_new_psr_dict = {}
for sentstr in data_psr_dict.keys():
num_words = len(sentstr.split(' '))
words = data_psr_dict[sentstr].boxes[:num_words]
if sent_type[sentstr] == 'int':
noun = Box(words[1].name, n.l, Ty())
words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2]) # Rearranged words
sentence = words_new >> grammar_dict['ADJ_N_IV'] # Apply grammar on rearranged words
data_new_psr_dict[sentstr] = sentence.normal_form() # Store sentece with optimum diagram
elif 'tra' in sent_type[sentstr]:
if sent_type[sentstr] == 'tra':
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[2].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_l': #adjective at beginning
noun1 = Box(words[1].name, n.l, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['ADJ_N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_r': #adjective on second noun
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_ADJ_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
vocab_psr = []
for word in vocab:
if word.cod == Ty('n'):
vocab_psr.append(Box(word.name, n.r, Ty())) # n.l case is dealt with in definition of quantum functor
else:
vocab_psr.append(word)
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#*****************************************************
# Translation to quantum circuits
#*****************************************************
from discopy.quantum import Ket, IQPansatz, Bra, qubit
from discopy.quantum.circuit import Functor, Id
from discopy.quantum.circuit import Circuit
from functools import reduce, partial
from discopy.quantum.gates import Rx, Rz
q_s = 1 # number of qubits for type s (sentence)
q_n = 1 # number of qubits for type n (noun)
depth = 1 # depth of the IQPansatz
p_n = 3 # number of parameters for the single qubit iqp ansatz
# Define the dimensions of the objects of the circuit functor
ob = {s: q_s, n: q_n}
ob_cqmap = {s: qubit ** q_s, n: qubit ** q_n}
#-----------------------------------------
# parametrised part of ansaetze
#-----------------------------------------
def single_qubit_iqp_ansatz(params):
if len(params) == 1:
return Rx(params[0])
if len(params) == 2:
return Rx(params[0]) >> Rz(params[1])
if len(params) == 3:
return IQPansatz(1, params)
def ansatz_state(state, params):
arity = sum(ob[Ty(factor.name)] for factor in state.cod)
if arity == 1:
return Ket(0) >> single_qubit_iqp_ansatz(params)
return Ket(*tuple([0 for i in range(arity)])) >> IQPansatz(arity, params)
def ansatz_effect(effect, params):
arity = sum(ob[Ty(factor.name)] for factor in effect.dom)
if arity == 1:
return single_qubit_iqp_ansatz(params) >> Bra(0)
return IQPansatz(arity, params) >> Bra(*tuple([0 for i in range(arity)]))
def ansatz(box,params):
dom_type = box.dom
cod_type = box.cod
if len(dom_type) == 0 and len(cod_type) != 0:
return ansatz_state(box, params)
if len(dom_type) != 0 and len(cod_type) == 0:
return ansatz_effect(box, params)
#----------------------------------------------------------
# Define parametrised functor to quantum circuits
#----------------------------------------------------------def F(params):
def F(params):
ar = dict()
for i in range(len(vocab_psr)):
pgbox = vocab_psr[i]
qbox = ansatz(vocab_psr[i], params[i])
ar.update({pgbox: qbox})
if pgbox.cod == Ty():
ar.update({Box(pgbox.name, n.l, Ty()): qbox}) # send the effect with n.l to same quantum effect
return Functor(ob_cqmap, ar)
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#*****************************************************
# Functions to deal with the parametrisation
#*****************************************************
def paramshapes(vocab_psr):
parshapes = []
for box in vocab_psr:
dom_type = box.dom
cod_type = box.cod
dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom)
cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod)
if dom_arity == 0 or cod_arity == 0: # states and effects
arity = max(dom_arity, cod_arity)
assert arity != 0
if arity == 1:
parshapes.append((p_n,))
if arity != 1:
parshapes.append((depth, arity-1))
return parshapes
def randparams(par_shapes):
params = np.array([])
for i in range(len(par_shapes)):
params = np.concatenate((params, np.ravel(np.random.rand(*par_shapes[i])))) # np.ravel flattens an array
return params
def reshape_params(unshaped_pars, par_shapes):
pars_reshaped = [[] for ii in range(len(par_shapes))]
shift = 0
for ss, s in enumerate(par_shapes):
idx0 = 0 + shift
if len(s) == 1:
idx1 = s[0] + shift
elif len(s) == 2:
idx1 = s[0] * s[1] + shift
pars_reshaped[ss] = np.reshape(unshaped_pars[idx0:idx1], s)
if len(s) == 1:
shift += s[0]
elif len(s) == 2:
shift += s[0] * s[1]
return pars_reshaped
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#****************************************
# Parameters of the current model
#****************************************
par_shapes = paramshapes(vocab_psr)
rand_unshaped_pars = randparams(par_shapes)
rand_shaped_pars = reshape_params(rand_unshaped_pars, par_shapes)
print('Number of parameters: ', len(rand_unshaped_pars))
from sklearn.model_selection import train_test_split
psr_diagrams = []
psr_diagrams_dict = {}
psr_labels = []
sentences = []
for sentstr in data_new_psr_dict.keys():
sentences.append(sentstr)
diagram = data_new_psr_dict[sentstr]
psr_diagrams.append(diagram)
psr_diagrams_dict[sentstr] = diagram
if labels_dict[sentstr] == '0':
label = np.array([1,0])
elif labels_dict[sentstr] == '1':
label = np.array([0,1])
psr_labels.append(label)
train_data_psr, test_data_psr, train_labels, test_labels = \
train_test_split(psr_diagrams, psr_labels, test_size=0.25, random_state=42)
from qiskit import BasicAer, execute, ClassicalRegister
from pytket.extensions.qiskit import tk_to_qiskit
from qiskit.quantum_info import Statevector
#from qiskit import IBMQ
#from qiskit.providers.aer.noise import NoiseModel
backend = BasicAer.get_backend('qasm_simulator')
noise_model = None
coupling_map = None
basis_gates= None
## Build noise model from backend properties
#provider = IBMQ.load_account()
#backend = provider.get_backend('ibmq_16_melbourne')
#noise_model = NoiseModel.from_backend(backend)
## Get coupling map from backend
#coupling_map = backend.configuration().coupling_map
## Get basis gates from noise model
#basis_gates = noise_model.basis_gates
#backend = Aer.get_backend('qasm_simulator')
max_shots = 8192
#with open(f'./noise_model_melbourne.pkl', "rb") as fp:
#data = pickle.load(fp)
#noise_model, coupling_map, basis_gates = data[0], data[1], data[2]
from qiskit import Aer
def get_qiskit_results(circ, s_type, retries=10, qasm=False, noise_model=None,
basis_gates=None, coupling_map=None, max_shots=8192):
"""Function to get the Qiskit's results from a DisCoPy circuit.
Args:
circ = DisCoPy circuit.
s_type = sentence type for the sentence associated to the circuit.
retries = number of retries before assigning a random result
if the postselection leads to zero values (Default is 10).
qasm = if True qasm_simulator is used, if not statevector_simulator
(Default is False).
noise_model = Qiskit's noise model object (Default is None).
basis_gates = basis gates of the device (Default is None).
coupling_map = coupling_map of the device (Default is None).
max_shots = number of shots (Default is 8192).
Returns:
array: results from the postselection measurement.
"""
# Select qubits for postselection according to the sentence type
if s_type == 'int':
n_qubits = 4
post = 2
elif s_type == 'tra':
n_qubits = 3
post = 1
elif s_type == 'tra_l':
n_qubits = 5
post = 2
else:
assert s_type == 'tra_r'
n_qubits = 5
post = 1
# From DisCoPy to Qiskit circuit
qc = tk_to_qiskit(circ.to_tk())
if qasm == True:
#qasm_simulator
out_reg = ClassicalRegister(1)
qc.add_register(out_reg)
qc.measure(post, out_reg[0])
if noise_model is not None:
backend = Aer.get_backend('qasm_simulator')
# Include noise model
results = execute(qc, backend, shots=max_shots, noise_model=noise_model,
coupling_map=coupling_map,basis_gates=basis_gates).result().get_counts()
else:
backend = BasicAer.get_backend('qasm_simulator')
results = execute(qc, backend, shots=max_shots).result().get_counts()
zeros = '0' * (n_qubits - 1)
if '0 ' + zeros not in results and '1 ' + zeros not in results:
if retries == 0:
return np.random.rand(2)
return get_qiskit_results(circ, s_type, retries=retries-1, qasm = qasm,
noise_model=noise_model, coupling_map=coupling_map,
basis_gates=basis_gates, max_shots = max_shots)
return parse_results(results, eff=zeros)
else:
# statevector_simulator
qc.remove_final_measurements()
state_dict = Statevector(qc).to_dict()
post0, post1 = '0' * n_qubits, '0' * n_qubits
post1 = post1[:post] + '1' + post1[post + 1:]
return [np.abs(state_dict[post0])**2, np.abs(state_dict[post1])**2]
def parse_results(results, eff='0'):
"""Parse results of qasm_simulator.
Args:
results: counts from quantum circuit's measurement.
eff: digits for splitting the results for post selection.
Returns:
array: post selected results.
"""
ks = [k for k in results.keys() if k.split()[1] == eff]
post_selected_results = {k.split()[0]:v for (k,v) in results.items() if k in ks}
if '0' not in post_selected_results:
post_selected_results['0'] = 0
if '1' not in post_selected_results:
post_selected_results['1'] = 0
total = post_selected_results['0'] + post_selected_results['1']
assert total > 0, 'total was 0 after postselection - try running with more shots'
return [post_selected_results['0']/total, post_selected_results['1']/total]
def process_dataset(dataset):
""" Process a QNLP dataset.
Args:
dataset: txt dataset to be processed.
Returns:
psr_diagrams: parsing diagrams.
psr_labels: labels.
sentences: sentences.
sent_type: dictionary with the sentence type for each sentence.
"""
with open(dataset) as f:
data = f.readlines()
labels_dict = {} # Dictionary with the labels for each sentence
data_psr_dict = {} # Dictionary with the parsing for each sentence
sent_type = {} # Dictionary with the sentence type for each sentence
# Create the previous dictionaries from the given dataset
adjective_words = [a.name for a in adjectives]
for sentence in data:
sentstr = sentence[:-7]
if sentence[-6:-3] == 'int':
diagram = parsing_int[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
sent_type[sentstr] = 'int'
elif sentence[-6:-3] == 'tra':
diagram = parsing_tra[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
if len(sentstr.split()) == 4:
if sentstr.split()[0] in adjective_words:
sent_type[sentstr] = 'tra_' + 'l'
else:
sent_type[sentstr] = 'tra_' + 'r'
else:
sent_type[sentstr] = 'tra'
# Rearrange the parsing of the diagrams
data_new_psr_dict = {}
for sentstr in data_psr_dict.keys():
num_words = len(sentstr.split(' '))
words = data_psr_dict[sentstr].boxes[:num_words]
if sent_type[sentstr] == 'int':
noun = Box(words[1].name, n.l, Ty())
words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2]) # Rearranged words
sentence = words_new >> grammar_dict['ADJ_N_IV'] # Apply grammar on rearranged words
data_new_psr_dict[sentstr] = sentence.normal_form() # Store sentece with optimum diagram
elif 'tra' in sent_type[sentstr]:
if sent_type[sentstr] == 'tra':
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[2].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_l': #adjective at beginning
noun1 = Box(words[1].name, n.l, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['ADJ_N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_r': #adjective on second noun
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_ADJ_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
# Store the diagrams, labels and sentences for the classification
psr_diagrams = []
psr_diagrams_dict = {}
psr_labels = []
sentences = []
for sentstr in data_new_psr_dict.keys():
sentences.append(sentstr)
diagram = data_new_psr_dict[sentstr]
psr_diagrams.append(diagram)
psr_diagrams_dict[sentstr] = diagram
if labels_dict[sentstr] == '0':
label = np.array([1,0])
elif labels_dict[sentstr] == '1':
label = np.array([0,1])
psr_labels.append(label)
return psr_diagrams, psr_labels, sentences, sent_type
from qiskit.aqua.components.optimizers import SPSA
import time
def QNLP_optimize(dataset, initial_point, n_iterations, cost_function, qasm_bool=False,
noise_model=None, coupling_map=None, basis_gates=None, max_shots = 8192):
""" Optimize a QNLP dataset.
Args:
dataset = dataset for the optimization.
initial_point = initial value of the parameters.
niter = number of iterations for SPSA optimizer.
cost_function = cost function for the optimization
qasm_bool: if True qasm_simulator is used, if not
statevector_simulator (Default is False).
Returns:
list: Qiskit's SPSA results.
cost_save: cost of each evaluation of the cost function.
params_save: parameters of each evaluation of the cost function.
"""
# Obtain the data from the dataset
train_data_psr, train_labels, train_sent, sent_type = process_dataset(dataset)
# Qiskit's SPSA parameters
num_vars = len(initial_point)
bounds = [[0.0, 1.0] for _ in range(len(initial_point))]
# Initialize cost function global parameters
cost_save = []
params_save = []
i_cost = []
# Choose cost function
if cost_function == 'cost_train':
def get_cost_train_error(unshaped_params):
""" Cost function using training error.
Args:
unshaped_params: parameters for the optimization.
Returns:
float: cost.
"""
# Print iterations
i_cost.append(1)
if len(i_cost) % 2 == 0:
print('Iteration', len(i_cost)/2)
# Create functor to construct DisCoPy circuits
func = F(reshape_params(unshaped_params, par_shapes))
circs = [func(diag) for diag in train_data_psr]
# Get Qiskit's results
results = np.array([get_qiskit_results(circs[i], sent_type[train_sent[i]], qasm = qasm_bool,
noise_model=noise_model, coupling_map=coupling_map,
basis_gates=basis_gates, max_shots=max_shots) for i in range(len(train_sent))])
#Tweak results
results_tweaked = [np.abs(np.array(res) - 1e-9) for res in results]
pred_labels_distrs = [res.flatten() / np.sum(res) for res in results_tweaked]
# Compute cost
error = 0
for i, r in enumerate(pred_labels_distrs):
error += int(np.argmax(r) != np.argmax(train_labels[i]))
# Print cost
print('Cost', error/len(pred_labels_distrs))
# Save cost and parameters
cost_save.append(error/len(pred_labels_distrs))
params_save.append(unshaped_params)
return error/len(pred_labels_distrs)
get_cost = get_cost_train_error
elif cost_function == 'cost_entropy':
def get_cost_cross_entropy(unshaped_params):
""" Cost function using cross entropy.
Args:
unshaped_params: parameters for the optimization.
Returns:
float: cost.
"""
# Print iterations
i_cost.append(1)
if len(i_cost) % 2 == 0:
print('Iteration', len(i_cost)/2)
# Create functor to construct DisCoPy circuits
func = F(reshape_params(unshaped_params, par_shapes))
circs = [func(diag) for diag in train_data_psr]
# Get Qiskit's results
results = np.array([get_qiskit_results(circs[i], sent_type[train_sent[i]], qasm = qasm_bool,
noise_model=noise_model, coupling_map=coupling_map,
basis_gates=basis_gates, max_shots=max_shots) for i in range(len(train_sent))])#Tweak results
results_tweaked = [np.abs(np.array(res) - 1e-9) for res in results]
pred_labels_distrs = [res.flatten() / np.sum(res) for res in results_tweaked]
# Compute cost
cross_entropies = np.array([np.sum(train_labels[s] * np.log2(pred_labels_distrs[s])) for s in range(len(train_labels))])
# Print cost
print('Cost', -1 / len(train_data_psr) * np.sum(cross_entropies))
# Save cost and parameters
cost_save.append(-1 / len(train_data_psr) * np.sum(cross_entropies))
params_save.append(unshaped_params)
return -1 / len(train_data_psr) * np.sum(cross_entropies)
get_cost = get_cost_cross_entropy
else:
raise NameError('No valid cost function name.')
# Optimization
t1 = time.time()
opt = SPSA(maxiter=n_iterations)
ps = opt.optimize(num_vars, get_cost, initial_point=initial_point, variable_bounds=bounds)
print("Final time", time.time() - t1)
if qasm_bool == True:
simul = 'qasm'
else:
simul = 'statevector'
pickle.dump([ps, cost_save, params_save],
open(f"sentiment_analysis_1vs1_{dataset[16:-4]}_{str(cost_function)}_niter{n_iterations}_{simul}.pkl", "wb"))
return ps, cost_save, params_save
datasets = ['train_happy_vs_sad.txt', 'train_happy_vs_angry.txt', 'train_happy_vs_scared.txt',
'train_sad_vs_angry.txt', 'train_sad_vs_scared.txt', 'train_angry_vs_scared.txt']
n_iterations = 1
cost_function = 'cost_train'
initial_point = randparams(par_shapes)
for dataset in datasets:
dataset = './1vs1_datasets/' + dataset
qasm_bool = False
results = QNLP_optimize(dataset,initial_point, n_iterations, cost_function, qasm_bool=qasm_bool,
noise_model=noise_model, coupling_map=coupling_map,
basis_gates=basis_gates, max_shots=max_shots)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
from qiskit import converters
from qiskit import qasm
from .utils import random_circuit
class ConverterBenchmarks:
params = ([1, 2, 5, 8, 14, 20, 32, 53], [8, 128, 2048, 8192])
param_names = ["n_qubits", "depth"]
timeout = 600
def setup(self, n_qubits, depth):
seed = 42
# NOTE: Remove the benchmarks larger than 20x2048 and 14x8192, this is
# a tradeoff for speed of benchmarking, creating circuits this size
# takes more time than is worth it for benchmarks that take a couple
# seconds
if n_qubits >= 20:
if depth >= 2048:
raise NotImplementedError
elif n_qubits == 14:
if depth > 2048:
raise NotImplementedError
self.qc = random_circuit(n_qubits, depth, measure=True, conditional=True, seed=seed)
self.dag = converters.circuit_to_dag(self.qc)
self.qasm = qasm.Qasm(data=self.qc.qasm()).parse()
def time_circuit_to_dag(self, *_):
converters.circuit_to_dag(self.qc)
def time_circuit_to_instruction(self, *_):
converters.circuit_to_instruction(self.qc)
def time_dag_to_circuit(self, *_):
converters.dag_to_circuit(self.dag)
def time_ast_to_circuit(self, *_):
converters.ast_to_dag(self.qasm)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# create qubit using quantum registers
qr = QuantumRegister(2)
# create classical register to take measurement of `qr`
cr = ClassicalRegister(2)
# build a circuit
qc = QuantumCircuit(qr, cr)
# visualize the circuit to know how it's looks like or there any modification init ?
qc.draw()
# to add gates into the circuit so that
# to build entanglement in circuit we uses hadamard gate : H
qc.h(0)
qc.draw(output='mpl')
# two qubit controlled operation gate : CNOT gate
# cx(c_1, t) it controls the c_1 qubit and target the t qubit
qc.cx(0, 1)
#qc.cx(qr[0],qr[1])
qc.draw(output='mpl')
# to measure the qubits and store into classical bits
qc.measure(qr, cr)
qc.draw(output='mpl')
# How to run this quantum circuit on classical computer or quantum simulator
# used qiskit's Aer Simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator).result()
plot_histogram(result.get_counts(qc))
# How to run this qunatum circuit on the Quantum computer
# IBM's Quantum Computer
# We access it from cloud using an api call with our account on the ibm experieance
#loading our ibm account
IBMQ.load_account('API_Key')
#
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmqx2')
job = execute(qc, backend=qcomp)
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(qc))
"""
Question : Why there is a difference in output in executing quantum circuit on simulator and on actual quantum device ?
Question : What is the difference b/w the Quantum Simulator and a Quantum Computer ?
"""
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spin_orbitals = 10
from qiskit_nature.second_q.circuit.library import UCCSD
ansatz = UCCSD()
ansatz.num_spatial_orbitals = 5
from qiskit_nature.circuit.library import UCC, UVCC
ucc = UCC(qubit_converter=None, num_particles=None, num_spin_orbitals=None, excitations=None)
uvcc = UVCC(qubit_converter=None, num_modals=None, excitations=None)
from qiskit_nature.second_q.circuit.library import UCC, UVCC
ucc = UCC(num_spatial_orbitals=None, num_particles=None, excitations=None, qubit_converter=None)
uvcc = UVCC(num_modals=None, excitations=None, qubit_converter=None)
from qiskit_nature.circuit.library import HartreeFock, VSCF
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import DirectMapper, JordanWignerMapper
hf = HartreeFock(
num_spin_orbitals=4, num_particles=(1, 1), qubit_converter=QubitConverter(JordanWignerMapper())
)
vscf = VSCF(num_modals=[2, 2])
from qiskit_nature.second_q.circuit.library import HartreeFock, VSCF
from qiskit_nature.second_q.mappers import DirectMapper, JordanWignerMapper, QubitConverter
hf = HartreeFock()
hf.num_spatial_orbitals = 2
hf.num_particles = (1, 1)
hf.qubit_converter = QubitConverter(JordanWignerMapper())
vscf = VSCF()
vscf.num_modals = [2, 2]
from qiskit.providers.basicaer import BasicAer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms.ground_state_solvers import VQEUCCFactory
quantum_instance = QuantumInstance(BasicAer.get_backend("statevector_simulator"))
vqe_factory = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import VQEUCCFactory
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver, VQEUCCFactory
from qiskit_nature.algorithms.excited_states_solvers import QEOM
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
vqe_factory = VQEUCCFactory()
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver)
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms.ground_state_solvers import (
GroundStateEigensolver,
VQEUCCFactory,
)
from qiskit_nature.second_q.algorithms.excited_states_solvers import QEOM
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
estimator = Estimator()
ansatz = UCCSD()
optimizer = SLSQP()
vqe_factory = VQEUCCFactory(estimator, ansatz, optimizer)
converter = QubitConverter(JordanWignerMapper())
ground_state_solver = GroundStateEigensolver(converter, vqe_factory)
qeom = QEOM(ground_state_solver, estimator)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
import numpy as np
from scipy.linalg import sqrtm
Dag = lambda matrix: matrix.conj().T
def D(rou, sigma):
A = rou - sigma
A_ = sqrtm( np.dot( A.conj().T, A ) )
return 0.5 * np.linalg.norm( np.trace(A_) )
def d(A, rou, sigma):
distance = 0
for output in A.O:
trace = np.trace(
Dag(A.M[output]) @ A.M[output] @
(A.E @ (rou - sigma) @ Dag(A.E))
)
distance += np.linalg.norm(trace)
return distance / 2
|
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/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate,Initialize
from qiskit.quantum_info import Statevector
from qiskit.compiler import assemble
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
import os
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education')
simulator = Aer.get_backend('qasm_simulator')
athens = provider.get_backend('ibmq_athens')
class global_max_SPEA():
def __init__(self,unitary,resolution = 100, error = 3, max_iters = 20):
# handle resolution
if not isinstance(resolution,int):
raise TypeError("Please enter the number of intervals as an integer value")
if resolution < 10 or resolution > 1e6:
raise ValueError("Resolution needs to be atleast 0.1 and greater than 0.000001")
self.resolution = resolution
# handle unitary
if not isinstance(unitary, np.ndarray) and not isinstance(unitary, QuantumCircuit)\
and not isinstance(unitary, UnitaryGate):
raise TypeError("A numpy array or Quantum Circuit or UnitaryGate needs to be passed as the unitary matrix")
# convert circuit to numpy array for uniformity
if isinstance(unitary, UnitaryGate):
U = unitary.to_matrix()
else: # both QC and ndarray type
U = unitary
# note - the unitary here is not just a single qubit unitary
if isinstance(U,np.ndarray):
self.dims = U.shape[0]
else:
self.dims = 2**(U.num_qubits)
if isinstance(U,np.ndarray):
self.c_unitary_gate = UnitaryGate(data = U).control(num_ctrl_qubits = 1,label = 'CU',ctrl_state = '1')
else:
self.c_unitary_gate = U.control(num_ctrl_qubits = 1,label = 'CU',ctrl_state = '1')
# handle error
if not isinstance(error,int):
raise TypeError("The allowable error should be provided as an int. Interpreted as 10**(-error)")
if error <= 0:
raise ValueError("The error threshold must be finite and greater than 0.")
self.error = error
# handle max_iters
if not isinstance(max_iters,int):
raise TypeError("Max iterations must be of integer type")
if max_iters <= 0 and max_iters > 1e5:
raise ValueError("Max iterations should be atleast 1 and less than 1e5")
self.iterations = max_iters
self.basis = []
def get_basis_vectors(self,randomize = True):
# get the d dimensional basis for the unitary provided
if randomize == True:
UR = unitary_group.rvs(self.dims)
else:
UR = np.identity(self.dims)
basis = []
for k in UR:
basis.append(np.array(k,dtype = complex))
return basis
def get_unitary_circuit(self, backend):
'''Return the pretranspiled circuit '''
if backend is None:
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(1 + int(np.log2(self.dims)))
# make the circuit
qc.h(0)
qc = qc.compose(self.c_unitary_gate, qubits=range(
1+int(np.log2(self.dims))))
qc.barrier()
qc = transpile(qc,backend=backend,optimization_level = 3)
return qc
def get_circuit(self, state, backend, angle=None):
'''Given an initial state ,
return the circuit that is generated with
inverse rotation '''
# all theta values are iterated over for the same state
phi = Initialize(state)
shots = 512
qc1 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
# initialize the circuit
qc1 = qc1.compose(phi, qubits=list(
range(1, int(np.log2(self.dims))+1)))
qc1 = transpile(qc1, backend=backend,optimization_level=1)
# get the circuit2
qc2 = self.unitary_circuit
qc3 = QuantumCircuit(1 + int(np.log2(self.dims)), 1)
if angle is not None:
# add inverse rotation on the first qubit
qc3.p(-2*np.pi*angle, 0)
# add hadamard
qc3.h(0)
qc3 = transpile(qc3, backend=backend,optimization_level=1)
# make final circuit
qc = qc1 + qc2 + qc3
# measure
qc.measure([0], [0])
return qc
def get_standard_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle
state is a normalized state in ndarray form'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
phi = Initialize(state)
circuits = []
for theta in angles:
qc = self.get_circuit(state,backend,theta)
circuits.append(qc)
circuits = assemble(circuits)
# execute only once...
counts = backend.run(circuits, shots=shots).result().get_counts()
# get the cost for this theta
for k, theta in zip(counts, angles):
# for all experiments you ran
try:
C_val = (k['0'])/shots
except:
C_val = 0
if C_val > result['cost']:
# means this is a better theta value
result['theta'] = theta
result['cost'] = C_val
return result
def get_alternate_cost(self, angles, state, backend,shots):
'''Given an initial state and a set of angles,
return the best cost and the associated angle
state is a normalized state in ndarray form'''
result = {'cost': -1, 'theta': -1}
# all theta values are iterated over for the same state
phi = Initialize(state)
qc = self.get_circuit(state,backend)
qc = assemble(qc)
# execute only once...
counts = backend.run(qc, shots=shots).result().get_counts()
# generate experimental probabilities
try:
p0 = counts['0']/shots
except:
p0 = 0
try:
p1 = counts['1']/shots
except:
p1 = 0
# now, find the best theta as specified by the
# alternate method classically
min_s = 1e5
for theta in angles:
# generate theoretical probabilities
c0 = (np.cos(np.pi*theta))**2
c1 = (np.sin(np.pi*theta))**2
# generate s value
s = (p0-c0)**2 + (p1-c1)**2
if s < min_s:
result['theta'] = theta
min_s = s
# now , we have the best theta stored in phi
# run circuit once again to get the value of C*
qc = self.get_circuit(state, backend, result['theta'])
qc = assemble(qc)
counts = backend.run(qc, shots=shots).result().get_counts()
try:
result['cost'] = counts['0']/shots
except:
result['cost'] = 0
# no 0 counts presenta
# return the result
return result
def get_eigen_pair(self,backend,algo = 'alternate',progress = False,randomize = True,
basis=None,basis_ind = None, shots=512):
'''Finding the eigenstate pair for the unitary'''
#handle algorithm...
self.unitary_circuit = self.get_unitary_circuit(backend)
if not isinstance(algo,str):
raise TypeError("Algorithm must be mentioned as a string from the values {alternate,standard}")
elif algo not in ['alternate','standard']:
raise ValueError("Algorithm must be specified as 'alternate' or 'standard' ")
# handle progress...
if not isinstance(progress,bool):
raise TypeError("Progress must be a boolean variable")
if not isinstance(randomize,bool):
raise Exception("Randomize must be a boolean variable")
results = dict()
# first initialize the state phi
if basis is None:
self.basis = self.get_basis_vectors(randomize)
else:
# is basis is specified, given as array of vectors...
self.basis = basis
# choose a random index
if basis_ind is None:
ind = np.random.choice(self.dims)
else:
# choose the index given in that basis
ind = basis_ind
phi = self.basis[ind]
# doing the method 1 of our algorithm
# define resolution of angles and precision
precision = 1/10**self.error
samples = self.resolution
# initialization of range
left,right = 0,1
# generate the angles
angles = np.linspace(left,right,samples)
# iterate once
if algo == 'alternate':
result = self.get_alternate_cost(angles,phi,backend,shots)
else:
result = self.get_standard_cost(angles,phi,backend,shots)
# get initial estimates
cost = result['cost']
theta_max = result['theta']
best_phi = phi
# the range upto which theta extends iin each iteration
angle_range = 0.5
# a parameter
a = 1
# start algorithm
iters = 0
found = True
plus = (1/np.sqrt(2))*np.array([1,1])
minus = (1/np.sqrt(2))*np.array([1,-1])
while 1 - cost >= precision:
# get angles, note if theta didn't change, then we need to
# again generate the same range again
right = min(1,theta_max + angle_range/2)
left = max(0,theta_max - angle_range/2)
if progress:
print("Right :",right)
print("Left :",left)
# generate the angles only if the theta has been updated
if found == True:
angles = np.linspace(left,right,samples)
found = False # for this iteration
if progress:
print("ITERATION NUMBER",iters+1,"...")
# generate a cost dict for each of the iterations
thetas, costs, states = [],[],[]
for i in range((2*self.dims)):
# everyone is supplied with the same range of theta in one iteration
#define z
if i < self.dims:
z = 1
else:
z = 1j
# alter and normalise phi
curr_phi = best_phi + z*a*(1 - cost)*self.basis[i % self.dims]
curr_phi = curr_phi / np.linalg.norm(curr_phi)
# iterate (angles would be same until theta is changed)
if algo == 'alternate':
res = self.get_alternate_cost(angles,curr_phi,backend,shots)
else:
res = self.get_standard_cost(angles,curr_phi,backend,shots)
curr_cost = res['cost']
curr_theta = res['theta']
# append these parameters
# bundle the circuits together ...
if curr_cost > cost: # then only add this cost in the cost and states list
thetas.append(float(curr_theta))
costs.append(float(curr_cost))
states.append(curr_phi)
found = True
# now each iteration would see the same state as the best phi
# is updated once at the end of the iteration
# also, the cost is also updated only once at the end of the iteration
if progress:
sys.stdout.write('\r')
sys.stdout.write("%f %%completed" % (100*(i+1)/(2*self.dims)))
sys.stdout.flush()
# 1 iteration completes
if found == False:
# phi was not updated , change a
a = a/2
if progress:
print("\nNo change, updating a...")
else:
# if found is actually true, then only update
# O(n) , would update this though
index = np.argmax(costs)
# update the parameters of the model
cost = costs[index]
theta_max = thetas[index]
best_phi = states[index]
if progress:
print("Best Phi is :",best_phi)
print("Theta estimate :",theta_max)
print("Current cost :",cost)
angle_range /= 2 # updated phi and thus theta too -> refine theta range
# update the iterations
iters+=1
if progress:
print("\nCOST :",cost)
print("THETA :",theta_max)
if iters >= self.iterations:
print("Maximum iterations reached for the estimation.\nTerminating algorithm...")
break
# add cost, eigenvector and theta to the dict
results['cost'] = cost
results['theta'] = theta_max
results['state'] = best_phi
return results
simulator = Aer.get_backend('qasm_simulator')
U = QuantumCircuit(2)
U.cp(2*np.pi*(1/3),0,1)
U.draw('mpl')
spe = global_max_SPEA(U,resolution= 40,error = 3,max_iters=15)
# O(max_iters*(shots+resolution)*|Bm|)
result = spe.get_eigen_pair(progress = False,algo = 'alternate',backend=simulator,shots=512)
result
U = QuantumCircuit(3)
U.cp(2*np.pi*(1/3),1,2)
U.draw('mpl')
errors = []
eigvals = np.array([0.0,1/3,1.0])
for resolution in range(10,80,10):
spe = global_max_SPEA(U,resolution= resolution,error = 4,max_iters=15)
res = spe.get_eigen_pair(backend = simulator)
theta = res['theta']
min_error = 1e5
# get percentage error
for e in eigvals:
error = abs(e-theta)
if error < min_error:
min_error = error
if e != 0:
perc_error = (error/e)*100
else:
perc_error = error*100
errors.append(perc_error)
plt.title("Eigenphase estimation for theta = 1/3, 0, 1 (3-qubit unitary)",fontsize = 15)
plt.grid()
plt.plot(list(range(10,80,10)),errors,marker = 'o',color='g',label = 'Estimates',alpha=0.7)
# plt.plot([10,80],[0.25,0.25],color='black',label = "True")
# plt.plot([10,80],[0,0],color='black',label = "True")
# plt.plot([10,80],[1,1],color='black',label = "True")
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Errors from closest eigvals")
plt.savefig("Alternate_SPE_PLOT_1.jpg",dpi = 200)
U = QuantumCircuit(2)
U.cp(2*np.pi*(1/2),0,1)
U.draw('mpl')
eigvals = np.array([0.0,1/2,1.0])
errors = []
for resolution in range(10,80,10):
spe = global_max_SPEA(U,resolution= resolution,error = 3,max_iters=12)
#run 5 experiments of this
p_errors = []
for exp in range(4):
res = spe.get_eigen_pair(progress = False,backend = simulator)
theta = res['theta']
min_error = 1e5
min_val = -1
# get min error
for e in eigvals:
error = abs(e-theta)
if error < min_error:
min_error = error
min_val = e
# percent error in this experiment
if min_val!=0:
p_errors.append((min_error/min_val)*100)
else:
p_errors.append((min_error)*100)
print("Percentage Errors in current iteration:",p_errors)
errors.append(np.average(p_errors))
print("Errors :",errors)
plt.title("Eigenphase estimation for theta = 1/2, 0.0, 1.0 (2-qubit unitary)",fontsize = 15)
plt.grid()
plt.plot(list(range(10,80,10)),errors,marker = 'o',color='orange',label = 'Estimates',alpha=0.7)
# plt.plot([10,80],[0.25,0.25],color='black',label = "True")
# plt.plot([10,80],[0,0],color='black',label = "True")
# plt.plot([10,80],[1,1],color='black',label = "True")
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Errors from closest eigvals")
plt.savefig("Alternate_SPE_PLOT_2(simulator).jpg",dpi = 200)
|
https://github.com/EusseJhoan/DeutschJosza_algorithm
|
EusseJhoan
|
from qiskit import QuantumCircuit, transpile, Aer
from qiskit.visualization import plot_histogram
import numpy as np
sim = Aer.get_backend('aer_simulator')
def U_f1(qc):
return qc
def U_f2(qc):
qc.x(1) #Compuerta X al segundo qubit
return qc
def U_f3(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
return qc
def U_f4(qc):
qc.cx(0,1) #Compuerta CNOT entre primer y segundo quibit (el primero es el que controla)
qc.x(1) #Compuerta X al segundo qubit
return qc
def Deutsch(U_f):
qc=QuantumCircuit(2,1) #Se crea un circuito cuántico con 2 bits cuánticos y 1 canal clásico
qc.x(1) #Compuerta X al segundo qubit (inicializar estado |1>)
qc.h(0) #Compuerta H al primer qubit
qc.h(1) #Compuerta H al segundo qubit
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
qc.h(0) #Compuerta H al primer qubit
qc.measure(0,0) #Medimos el primer qubit y enviamos señal al canal clásico
return qc
qc=Deutsch(U_f1) # definición circuito con oráculo usando f_1(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f2) #definición circuito con oráculo usando f_2(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas del simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f3) #definición circuito con oráculo usando f_3(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=Deutsch(U_f4) #definición circuito con oráculo usando f_4(x)
display(qc.draw()) # visualización del circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
#oráculo para f(x) constante para un número n de bits en el registro
def constant(qc,n):
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
#oráculo para f(x) balanceado para un número n de bits en el registro
def balanced(qc,n):
for i in range(n):
qc.cx(i,n) #se crea una CNOT entre cada qubit del registro y el objetivo (los qubits del registro controlan)
ran=np.random.randint(2) #selección aleatoria de 0 ó 1
if ran == 1:
qc.x(n) #si el número aleatorio es 1 se pone compuerta X en el objetivo (se induce fase global -1 al registro)
return qc
def D_J(U_f,n):
qc=QuantumCircuit(n+1,n) #Se crea un circuito cuántico con n+1 quibits y n canales clásicos
qc.x(n) #Compuerta X al bit del registro
for i in range(n+1):
qc.h(i) #Compuerta H a todos los bits
qc.barrier() #Barrera (empieza oráculo)
qc = U_f(qc,n) #Agregamos el oráculo
qc.barrier() #Barrera (termina oráculo)
for i in range(n):
qc.h(i) #Compuerta H a los n bits del registro
qc.measure(i,i) #Medición los n bits del registro
return qc
qc=D_J(constant,3) #definición circuito con oráculo constante y 3 bits en registro
display(qc.draw()) #ver circuito
counts = sim.run(qc).result().get_counts() #contando las medidas de simulador cuántico
plot_histogram(counts) #histrograma de resultados
qc=D_J(balanced,3)
display(qc.draw())
counts = sim.run(qc).result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.opflow import I, X, Y, Z
print(I, X, Y, Z)
print(1.5 * I)
print(2.5 * X)
print(X + 2.0 * Y)
print(X^Y^Z)
print(X @ Y @ Z)
print((X + Y) @ (Y + Z))
print((X + Y) ^ (Y + Z))
(I, X)
2.0 * X^Y^Z
print(1.1 * ((1.2 * X)^(Y + (1.3 * Z))))
from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H,
DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn)
print(Zero, One)
print(Plus, Minus)
print(Zero.eval('0'))
print(Zero.eval('1'))
print(One.eval('1'))
print(Plus.eval('0'))
print(Minus.eval('1'))
One.adjoint()
~One
(2.0 + 3.0j) * Zero
print(Zero + One)
import math
v_zero_one = (Zero + One) / math.sqrt(2)
print(v_zero_one)
print(Plus + Minus)
print(~One @ One)
(~One @ One).eval()
(~v_zero_one @ v_zero_one).eval()
(~Minus @ One).eval()
print((~One).compose(One))
(~One).eval(One)
print(Zero^Plus)
print((Zero^Plus).to_circuit_op())
print(600 * ((One^5) + (Zero^5)))
print((One^Zero)^3)
print(((Plus^Minus)^2).to_matrix_op())
print(((Plus^One)^2).to_circuit_op())
print(((Plus^One)^2).to_matrix_op().sample())
print(StateFn({'0':1}))
print(StateFn({'0':1}) == Zero)
print(StateFn([0,1,1,0]))
from qiskit.circuit.library import RealAmplitudes
print(StateFn(RealAmplitudes(2)))
from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp
X
print(X.eval('0'))
X.eval('0').eval('1')
print(CX)
print(CX.to_matrix().real) # The imaginary part vanishes.
CX.eval('01') # 01 is the one in decimal. We get the first column.
CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3)
print(X @ One)
(X @ One).eval()
X.eval(One)
print(((~One^2) @ (CX.eval('01'))).eval())
print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2)
print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5))
print(((H^I^I)@(X^I^I)@Zero))
print(~One @ Minus)
from qiskit.opflow import ListOp
print((~ListOp([One, Zero]) @ ListOp([One, Zero])))
print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce())
print(StateFn(Z).adjoint())
StateFn(Z).adjoint()
print(StateFn(Z).adjoint().eval(Zero))
print(StateFn(Z).adjoint().eval(One))
print(StateFn(Z).adjoint().eval(Plus))
import numpy as np
from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki
from qiskit.circuit import Parameter
from qiskit import Aer
two_qubit_H2 = (-1.0523732 * I^I) + \
(0.39793742 * I^Z) + \
(-0.3979374 * Z^I) + \
(-0.0112801 * Z^Z) + \
(0.18093119 * X^X)
print(two_qubit_H2)
evo_time = Parameter('θ')
evolution_op = (evo_time*two_qubit_H2).exp_i()
print(evolution_op) # Note, EvolvedOps print as exponentiations
print(repr(evolution_op))
h2_measurement = StateFn(two_qubit_H2).adjoint()
print(h2_measurement)
bell = CX @ (I ^ H) @ Zero
print(bell)
evo_and_meas = h2_measurement @ evolution_op @ bell
print(evo_and_meas)
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
# We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization.
print(trotterized_op)
bound = trotterized_op.bind_parameters({evo_time: .5})
bound[1].to_circuit().draw()
# Note that XX was the only non-diagonal measurement in our H2 Observable
print(PauliExpectation(group_paulis=False).convert(h2_measurement))
print(PauliExpectation().convert(h2_measurement))
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = list(range(8))
h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points})
h2_trotter_expectations.eval()
sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator'))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies)))
print('Before:\n')
print(h2_trotter_expectations.reduce()[0][0])
print('\nAfter:\n')
print(sampled_trotter_exp_op[0][0])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.opflow import I, X, Y, Z
print(I, X, Y, Z)
print(1.5 * I)
print(2.5 * X)
print(X + 2.0 * Y)
print(X^Y^Z)
print(X @ Y @ Z)
print((X + Y) @ (Y + Z))
print((X + Y) ^ (Y + Z))
(I, X)
2.0 * X^Y^Z
print(1.1 * ((1.2 * X)^(Y + (1.3 * Z))))
from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H,
DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn)
print(Zero, One)
print(Plus, Minus)
print(Zero.eval('0'))
print(Zero.eval('1'))
print(One.eval('1'))
print(Plus.eval('0'))
print(Minus.eval('1'))
One.adjoint()
~One
(2.0 + 3.0j) * Zero
print(Zero + One)
import math
v_zero_one = (Zero + One) / math.sqrt(2)
print(v_zero_one)
print(Plus + Minus)
print(~One @ One)
(~One @ One).eval()
(~v_zero_one @ v_zero_one).eval()
(~Minus @ One).eval()
print((~One).compose(One))
(~One).eval(One)
print(Zero^Plus)
print((Zero^Plus).to_circuit_op())
print(600 * ((One^5) + (Zero^5)))
print((One^Zero)^3)
print(((Plus^Minus)^2).to_matrix_op())
print(((Plus^One)^2).to_circuit_op())
print(((Plus^One)^2).to_matrix_op().sample())
print(StateFn({'0':1}))
print(StateFn({'0':1}) == Zero)
print(StateFn([0,1,1,0]))
from qiskit.circuit.library import RealAmplitudes
print(StateFn(RealAmplitudes(2)))
from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp
X
print(X.eval('0'))
X.eval('0').eval('1')
print(CX)
print(CX.to_matrix().real) # The imaginary part vanishes.
CX.eval('01') # 01 is the one in decimal. We get the first column.
CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3)
print(X @ One)
(X @ One).eval()
X.eval(One)
print(((~One^2) @ (CX.eval('01'))).eval())
print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2)
print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5))
print(((H^I^I)@(X^I^I)@Zero))
print(~One @ Minus)
from qiskit.opflow import ListOp
print((~ListOp([One, Zero]) @ ListOp([One, Zero])))
print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce())
print(StateFn(Z).adjoint())
StateFn(Z).adjoint()
print(StateFn(Z).adjoint().eval(Zero))
print(StateFn(Z).adjoint().eval(One))
print(StateFn(Z).adjoint().eval(Plus))
import numpy as np
from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki
from qiskit.circuit import Parameter
from qiskit import Aer
two_qubit_H2 = (-1.0523732 * I^I) + \
(0.39793742 * I^Z) + \
(-0.3979374 * Z^I) + \
(-0.0112801 * Z^Z) + \
(0.18093119 * X^X)
print(two_qubit_H2)
evo_time = Parameter('θ')
evolution_op = (evo_time*two_qubit_H2).exp_i()
print(evolution_op) # Note, EvolvedOps print as exponentiations
print(repr(evolution_op))
h2_measurement = StateFn(two_qubit_H2).adjoint()
print(h2_measurement)
bell = CX @ (I ^ H) @ Zero
print(bell)
evo_and_meas = h2_measurement @ evolution_op @ bell
print(evo_and_meas)
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
# We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization.
print(trotterized_op)
bound = trotterized_op.bind_parameters({evo_time: .5})
bound[1].to_circuit().draw()
# Note that XX was the only non-diagonal measurement in our H2 Observable
print(PauliExpectation(group_paulis=False).convert(h2_measurement))
print(PauliExpectation().convert(h2_measurement))
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = list(range(8))
h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points})
h2_trotter_expectations.eval()
sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator'))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies)))
print('Before:\n')
print(h2_trotter_expectations.reduce()[0][0])
print('\nAfter:\n')
print(sampled_trotter_exp_op[0][0])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import I, X, Y, Z
import matplotlib.pyplot as plt
from volta.observables import sample_hamiltonian
from volta.hamiltonians import BCS_hamiltonian
EPSILONS = [3, 3]
V = -2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix())
print(f"Eigenvalues: {eigenvalues}")
def create_circuit(n: int) -> list:
return [QuantumCircuit(n) for _ in range(2)]
n = hamiltonian.num_qubits
init_states = create_circuit(n)
def copy_unitary(list_states: list) -> list:
out_states = []
for state in list_states:
out_states.append(state.copy())
return out_states
import textwrap
def apply_initialization(list_states: list) -> None:
for ind, state in enumerate(list_states):
b = bin(ind)[2:]
if len(b) != n:
b = '0'*(n - len(b)) + b
spl = textwrap.wrap(b, 1)
for qubit, val in enumerate(spl):
if val == '1':
state.x(qubit)
apply_initialization(init_states)
initialization = copy_unitary(init_states)
from qiskit.circuit.library import TwoLocal
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None:
for states in list_states:
states.append(ansatz, range(n))
apply_ansatz(ansatz, init_states)
init_states[1].draw('mpl')
w = np.arange(n, 0, -1)
w
def _apply_varform_params(ansatz, params: list):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = ansatz
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(params), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
def cost_function(params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
for i, state in enumerate(init_states):
qc = _apply_varform_params(state, params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += w[i] * hamiltonian_eval
return cost
from qiskit.aqua.components.optimizers import COBYLA
optimizer = COBYLA(maxiter=1000)
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost_function,
initial_point=params)
mean_energy
# Optimized first ansatz
ansatz_1 = _apply_varform_params(ansatz, optimal_params)
ansatz_1.name = 'U(θ)'
apply_ansatz(ansatz_1, init_states)
init_states[2].draw()
from qiskit.aqua import QuantumInstance
def cost_function_ind(ind: int, params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
qc = _apply_varform_params(init_states[ind], params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += hamiltonian_eval
return - cost
from functools import partial
cost = partial(cost_function_ind, 2)
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost,
initial_point=params)
energy_gs
eigenvalues
# Optimized second ansatz
ansatz_2 = _apply_varform_params(ansatz, optimal_params)
ansatz_2.name = 'V(ϕ)'
|
https://github.com/Hayatto9217/Qiskit7
|
Hayatto9217
|
from qiskit import QuantumCircuit
circ= QuantumCircuit(2,2)
circ.h(0)
circ.cx(0,1)
circ.measure(0,0)
circ.measure(1,1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16),
pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h',[0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend =FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1,1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
circ.append(custom_gate, [0])
circ.measure(0,0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8),
pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
circ =transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2,2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# 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.
"""Class for holding evolution result."""
from __future__ import annotations
from qiskit import QuantumCircuit
from qiskit_algorithms.list_or_dict import ListOrDict
from qiskit.opflow import StateFn, OperatorBase
from qiskit.utils.deprecation import deprecate_func
from ..algorithm_result import AlgorithmResult
class EvolutionResult(AlgorithmResult):
"""Deprecated: Class for holding evolution result.
The EvolutionResult class has been superseded by the
:class:`qiskit_algorithms.time_evolvers.TimeEvolutionResult` class.
This class will be deprecated in a future release and subsequently
removed after that.
"""
@deprecate_func(
additional_msg=(
"Instead, use the class ``qiskit_algorithms.time_evolvers.TimeEvolutionResult``. "
"See https://qisk.it/algo_migration for a migration guide."
),
since="0.24.0",
)
def __init__(
self,
evolved_state: StateFn | QuantumCircuit | OperatorBase,
aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None,
):
"""
Args:
evolved_state: An evolved quantum state.
aux_ops_evaluated: Optional list of observables for which expected values on an evolved
state are calculated. These values are in fact tuples formatted as (mean, standard
deviation).
"""
self.evolved_state = evolved_state
self.aux_ops_evaluated = aux_ops_evaluated
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from pprint import pprint
import pickle
import time
import datetime
%matplotlib inline
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, X, Y, Z, I
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, 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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
backend = Aer.get_backend("qasm_simulator")
# Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line
def H_heis3():
# Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product)
XXs = (I^X^X) + (X^X^I)
YYs = (I^Y^Y) + (Y^Y^I)
ZZs = (I^Z^Z) + (Z^Z^I)
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
# Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def U_heis3(t):
# Compute XXX Hamiltonian for 3 spins in a line
H = H_heis3()
# Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian
return (t * H).exp_i()
# Define array of time points
ts = np.linspace(0, np.pi, 100)
target_state = DictStateFn({"000": 0,
"001": 0,
"010": 1,
"011": 0,
"100": 0,
"101": 0,
"110": 1,
"111": 0}, 1 / np.sqrt(2))
print(DensityMatrix(target_state.to_density_matrix()).is_valid())
# Compute probability of remaining in |110> state over the array of time points
# ~target_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.figure(dpi=200)
plt.plot(ts, probs_010_110)
plt.xlabel('time')
plt.ylabel(r'probability of state $|010\rangle + |110\rangle$')
plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$')
# plt.grid()
plt.show()
num_qubits = 3
# The final time of the state evolution
target_times = [i * np.pi / 20 for i in range(0, 20 + 1)]
pprint(target_times)
# 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] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = np.zeros((1 << num_qubits, 1 << num_qubits))
target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5
target_state = DensityMatrix(target_state)
target_state.draw("latex")
prob_list = []
for target_time in target_times:
print("target_time: ", target_time)
t1 = time.perf_counter()
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
cr = ClassicalRegister(num_qubits, name="c")
qc = QuantumCircuit(qr, cr)
# 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>)
qc.h(0)
qc.x(1)
general_subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
general_subspace_decoder(qc, targets=[0, 1, 2]) # decode
qc.x(1)
qc.h(0)
qc.measure(qr, cr[::-1])
# 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")
# optimize circuit
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_qc (depth:", t3_qc.depth(), ")")
t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_qc (depth:", t3_qc.depth(), ")")
job = execute(t3_qc, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
prob = job.result().get_counts().get("0" * num_qubits, 0) / shots
prob_list.append(prob)
t2 = time.perf_counter()
print(r'probability of state |010> + |110> = {:.4f}'.format(prob))
print("time:", t2 - t1)
print()
plt.figure(dpi=200)
plt.plot(ts, probs_010_110, label="theoretical prediction")
plt.scatter(target_times, prob_list, c="green", zorder=4)
plt.legend(("theoretical prediction", "proposed method"))
plt.xlabel('time')
plt.ylabel(r'probability of state $|010\rangle + |110\rangle$')
plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$')
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
fid_list = []
for target_time in target_times:
print("target_time: ", target_time)
t1 = time.perf_counter()
# 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>)
qc.h(0)
qc.x(1)
general_subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
general_subspace_decoder(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 = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# 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), ")")
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fid_list.append(fid)
t2 = time.perf_counter()
print('state tomography fidelity = {:.4f}'.format(fid))
print("time:", t2 - t1)
print()
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import logging
import sys
import time
from itertools import product
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit, execute
from qiskit.circuit.library import U3Gate
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel, depolarizing_error, ReadoutError, thermal_relaxation_error
def get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots):
"""Generate a dict datapoint with the given circuit and noise parameters"""
U3_gate_length = 7.111111111111112e-08
# extract parameters
(p0_0, p1_0), (p0_1, p1_1) = readout_params
depol_prob = depol_param
t1, t2, population = thermal_params
# Add Readout and Quantum Errors
noise_model = NoiseModel()
noise_model.add_all_qubit_readout_error(ReadoutError(readout_params))
noise_model.add_all_qubit_quantum_error(depolarizing_error(depol_param, 1), 'u3', warnings=False)
noise_model.add_all_qubit_quantum_error(
thermal_relaxation_error(t1, t2, U3_gate_length, excited_state_population=population), 'u3',
warnings=False)
job = execute(circ, QasmSimulator(), shots=shots, noise_model=noise_model)
result = job.result()
# add data point to DataFrame
data_point = {'theta': theta,
'phi': phi,
'lam': lam,
'p0_0': p0_0,
'p1_0': p1_0,
'p0_1': p0_1,
'p1_1': p1_1,
'depol_prob': depol_prob,
't1': t1,
't2': t2,
'population': population,
'E': result.get_counts(0).get('1', 0) / shots}
return data_point
def get_noise_model_params(K=10, readout=True, thermal=True, depol=True):
"""generate a list of tuples for all noise params (readout_params, depol_param, thermal_params) """
# Simple implementation. Use this...
noise_model_params = []
# Readout Error
for p0_0 in np.linspace(0.94, 1.0, K, endpoint=True):
for p1_1 in np.linspace(0.94, 1.0, K, endpoint=True):
p1_0 = 1 - p0_0
p0_1 = 1 - p1_1
readout_params = (p0_0, p1_0), (p0_1, p1_1)
# Thermal Error
# for t1 in np.itertools.chain(np.linspace(34000, 190000, K, endpoint=True), np.inf):
# for t2 in np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True):
# for population in np.linspace(0, 1, K, endpoint=True):
# thermal_params = (t1, t2, population)
t1 = np.inf
t2 = np.inf
population = 0
thermal_params = (t1, t2, population)
# Depolarizing Error
for depol_param in np.linspace(0, 0.001, K, endpoint=True):
noise_model_params.append((readout_params, depol_param, thermal_params))
return noise_model_params
# Inefficient implementation. Don't Use...
"""if readout:
p0_0_iter = np.linspace(0.94, 1.0, K, endpoint=True)
p1_1_iter = np.linspace(0.94, 1.0, K, endpoint=True)
else:
p0_0_iter = [1]
p1_1_iter = [1]
if depol:
depol_iter = np.linspace(0, 0.001, K, endpoint=True)
else:
depol_iter = [0]
if thermal:
t1_iter = np.linspace(34000, 190000, K, endpoint=True)
# thermal_iter = map(lambda t1: (t1, np.linspace(t1/5.6, t1/0.65, 10, endpoint=True)), t1_iter)
thermal_iter = chain.from_iterable(
map(lambda t1: product([t1], np.linspace(t1 / 5.6, t1 / 0.65, K, endpoint=True)), t1_iter))
else:
thermal_iter = [(np.inf, np.inf)]
iterator = product(p0_0_iter, p1_1_iter, depol_iter, thermal_iter)
noise_model_params = [(((p0_0, 1 - p0_0), (1 - p1_1, p1_1)), depol, (t1, t2)) for p0_0, p1_1, depol, (t1, t2) in
tqdm(iterator)]
return noise_model_params"""
def U3Dataset(angle_step=10, other_steps=10, shots=2048, readout=True, thermal=True, depol=True, save_dir=None):
a_logger = logging.getLogger(__name__)
# the dictionary to pass to pandas dataframe
data = {}
# a counter to use to add entries to "data"
i = 0
# a counter to use to log circuit number
j = 0
# Iterate over all U3 gates
for theta, phi, lam in product(np.linspace(0, 2 * np.pi, angle_step, endpoint=True), repeat=3):
j = j + 1
# Generate sample data
circ = QuantumCircuit(1, 1)
circ.append(U3Gate(theta, phi, lam), [0])
circ.measure(0, 0)
a_logger.info("Generating data points for circuit: {}/{}\n".format(j, angle_step ** 3) + str(circ))
start_time = time.time()
for readout_params, depol_param, thermal_params in get_noise_model_params(other_steps, readout, thermal, depol):
data_point = get_data_point(circ, theta, phi, lam, readout_params, depol_param, thermal_params, shots)
data[i] = {'theta': data_point['theta'],
'phi': data_point['phi'],
'lam': data_point['lam'],
'p0_0': data_point['p0_0'],
'p1_0': data_point['p1_0'],
'p0_1': data_point['p0_1'],
'p1_1': data_point['p1_1'],
'depol_prob': data_point['depol_prob'],
't1': data_point['t1'],
't2': data_point['t2'],
'population': data_point['population'],
'E': data_point['E']}
i = i + 1
a_logger.info("Last circuit took: {:.2f} seconds.".format(time.time() - start_time))
# set the 'orient' parameter to "index" to make the keys as rows
df = pd.DataFrame.from_dict(data, "index")
# Save to CSV
if save_dir is not None:
df.to_csv(save_dir)
return df
# start main script
if __name__ == '__main__':
# create formatter
formatter = logging.Formatter("%(asctime)s; %(message)s", "%y-%m-%d %H:%M:%S")
# initialize logger
a_logger = logging.getLogger(__name__)
a_logger.setLevel(logging.INFO)
# log to output file
log_file_path = "../logs/output_{}.log".format(time.strftime("%Y%m%d-%H%M%S"))
output_file_handler = logging.FileHandler(log_file_path, mode='w', encoding='utf-8')
output_file_handler.setFormatter(formatter)
a_logger.addHandler(output_file_handler)
# log to stdout
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
a_logger.addHandler(stdout_handler)
for n, m in [(5, 5)]:
save_dir = '../datasets/universal_error/AllErrors/U3_{}_{}_no_thermal.csv'.format(n, m)
a_logger.info("Starting dataset generation with resolution n = {}, m = {}.".format(n, m))
angle_step = n
other_steps = m
U3Dataset(angle_step=angle_step, other_steps=other_steps, readout=True, thermal=True, depol=True,
save_dir=save_dir)
a_logger.info("Finished dataset generation with resolution n = {}, m = {}.".format(n, m))
a_logger.info("Dataset saved to {}".format(save_dir))
a_logger.info("Exiting Gracefully")
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import pytest
import qiskit
from orquestra.quantum.circuits.symbolic.expressions import FunctionCall, Symbol
from orquestra.quantum.circuits.symbolic.translations import translate_expression
from orquestra.integrations.qiskit.conversions._qiskit_expressions import (
QISKIT_DIALECT,
expression_from_qiskit,
integer_pow,
)
THETA = qiskit.circuit.Parameter("theta")
PHI = qiskit.circuit.Parameter("phi")
EQUIVALENT_EXPRESSIONS = [
(
FunctionCall(
name="add",
args=(1, FunctionCall(name="mul", args=(2, Symbol(name="theta")))),
),
THETA * 2 + 1,
),
(
FunctionCall(
name="add",
args=(1, FunctionCall(name="pow", args=(Symbol(name="theta"), 2))),
),
THETA * THETA + 1,
),
(
FunctionCall(
name="sub",
args=(
2,
FunctionCall(
name="mul", args=(Symbol(name="phi"), Symbol(name="theta"))
),
),
),
2 - THETA * PHI,
),
]
INTERMEDIATE_EXPRESSIONS = [expr for expr, _ in EQUIVALENT_EXPRESSIONS]
class TestParsingQiskitExpressions:
@pytest.mark.parametrize("intermediate_expr, qiskit_expr", EQUIVALENT_EXPRESSIONS)
def test_parsed_intermediate_expression_matches_equivalent_expression(
self, intermediate_expr, qiskit_expr
):
parsed_expr = expression_from_qiskit(qiskit_expr)
assert parsed_expr == intermediate_expr
@pytest.mark.parametrize("expr", INTERMEDIATE_EXPRESSIONS)
def test_translate_parse_identity(self, expr):
# NOTE: the other way round (Qiskit -> intermediate -> Qiskit) can't be done
# directly, because Qiskit expressions don't implement equality checks.
qiskit_expr = translate_expression(expr, QISKIT_DIALECT)
parsed_expr = expression_from_qiskit(qiskit_expr)
assert parsed_expr == expr
class TestIntegerPower:
def test_only_integer_exponents_are_valid(self):
with pytest.raises(ValueError):
integer_pow(2, 2.5)
@pytest.mark.parametrize("base", [10, THETA])
def test_with_exponent_0_is_equal_to_one(self, base):
assert integer_pow(base, 0) == 1
@pytest.mark.parametrize(
"base, exponent, expected_result",
[(2.5, 3, 2.5**3), (THETA, 2, THETA * THETA)],
)
def test_with_positive_exponent_is_converted_to_repeated_multiplication(
self, base, exponent, expected_result
):
assert integer_pow(base, exponent) == expected_result
def test_negative_exponent_cannot_be_used_if_base_is_zero(self):
with pytest.raises(ValueError):
integer_pow(0, -10)
@pytest.mark.parametrize(
"base, exponent, expected_result",
[(2.0, -4, 0.5**4), (THETA, -3, (1 / THETA) * (1 / THETA) * (1 / THETA))],
)
def test_with_neg_exponent_is_converted_to_repeated_multiplication_of_reciprocals(
self, base, exponent, expected_result
):
assert integer_pow(base, exponent) == expected_result
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# -*- 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/AbeerVaishnav13/4-qubit-design
|
AbeerVaishnav13
|
import warnings
warnings.filterwarnings('ignore')
from qiskit_metal import designs, MetalGUI
design = designs.DesignPlanar()
design.overwrite_enabled = True
design.chips.main.size_x = '12mm'
design.chips.main.size_y = '10mm'
gui = MetalGUI(design)
from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL
design.delete_all_components()
# Some local variables to modularize the deesign
design_span_x = 5
design_span_y = 3
half_chip_width = design_span_x / 2
half_chip_height = design_span_y / 2
connection_pads_options = dict(
a = dict(loc_W=1, loc_H=-1),
b = dict(loc_W=1, loc_H=1),
c = dict(loc_W=-1, loc_H=-1)
)
transmons = []
transmons.append(TransmonPocketCL(design, 'Q1',
options=dict(pos_x=f'-{half_chip_width}mm',
pos_y=f'{-half_chip_height}mm',
connection_pads=dict(**connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q2',
options=dict(pos_x=f'0mm',
pos_y=f'{half_chip_height}mm',
orientation=-90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q3',
options=dict(pos_x=f'0mm',
pos_y=f'{-half_chip_height}mm',
orientation=90,
connection_pads=dict(d=dict(loc_W=-1, loc_H=1), **connection_pads_options))))
transmons.append(TransmonPocketCL(design, 'Q4',
options=dict(pos_x=f'{half_chip_width}mm',
pos_y=f'{half_chip_height}mm',
orientation=180,
connection_pads=dict(**connection_pads_options))))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.meandered import RouteMeander
from qiskit_metal import Dict
# Options for the meaders
fillet='99.99um'
options = Dict(
meander=Dict(
lead_start='0.1mm',
lead_end='0.1mm',
asymmetry='0 um')
)
# Helper function to connect thee meandered routes
def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str,
length: str,
asymmetry='0 um', start_strght='0 um', end_strght='0 um', flip=False):
"""Connect two pins with a CPW."""
myoptions = Dict(
pin_inputs=Dict(
start_pin=Dict(
component=component1,
pin=pin1),
end_pin=Dict(
component=component2,
pin=pin2)),
lead=Dict(
start_straight=start_strght,
end_straight=end_strght
),
total_length=length,
fillet = '99.9um')
myoptions.update(options)
myoptions.meander.asymmetry = asymmetry
myoptions.meander.lead_direction_inverted = 'true' if flip else 'false'
return RouteMeander(design, component_name, myoptions)
# Define asymmetry (itrative process)
asym_h = 100
asym_v = 100
cpw = []
# Connect CPW coulers between qubits (with some arbitrary length initially)
cpw.append(connect('cpw1', 'Q1', 'b', 'Q2', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw2', 'Q3', 'b', 'Q2', 'b', '8 mm', f'-{asym_v}um', '0.6mm', '0.4mm'))
cpw.append(connect('cpw3', 'Q4', 'b', 'Q3', 'a', '8 mm', f'+{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw4', 'Q3', 'd', 'Q1', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
cpw.append(connect('cpw5', 'Q2', 'd', 'Q4', 'a', '8 mm', f'-{asym_h}um', '0.1mm', '0.1mm'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength
def find_resonator_length(frequency, line_width, line_gap, N):
#frequency in GHz
#line_width/line_gap in um
#N -> 2 for lambda/2, 4 for lambda/4
[lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6,
line_gap*10**-6, 750*10**-6, 200*10**-9)
return str(lambdaG/N*10**3)+" mm"
find_resonator_length(6.5, 15, 1, 2)
from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled
readouts_lwc = []
cl_lwc = []
offset_x = 0
offset_y = 1
#Readouts
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R1',
options = dict(
pos_x = '-5mm',
pos_y = f'-{half_chip_height+offset_y}mm',
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R2',
options = dict(
pos_x = '-1mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R3',
options = dict(
pos_x = '1mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
readouts_lwc.append(LaunchpadWirebondCoupled(design, 'R4',
options = dict(
pos_x = '5mm',
pos_y = f'{half_chip_height+offset_y}mm',
orientation = 180,
lead_length = '30um')))
#Controls
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL1',
options = dict(
pos_x = '-5mm',
pos_y = '2mm',
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL2',
options = dict(
pos_x = '4mm',
pos_y = '4mm',
orientation = -90,
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL3',
options = dict(
pos_x = '-4mm',
pos_y = '-4mm',
orientation = 90,
lead_length = '30um')))
cl_lwc.append(LaunchpadWirebondCoupled(design, 'CL4',
options = dict(
pos_x = '5mm',
pos_y = '-2mm',
orientation = 180,
lead_length = '30um')))
gui.rebuild()
gui.autoscale()
readout_lines = []
asym_14 = 700
asym_23 = 700
options = Dict(
lead=Dict(
start_straight='430um',
end_straight='0um'),
fillet='99.99um')
readout_lines.append(connect('ol1', 'Q1', 'c', 'R1', 'tie', '8 mm', f'{asym_14}um'))
readout_lines.append(connect('ol2', 'Q2', 'c', 'R2', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol3', 'Q3', 'c', 'R3', 'tie', '8 mm', f'{asym_23}um'))
readout_lines.append(connect('ol4', 'Q4', 'c', 'R4', 'tie', '8 mm', f'{asym_14}um'))
gui.rebuild()
gui.autoscale()
from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors
from collections import OrderedDict
import numpy as np
control_lines = []
def connectRouteAnchor(name: str,
component1: str, pin1: str, component2: str, pin2: str,
anchor_points: OrderedDict) -> RouteAnchors:
options_line_cl = dict(
pin_inputs = dict(start_pin = dict(component = component1, pin = pin1),
end_pin = dict(component = component2, pin = pin2)),
anchors = anchor_points,
lead = dict(start_straight = '200um',
end_straight = '225um'),
fillet = fillet
)
return RouteAnchors(design, name, options_line_cl)
anchors1c = OrderedDict()
anchors1c[0] = np.array([-4, -1.42])
anchors1c[1] = np.array([-4, 2])
control_lines.append(connectRouteAnchor('line_cl1', 'Q1', 'Charge_Line', 'CL1', 'tie', anchors1c))
anchors2c = OrderedDict()
anchors2c[0] = np.array([0.08, 3.25])
anchors2c[1] = np.array([4, 3.25])
control_lines.append(connectRouteAnchor('line_cl2', 'Q2', 'Charge_Line', 'CL2', 'tie', anchors2c))
anchors3c = OrderedDict()
anchors3c[0] = np.array([-0.08, -3.25])
anchors3c[1] = np.array([-4, -3.25])
control_lines.append(connectRouteAnchor('line_cl3', 'Q3', 'Charge_Line', 'CL3', 'tie', anchors3c))
anchors4c = OrderedDict()
anchors4c[0] = np.array([4, 1.42])
anchors4c[1] = np.array([4, -2])
control_lines.append(connectRouteAnchor('line_cl4', 'Q4', 'Charge_Line', 'CL4', 'tie', anchors4c))
gui.rebuild()
gui.autoscale()
# Qubit Frequencies
# Q1 : 5
# Q2 : 5.1
# Q3 : 5.2
# Q4 : 5.3
# Readout Frequencies
# R1 : 7
# R2 : 7.1
# R3 : 7.2
# R4 : 7.3
# CPW Frequencies
# cpw1 : 7.5
# cpw2 : 7.6
# cpw3 : 7.7
# cpw4 : 7.8
# cpw5 : 7.9
gui.screenshot()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/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.
"""Test the VF2Layout pass"""
import io
import pickle
import unittest
from math import pi
import ddt
import numpy
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import ControlFlowOp
from qiskit.transpiler import CouplingMap, Target, TranspilerError
from qiskit.transpiler.passes.layout.vf2_layout import VF2Layout, VF2LayoutStopReason
from qiskit._accelerate.error_map import ErrorMap
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeTenerife,
FakeVigoV2,
FakeRueschlikon,
FakeManhattan,
FakeYorktown,
FakeGuadalupeV2,
)
from qiskit.circuit import Measure
from qiskit.circuit.library import GraphState, CXGate, XGate, HGate
from qiskit.transpiler import PassManager, AnalysisPass
from qiskit.transpiler.target import InstructionProperties
from qiskit.transpiler.preset_passmanagers.common import generate_embed_passmanager
class LayoutTestCase(QiskitTestCase):
"""VF2Layout assertions"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set, strict_direction=False):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND)
layout = property_set["layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
if strict_direction:
result = (physical_q0, physical_q1) in edges
else:
result = (physical_q0, physical_q1) in edges or (
physical_q1,
physical_q0,
) in edges
self.assertTrue(result)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits})
@ddt.ddt
class TestVF2LayoutSimple(LayoutTestCase):
"""Tests the VF2Layout pass"""
def test_1q_component_influence(self):
"""Assert that the 1q component of a connected interaction graph is scored correctly."""
target = Target()
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(error=0.0),
(1, 2): InstructionProperties(error=0.0),
(2, 3): InstructionProperties(error=0.0),
},
)
target.add_instruction(
HGate(),
{
(0,): InstructionProperties(error=0.0),
(1,): InstructionProperties(error=0.0),
(2,): InstructionProperties(error=0.0),
},
)
target.add_instruction(
Measure(),
{
(0,): InstructionProperties(error=0.1),
(1,): InstructionProperties(error=0.1),
(2,): InstructionProperties(error=0.9),
},
)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 0)
qc.measure(0, 0)
qc.measure(1, 1)
vf2_pass = VF2Layout(target=target, seed=self.seed)
vf2_pass(qc)
layout = vf2_pass.property_set["layout"]
self.assertEqual([1, 0], list(layout._p2v.keys()))
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=True)
@ddt.data(True, False)
def test_2q_circuit_simple_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2)
with circuit.for_loop((1,)):
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
@ddt.data(True, False)
def test_2q_circuit_nested_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2, 1)
with circuit.while_loop((circuit.clbits[0], True)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(1, 0)
with else_:
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
def test_3q_circuit_3q_coupling_non_induced(self):
"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_3q_circuit_3q_coupling_non_induced_control_flow(self):
r"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
circuit = QuantumCircuit(3, 1)
with circuit.for_loop((1,)):
circuit.cx(0, 1) # qr0-> qr1
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 2) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_call_limit(self):
"""Test that call limit is enforce."""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, call_limit=1)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_coupling_map_and_target(self):
"""Test that a Target is used instead of a CouplingMap if both are specified."""
cmap = CouplingMap([[0, 1], [1, 2]])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (1, 0): None})
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
circuit.cx(qr[1], qr[0]) # qr1-> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1, target=target)
pass_.run(dag)
self.assertLayout(dag, target.build_coupling_map(), pass_.property_set)
def test_neither_coupling_map_or_target(self):
"""Test that we raise if neither a target or coupling map is specified."""
vf2_pass = VF2Layout(seed=123, call_limit=1000, time_limit=20, max_trials=7)
circuit = QuantumCircuit(2)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
vf2_pass.run(dag)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
class TestVF2LayoutLattice(LayoutTestCase):
"""Fit in 25x25 hexagonal lattice coupling map"""
cmap25 = CouplingMap.from_hexagonal_lattice(25, 25, bidirectional=False)
def graph_state_from_pygraph(self, graph):
"""Creates a GraphState circuit from a PyGraph"""
adjacency_matrix = rustworkx.adjacency_matrix(graph)
return GraphState(adjacency_matrix).decompose()
def test_hexagonal_lattice_graph_20_in_25(self):
"""A 20x20 interaction map in 25x25 coupling map"""
graph_20_20 = rustworkx.generators.hexagonal_lattice_graph(20, 20)
circuit = self.graph_state_from_pygraph(graph_20_20)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
def test_hexagonal_lattice_graph_9_in_25(self):
"""A 9x9 interaction map in 25x25 coupling map"""
graph_9_9 = rustworkx.generators.hexagonal_lattice_graph(9, 9)
circuit = self.graph_state_from_pygraph(graph_9_9)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
class TestVF2LayoutBackend(LayoutTestCase):
"""Tests VF2Layout against backends"""
def test_5q_circuit_Rueschlikon_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] ↖ ↗ q0[2]
q0[0]
q0[3] ↙ ↘ q0[4]
"""
cmap16 = FakeRueschlikon().configuration().coupling_map
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed, max_trials=1)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_9q_circuit_Rueschlikon_sd(self):
"""9 qubits in Rueschlikon, considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_4q_circuit_Tenerife_loose_nodes(self):
"""4 qubits in Tenerife, with loose nodes
1
↙ ↑
0 ← 2 ← 3
↑ ↙
4
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_Tenerife_sd(self):
"""3 qubits in Tenerife, considering the direction
1 1
↙ ↑ ↙ ↑
0 ← 2 ← 3 0 ← qr2 ← qr1
↑ ↙ ↑ ↙
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set, strict_direction=True)
def test_9q_circuit_Rueschlikon(self):
"""9 qubits in Rueschlikon, without considering the direction
1 → 2 → 3 → 4 ← 5 ← 6 → 7 ← 8
↓ ↑ ↓ ↓ ↑ ↓ ↓ ↑
0 ← 15 → 14 ← 13 ← 12 → 11 → 10 ← 9
1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1
| | | | | | | |
q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2
"""
cmap16 = CouplingMap(FakeRueschlikon().configuration().coupling_map)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_3q_circuit_Tenerife(self):
"""3 qubits in Tenerife, without considering the direction
1 1
↙ ↑ / |
0 ← 2 ← 3 0 - qr1 - qr2
↑ ↙ | /
4 qr0
"""
cmap5 = CouplingMap(FakeTenerife().configuration().coupling_map)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_vigo_with_custom_scores(self):
"""Test custom ErrorMap from analysis pass are used for scoring."""
backend = FakeVigoV2()
target = backend.target
class FakeScore(AnalysisPass):
"""Fake analysis pass with custom scoring."""
def run(self, dag):
error_map = ErrorMap(9)
error_map.add_error((0, 0), 0.1)
error_map.add_error((0, 1), 0.5)
error_map.add_error((1, 1), 0.2)
error_map.add_error((1, 2), 0.8)
error_map.add_error((1, 3), 0.75)
error_map.add_error((2, 2), 0.123)
error_map.add_error((3, 3), 0.333)
error_map.add_error((3, 4), 0.12345423)
error_map.add_error((4, 4), 0.2222)
self.property_set["vf2_avg_error_map"] = error_map
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
vf2_pass = VF2Layout(target=target, seed=1234568942)
property_set = {}
vf2_pass(circuit, property_set)
pm = PassManager([FakeScore(), VF2Layout(target=target, seed=1234568942)])
pm.run(circuit)
# Assert layout is different from backend properties
self.assertNotEqual(property_set["layout"], pm.property_set["layout"])
self.assertLayout(circuit_to_dag(circuit), backend.coupling_map, pm.property_set)
def test_error_map_pickle(self):
"""Test that the `ErrorMap` Rust structure correctly pickles and depickles."""
errors = {(0, 1): 0.2, (1, 0): 0.2, (0, 0): 0.05, (1, 1): 0.02}
error_map = ErrorMap.from_dict(errors)
with io.BytesIO() as fptr:
pickle.dump(error_map, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(len(loaded), len(errors))
self.assertEqual({k: loaded[k] for k in errors}, errors)
def test_perfect_fit_Manhattan(self):
"""A circuit that fits perfectly in Manhattan (65 qubits)
See https://github.com/Qiskit/qiskit-terra/issues/5694"""
manhattan_cm = FakeManhattan().configuration().coupling_map
cmap65 = CouplingMap(manhattan_cm)
rows = [x[0] for x in manhattan_cm]
cols = [x[1] for x in manhattan_cm]
adj_matrix = numpy.zeros((65, 65))
adj_matrix[rows, cols] = 1
circuit = GraphState(adj_matrix).decompose()
circuit.measure_all()
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap65, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap65, pass_.property_set)
class TestVF2LayoutOther(LayoutTestCase):
"""Other VF2Layout tests"""
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 45
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
pass_2 = VF2Layout(CouplingMap(cmap5), seed=seed_2, max_trials=1)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertEqual(
pass_2.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
self.assertNotEqual(layout_1, layout_2)
def test_3_q_gate(self):
"""The pass does not handle gates with more than 2 qubits"""
seed_1 = 42
cmap5 = FakeTenerife().configuration().coupling_map
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[1], qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.MORE_THAN_2Q
)
class TestMultipleTrials(QiskitTestCase):
"""Test the passes behavior with >1 trial."""
def test_no_properties(self):
"""Test it finds the lowest degree perfect layout with no properties."""
vf2_pass = VF2Layout(
CouplingMap(
[
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(4, 0),
(0, 4),
(5, 1),
(1, 5),
]
)
)
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {4, 5})
def test_with_properties(self):
"""Test it finds the least noise perfect layout with no properties."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties)
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {1, 3})
def test_max_trials_exceeded(self):
"""Test it exits when max_trials is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, max_trials=1)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 1 is >= configured max trials 1",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_time_limit_exceeded(self):
"""Test the pass stops after time_limit is reached."""
backend = FakeYorktown()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, time_limit=0.0)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
if output.startswith(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:VF2Layout has taken"
) and output.endswith("which exceeds configured max time: 0.0"):
break
else:
self.fail("No failure debug log message found")
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_reasonable_limits_for_simple_layouts(self):
"""Test that the default trials is set to a reasonable number."""
backend = FakeManhattan()
qc = QuantumCircuit(5)
qc.cx(2, 3)
qc.cx(0, 1)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(cmap, properties=properties, seed=42)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 159 is >= configured max trials 159",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {49, 40, 33, 0, 34})
def test_no_limits_with_negative(self):
"""Test that we're not enforcing a trial limit if set to negative."""
backend = FakeYorktown()
qc = QuantumCircuit(3)
qc.h(0)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(
cmap,
properties=properties,
seed=42,
max_trials=0,
)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
self.assertNotIn("is >= configured max trials", output)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {3, 1, 0})
def test_qregs_valid_layout_output(self):
"""Test that vf2 layout doesn't add extra qubits.
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8667
"""
backend = FakeGuadalupeV2()
qr = QuantumRegister(16, name="qr")
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.rz(pi / 2, qr[0])
qc.sx(qr[0])
qc.sx(qr[1])
qc.rz(-pi / 4, qr[1])
qc.sx(qr[1])
qc.rz(pi / 2, qr[1])
qc.rz(2.8272143, qr[0])
qc.rz(0.43324854, qr[1])
qc.sx(qr[1])
qc.rz(-0.95531662, qr[7])
qc.sx(qr[7])
qc.rz(3 * pi / 4, qr[7])
qc.barrier([qr[1], qr[10], qr[4], qr[0], qr[7]])
vf2_pass = VF2Layout(
seed=12345,
target=backend.target,
)
vf2_pass(qc)
self.assertEqual(len(vf2_pass.property_set["layout"].get_physical_bits()), 16)
self.assertEqual(len(vf2_pass.property_set["layout"].get_virtual_bits()), 16)
pm = PassManager(
[
VF2Layout(
seed=12345,
target=backend.target,
)
]
)
pm += generate_embed_passmanager(backend.coupling_map)
res = pm.run(qc)
self.assertEqual(res.num_qubits, 16)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# pylint: disable=invalid-name
"""Tests for Pauli operator class."""
import re
import unittest
import itertools as it
from functools import lru_cache
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import (
IGate,
XGate,
YGate,
ZGate,
HGate,
SGate,
SdgGate,
CXGate,
CZGate,
CYGate,
SwapGate,
)
from qiskit.circuit.library.generalized_gates import PauliGate
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.operators import Pauli, Operator
LABEL_REGEX = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)")
PHASE_MAP = {"": 0, "-i": 1, "-": 2, "i": 3}
def _split_pauli_label(label):
match_ = LABEL_REGEX.fullmatch(label)
return match_["pauli"], match_["coeff"]
def _phase_from_label(label):
coeff = LABEL_REGEX.fullmatch(label)["coeff"] or ""
return PHASE_MAP[coeff.replace("+", "").replace("1", "").replace("j", "i")]
@lru_cache(maxsize=8)
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in it.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in it.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
pauli, coeff = _split_pauli_label(label)
coeff = (-1j) ** _phase_from_label(coeff)
return coeff * Operator.from_label(pauli)
@ddt
class TestPauliConversions(QiskitTestCase):
"""Test representation conversions of Pauli"""
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_labels(self, label):
"""Test round trip label conversion"""
pauli = Pauli(label)
self.assertEqual(Pauli(str(pauli)), pauli)
@data("S", "XX-")
def test_invalid_labels(self, label):
"""Test raise if invalid labels are supplied"""
with self.assertRaises(QiskitError):
Pauli(label)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_operator(self, label):
"""Test Pauli operator conversion"""
value = Operator(Pauli(label))
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_matrix_sparse(self, label):
"""Test Pauli operator conversion"""
spmat = Pauli(label).to_matrix(sparse=True)
value = Operator(spmat.todense())
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_instruction(self, label):
"""Test Pauli to instruction"""
pauli = Pauli(label)
value = Operator(pauli.to_instruction())
target = Operator(pauli)
self.assertEqual(value, target)
@data((IGate(), "I"), (XGate(), "X"), (YGate(), "Y"), (ZGate(), "Z"))
@unpack
def test_init_single_pauli_gate(self, gate, label):
"""Test initialization from Pauli basis gates"""
self.assertEqual(str(Pauli(gate)), label)
@data("IXYZ", "XXY", "ZYX", "ZI", "Y")
def test_init_pauli_gate(self, label):
"""Test initialization from Pauli basis gates"""
pauli = Pauli(PauliGate(label))
self.assertEqual(str(pauli), label)
@ddt
class TestPauliProperties(QiskitTestCase):
"""Test Pauli properties"""
@data("I", "XY", "XYZ", "IXYZ", "IXYZX")
def test_len(self, label):
"""Test __len__ method"""
self.assertEqual(len(Pauli(label)), len(label))
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equal(self, label1, label2):
"""Test __eq__ method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = (
np.all(pauli1.z == pauli2.z)
and np.all(pauli1.x == pauli2.x)
and pauli1.phase == pauli2.phase
)
self.assertEqual(pauli1 == pauli2, target)
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equiv(self, label1, label2):
"""Test equiv method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x)
self.assertEqual(pauli1.equiv(pauli2), target)
@data(*pauli_group_labels(1))
def test_phase(self, label):
"""Test phase attribute"""
pauli = Pauli(label)
_, coeff = _split_pauli_label(str(pauli))
target = _phase_from_label(coeff)
self.assertEqual(pauli.phase, target)
@data(*((p, q) for p in ["I", "X", "Y", "Z"] for q in range(4)))
@unpack
def test_phase_setter(self, pauli, phase):
"""Test phase setter"""
pauli = Pauli(pauli)
pauli.phase = phase
_, coeff = _split_pauli_label(str(pauli))
value = _phase_from_label(coeff)
self.assertEqual(value, phase)
def test_x_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.x = True
self.assertEqual(pauli, Pauli("XX"))
def test_z_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.z = True
self.assertEqual(pauli, Pauli("ZZ"))
@data(
*(
("IXYZ", i)
for i in [0, 1, 2, 3, slice(None, None, None), slice(None, 2, None), [0, 3], [2, 1, 3]]
)
)
@unpack
def test_getitem(self, label, qubits):
"""Test __getitem__"""
pauli = Pauli(label)
value = str(pauli[qubits])
val_array = np.array(list(reversed(label)))[qubits]
target = "".join(reversed(val_array.tolist()))
self.assertEqual(value, target, msg=f"indices = {qubits}")
@data(
(0, "iY", "iIIY"),
([1, 0], "XZ", "IZX"),
(slice(None, None, None), "XYZ", "XYZ"),
(slice(None, None, -1), "XYZ", "ZYX"),
)
@unpack
def test_setitem(self, qubits, value, target):
"""Test __setitem__"""
pauli = Pauli("III")
pauli[qubits] = value
self.assertEqual(str(pauli), target)
def test_insert(self):
"""Test insert method"""
pauli = Pauli("III")
pauli = pauli.insert([2, 0, 4], "XYZ")
self.assertEqual(str(pauli), "IXIZIY")
def test_delete(self):
"""Test delete method"""
pauli = Pauli("IXYZ")
pauli = pauli.delete([0, 2])
self.assertEqual(str(pauli), "IY")
@ddt
class TestPauli(QiskitTestCase):
"""Tests for Pauli operator class."""
@data(*pauli_group_labels(2))
def test_conjugate(self, label):
"""Test conjugate method."""
value = Pauli(label).conjugate()
target = operator_from_label(label).conjugate()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_transpose(self, label):
"""Test transpose method."""
value = Pauli(label).transpose()
target = operator_from_label(label).transpose()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_adjoint(self, label):
"""Test adjoint method."""
value = Pauli(label).adjoint()
target = operator_from_label(label).adjoint()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_inverse(self, label):
"""Test inverse method."""
pauli = Pauli(label)
value = pauli.inverse()
target = pauli.adjoint()
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_dot(self, label1, label2):
"""Test dot method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.dot(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2)
self.assertEqual(value, target)
target = op1 @ op2
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_dot_qargs(self, label2):
"""Test dot method with qargs."""
label1 = "-iXYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.dot(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""Test compose method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.compose(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2)
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_compose_qargs(self, label2):
"""Test compose method with qargs."""
label1 = "-XYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.compose(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_tensor(self, label1, label2):
"""Test tensor method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.tensor(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.tensor(op2)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_expand(self, label1, label2):
"""Test expand method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.expand(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.expand(op2)
self.assertEqual(value, target)
@data("II", "XI", "YX", "ZZ", "YZ")
def test_power(self, label):
"""Test power method."""
iden = Pauli("II")
op = Pauli(label)
self.assertTrue(op**2, iden)
@data(1, 1.0, -1, -1.0, 1j, -1j)
def test_multiply(self, val):
"""Test multiply method."""
op = val * Pauli(([True, True], [False, False], 0))
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
op = Pauli(([True, True], [False, False], 0)) * val
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Pauli("XYZ")
self.assertRaises(QiskitError, op._multiply, 2)
@data(0, 1, 2, 3)
def test_negate(self, phase):
"""Test negate method"""
op = Pauli(([False], [True], phase))
neg = -op
self.assertTrue(op.equiv(neg))
self.assertEqual(neg.phase, (op.phase + 2) % 4)
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_commutes(self, p1, p2):
"""Test commutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.commutes(P2), P1.dot(P2) == P2.dot(P1))
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_anticommutes(self, p1, p2):
"""Test anticommutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.anticommutes(P2), P1.dot(P2) == -P2.dot(P1))
@data(
*it.product(
(IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate()),
pauli_group_labels(1, False),
)
)
@unpack
def test_evolve_clifford1(self, gate, label):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(*it.product((CXGate(), CYGate(), CZGate(), SwapGate()), pauli_group_labels(2, False)))
@unpack
def test_evolve_clifford2(self, gate, label):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(
*it.product(
(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
),
[int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64],
)
)
@unpack
def test_phase_dtype_evolve_clifford(self, gate, dtype):
"""Test phase dtype for evolve method for Clifford gates."""
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
def test_evolve_clifford_qargs(self):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli = random_pauli(5, seed=10)
qargs = [3, 0, 1]
value = Operator(pauli.evolve(cliff, qargs=qargs))
value_h = Operator(pauli.evolve(cliff, qargs=qargs, frame="h"))
value_s = Operator(pauli.evolve(cliff, qargs=qargs, frame="s"))
value_inv = Operator(pauli.evolve(cliff.adjoint(), qargs=qargs))
target = Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
def test_barrier_delay_sim(self):
"""Test barrier and delay instructions can be simulated"""
target_circ = QuantumCircuit(2)
target_circ.x(0)
target_circ.y(1)
target = Pauli(target_circ)
circ = QuantumCircuit(2)
circ.x(0)
circ.delay(100, 0)
circ.barrier([0, 1])
circ.y(1)
value = Pauli(circ)
self.assertEqual(value, target)
@data(("", 0), ("-", 2), ("i", 3), ("-1j", 1))
@unpack
def test_zero_qubit_pauli_construction(self, label, phase):
"""Test that Paulis of zero qubits can be constructed."""
expected = Pauli(label + "X")[0:0] # Empty slice from a 1q Pauli, which becomes phaseless
expected.phase = phase
test = Pauli(label)
self.assertEqual(expected, test)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
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=IQXSimple())
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestLexer(QiskitTestCase):
# Most of the lexer is fully exercised in the parser tests. These tests here are really mopping
# up some error messages and whatnot that might otherwise be missed.
def test_pathological_formatting(self):
# This is deliberately _terribly_ formatted, included multiple blanks lines in quick
# succession and comments in places you really wouldn't expect to see comments.
program = """
OPENQASM
// do we really need a comment here?
2.0//and another comment very squished up
;
include // this line introduces a file import
"qelib1.inc" // this is the file imported
; // this is a semicolon
gate // we're making a gate
bell( // void, with loose parenthesis in comment )
) a,//
b{h a;cx a //,,,,
,b;}
qreg // a quantum register
q
[ // a square bracket
2];bell q[0],//
q[1];creg c[2];measure q->c;"""
parsed = qiskit.qasm2.loads(program)
expected_unrolled = qiskit.QuantumCircuit(
qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c")
)
expected_unrolled.h(0)
expected_unrolled.cx(0, 1)
expected_unrolled.measure([0, 1], [0, 1])
self.assertEqual(parsed.decompose(), expected_unrolled)
@ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2")
def test_float_lexes(self, number):
program = f"qreg q[1]; U({number}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0])
def test_no_decimal_float_rejected_in_strict_mode(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError,
r"\[strict\] all floats must include a decimal point",
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True)
@ddt.data("", "qre", "cre", ".")
def test_non_ascii_bytes_error(self, prefix):
token = f"{prefix}\xff"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"):
qiskit.qasm2.loads(token)
def test_integers_cannot_start_with_zero(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes"
):
qiskit.qasm2.loads("0123")
@ddt.data("", "+", "-")
def test_float_exponents_must_have_a_digit(self, sign):
token = f"12.34e{sign}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent"
):
qiskit.qasm2.loads(token)
def test_non_builtins_cannot_be_capitalised(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital"
):
qiskit.qasm2.loads("Qubit")
def test_unterminated_filename_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal"
):
qiskit.qasm2.loads('include "qelib1.inc')
def test_filename_with_linebreak_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal"
):
qiskit.qasm2.loads('include "qe\nlib1.inc";')
def test_strict_single_quoted_path_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes"
):
qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True)
def test_version_must_have_word_boundary_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2.0a;")
def test_no_boundary_float_in_version_position(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM .5a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 0.2e1a;")
def test_integers_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];")
def test_floats_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];")
def test_single_equals_is_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid"
):
qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];")
def test_bare_dot_is_not_valid_float(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part"
):
qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];")
def test_invalid_token(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match"
):
qiskit.qasm2.loads("!")
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
from svm_datasets import *
from qiskit_acqua.svm.data_preprocess import *
from qiskit_acqua.input import get_input_instance
from qiskit_acqua import run_algorithm
import logging
logger = logging.getLogger()
# logger.setLevel(logging.DEBUG) # uncomment it to see detailed logging
################# import Qconfig and set APIToken and API url and prepare backends ############
try:
import sys
sys.path.append("../../") # go to parent dir
import Qconfig
except Exception as e:
print(e)
from qiskit import register, available_backends
#set api
APItoken=getattr(Qconfig, 'APItoken', None)
url = Qconfig.config.get('url', None)
hub = Qconfig.config.get('hub', None)
group = Qconfig.config.get('group', None)
project = Qconfig.config.get('project', None)
try:
register(APItoken, url, hub, group, project)
except Exception as e:
print(e)
print("Backends: {}".format(available_backends()))
feature_dim=2 # we support feature_dim 2 or 3
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=20, test_size=10, n=feature_dim, gap=0.3, PLOT_DATA=True)
total_array, label_to_labelclass = get_points(test_input, class_labels)
params = {
'problem': {'name': 'svm_classification'},
'backend': {'name': 'local_qasm_simulator', 'shots':1000},
'algorithm': {
'name': 'SVM_QKernel',
'print_info' : True
}
}
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = total_array
result = run_algorithm(params,algo_input)
print("testing success ratio: ", result['test_success_ratio'])
print("predicted labels:", result['predicted_labels'])
print("kernel matrix of the training data:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
sample_Total, training_input, test_input, class_labels = Breast_cancer(training_size=20, test_size=10, n=feature_dim, PLOT_DATA=True)
algo_input = get_input_instance('SVMInput')
algo_input.training_dataset = training_input
algo_input.test_dataset = test_input
algo_input.datapoints = total_array
result = run_algorithm(params, algo_input)
print("testing success ratio: ", result['test_success_ratio'])
print("predicted labels:", result['predicted_labels'])
print("kernel matrix of the training data:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
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=IQXSimple())
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# 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 pygame
from qiskit import BasicAer, execute, ClassicalRegister
from utils.colors import *
from utils.fonts import ARIAL_30
from utils.states import comp_basis_states
from copy import deepcopy
#from utils.paddle import *
class StatevectorGrid(pygame.sprite.Sprite):
"""Displays a statevector grid"""
def __init__(self, circuit, qubit_num, num_shots):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.basis_states = comp_basis_states(circuit.width())
self.set_circuit(circuit, qubit_num, num_shots)
# def update(self):
# # Nothing yet
# a = 1ot
def set_circuit(self, circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
# This square represent the probability of state after measurement
self.image = pygame.Surface([(circuit.width()+1) * 50, 500])
self.image.convert()
self.image.fill(BLACK)
self.rect = self.image.get_rect()
block_size = int(round(500 / 2 ** qubit_num))
x_offset = 50
y_offset = 15
self.paddle = pygame.Surface([10, block_size])
self.paddle.convert()
for y in range(len(quantum_state)):
text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255))
self.image.blit(text_surface,(120, y * block_size + y_offset))
if abs(quantum_state[y]) > 0:
#pygame.draw.rect(self.image, WHITE, rect, 0)
self.paddle.fill(WHITE)
self.paddle.set_alpha(int(round(abs(quantum_state[y])*255)))
self.image.blit(self.paddle,(80,y * block_size))
def set_circuit_measure(self, circuit, qubit_num, shot_num):
backend_sv_sim = BasicAer.get_backend('qasm_simulator')
cr = ClassicalRegister(qubit_num)
circuit2 = deepcopy(circuit)
circuit2.add_register(cr)
circuit2.measure(circuit2.qregs[0],circuit2.cregs[0])
job_sim = execute(circuit2, backend_sv_sim, shots=shot_num)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
print(counts)
#quantum_state = result_sim.get_statevector(circuit, decimals=3)
# This square represent the probability of state after measurement
self.image = pygame.Surface([(circuit.width()+1) * 50, 500])
self.image.convert()
self.image.fill(BLACK)
self.rect = self.image.get_rect()
block_size = int(round(500 / 2 ** qubit_num))
x_offset = 50
y_offset = 15
self.paddle = pygame.Surface([10, block_size])
self.paddle.convert()
self.paddle.fill(WHITE)
#for y in range(len(quantum_state)):
# text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0))
# self.image.blit(text_surface,(120, y * block_size + y_offset))
# if abs(quantum_state[y]) > 0:
#pygame.draw.rect(self.image, WHITE, rect, 0)
#self.paddle.fill(WHITE)
# self.paddle.set_alpha(int(round(abs(quantum_state[y])*255)))
print(counts.keys())
print(int(list(counts.keys())[0],2))
self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size))
#pygame.time.wait(100)
return int(list(counts.keys())[0],2)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
# all libraries used by some part of the VQLS-implementation
from qiskit import (
QuantumCircuit, QuantumRegister, ClassicalRegister,
Aer, execute, transpile, assemble
)
from qiskit.circuit import Gate, Instruction
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import ZGate, YGate, XGate, IGate
from scipy.optimize import (
minimize, basinhopping, differential_evolution,
shgo, dual_annealing
)
import random
import numpy as np
import cmath
from typing import List, Set, Dict, Tuple, Optional, Union
# import the params object of the GlobalParameters class
# this provides the parameters used to desribed and model
# the problem the minimizer is supposed to use.
from GlobalParameters import params
# import the vqls algorithm and corresponding code
from vqls import (
generate_ansatz,
hadamard_test,
calculate_beta,
calculate_delta,
calculate_local_cost_function,
minimize_local_cost_function,
postCorrection,
_format_alpha,
_calculate_expectationValue_HadamardTest,
_U_primitive
)
# The user input for the VQLS-algorithm has to be given
# when params is initialized within GlobalParameters.py
# The decomposition for $A$ has to be manually
# inserted into the code of
# the class GlobalParameters.
print(
"This program will execute a simulation of the VQLS-algorithm "
+ "with 4 qubits, 4 layers in the Ansatz and a single Id-gate acting"
+ " on the second qubit.\n"
+ "To simulate another problem, one can either alter _U_primitive "
+ "in vqls.py to change |x_0>, GlobalParameters.py to change A "
+ "or its decomposition respectively."
)
# Executing the VQLS-algorithm
alpha_min = minimize_local_cost_function(params.method_minimization)
"""
Circuit with the $\vec{alpha}$ generated by the minimizer.
"""
# Create a circuit for the vqls-result
qr_min = QuantumRegister(params.n_qubits)
circ_min = QuantumCircuit(qr_min)
# generate $V(\vec{alpha})$ and copy $A$
ansatz = generate_ansatz(alpha_min).to_gate()
A_copy = params.A.copy()
if isinstance(params.A, Operator):
A_copy = A_copy.to_instruction()
# apply $V(\vec{alpha})$ and $A$ to the circuit
# this results in a state that is approximately $\ket{b}$
circ_min.append(ansatz, qr_min)
circ_min.append(A_copy, qr_min)
# apply post correction to fix for sign errors and a "mirroring"
# of the result
circ_min = postCorrection(circ_min)
"""
Reference circuit based on the definition of $\ket{b}$.
"""
circ_ref = _U_primitive()
"""
Simulate both circuits.
"""
# the minimizations result
backend = Aer.get_backend(
'statevector_simulator')
t_circ = transpile(circ_min, backend)
qobj = assemble(t_circ)
job = backend.run(qobj)
result = job.result()
print(
"This is the result of the simulation.\n"
+ "Reminder: 4 qubits and an Id-gate on the second qubit."
+ "|x_0> was defined by Hadamard gates acting on qubits 0 and 3.\n"
+ "The return value of the minimizer (alpha_min):\n"
+ str(alpha_min)
+ "\nThe resulting statevector for a circuit to which "
+ "V(alpha_min) and A and the post correction were applied:\n"
+ str(result.get_statevector())
)
t_circ = transpile(circ_ref, backend)
qobj = assemble(t_circ)
job = backend.run(qobj)
result = job.result()
print(
"And this is the statevector for the reference circuit: A |x_0>\n"
+ str(result.get_statevector())
)
print("these were Id gates and in U y on 0 and 1")
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!pip install qiskit
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place an Ry gate with a −3π/4 rotation
circ.ry(-3/4 * np.pi, qr[0])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
# Do the usual setup, but without classical registers or measurement
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, execute
qr = QuantumRegister(1)
circ = QuantumCircuit(qr)
# Place gates that will achieve the desired state
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circ, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector
quantum_state
# Plot the state vector on a Bloch sphere
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(quantum_state)
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
from sympy import *
from sympy.physics.quantum.state import Ket, Bra
import numpy as np
init_printing(use_unicode=True)
#in_1=Ket (0)
#in_1
in_1=Matrix([[1],[0],[0],[0]])
in_1
X_2 =Matrix([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])
CNOT=Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
X_2, CNOT
#Apply to circuit
out=CNOT*X_2*CNOT*in_1
out
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### added x gate ###
qc.x(qubit)
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
### Install Qiskit and relevant packages, if needed
### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages
%pip install qiskit[visualization]==1.0.2
%pip install qiskit-ibm-runtime
%pip install qiskit-aer
%pip install graphviz
%pip install qiskit-transpiler-service
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
### Save API Token, if needed
%set_env QXToken=deleteThisAndPasteYourTokenHere
# Set Grade only mode
%set_env QC_GRADE_ONLY=true
# Make sure there is no space between the equal sign
# and the beginning of your token
# qc-grader should be 0.18.10 (or higher)
import qc_grader
qc_grader.__version__
# Imports
import numpy as np
import matplotlib.pyplot as plt
from qiskit.circuit.library import EfficientSU2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_transpiler_service.transpiler_service import TranspilerService
# Import for grader
from qc_grader.challenges.iqc_2024 import grade_lab3_ait_ex1, grade_lab3_ait_ex2
NUM_QUBITS = 61
circuit = EfficientSU2(NUM_QUBITS, entanglement="circular", reps=1).decompose()
print(f"Original circuit -> Depth: {circuit.depth()}, CNOTs: {circuit.num_nonlocal_gates()}")
circuit.draw(fold=-1, output="mpl", style="iqp", scale=0.2)
transpiler_ai_false = TranspilerService(
backend_name="ibm_brisbane",
ai=False,
optimization_level=3
)
# Submit your answer using following code
grade_lab3_ait_ex1(transpiler_ai_false) # Expected result type: TranspilerService
circuit_ai_false = transpiler_ai_false.run(circuit)
print(f"Transpiled without AI -> Depth: {circuit_ai_false.depth()}, CNOTs: {circuit_ai_false.num_nonlocal_gates()}")
circuit_ai_false.draw(fold=-1, output="mpl", scale=0.2)
transpiler_ai_true = TranspilerService(
backend_name="ibm_brisbane",
ai=True,
optimization_level=3
)
# Submit your answer using following code
grade_lab3_ait_ex2(transpiler_ai_true) # Expected result type: TranspilerService
circuit_ai_true = transpiler_ai_true.run(circuit)
print(f"Transpiled with AI -> Depth: {circuit_ai_true.depth()}, CNOTs: {circuit_ai_true.num_nonlocal_gates()}")
circuit_ai_true.draw(fold=-1, output="mpl", scale=0.2)
# Transpiling locally using Qiskit SDK
service = QiskitRuntimeService()
backend = service.backend("ibm_sherbrooke")
pm = generate_preset_pass_manager(backend=backend, optimization_level=3)
# Run and compile results
num_qubits = [11, 21, 41, 61, 81]
num_cnots_local = []
num_cnots_with_ai = []
num_cnots_without_ai = []
for nq in num_qubits:
circuit = EfficientSU2(nq, entanglement="circular", reps=1).decompose()
# Using the Transpiler locally on Qiskit
circuit_local = pm.run(circuit)
# Using the transpiler service without AI
circuit_without_ai = transpiler_ai_false.run(circuit)
# Using the transpiler service with AI
circuit_with_ai = transpiler_ai_true.run(circuit)
num_cnots_local.append(circuit_local.num_nonlocal_gates())
num_cnots_without_ai.append(circuit_without_ai.num_nonlocal_gates())
num_cnots_with_ai.append(circuit_with_ai.num_nonlocal_gates())
plt.plot(num_qubits, num_cnots_with_ai, '.-')
plt.plot(num_qubits, num_cnots_without_ai, '.-')
plt.plot(num_qubits, num_cnots_local, '--')
plt.xlabel("Number of qubits")
plt.ylabel("CNOT count")
plt.legend(["Qiskit Transpiler Service with AI", "Qiskit Transpiler Service without AI", "Qiskit SDK"])
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, Alpine Quantum Technologies 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.
from math import pi
import pytest
import qiskit
from pydantic import ValidationError
from qiskit import QuantumCircuit
from qiskit_aqt_provider import api_models
from qiskit_aqt_provider.aqt_resource import AQTResource
from qiskit_aqt_provider.circuit_to_aqt import (
aqt_to_qiskit_circuit,
circuits_to_aqt_job,
qiskit_to_aqt_circuit,
)
from qiskit_aqt_provider.test.circuits import (
assert_circuits_equal_ignore_global_phase,
assert_circuits_equivalent,
empty_circuit,
qft_circuit,
random_circuit,
)
def test_no_circuit() -> None:
"""Cannot convert an empty list of circuits to an AQT job request."""
with pytest.raises(ValidationError):
circuits_to_aqt_job([], shots=1)
def test_empty_circuit() -> None:
"""Circuits need at least one measurement operation."""
qc = QuantumCircuit(1)
with pytest.raises(ValueError):
circuits_to_aqt_job([qc], shots=1)
def test_just_measure_circuit() -> None:
"""Circuits with only measurement operations are valid."""
shots = 100
qc = QuantumCircuit(1)
qc.measure_all()
expected = api_models.SubmitJobRequest(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
repetitions=shots,
number_of_qubits=1,
quantum_circuit=api_models.Circuit(root=[api_models.Operation.measure()]),
),
]
),
)
result = circuits_to_aqt_job([qc], shots=shots)
assert result == expected
def test_valid_circuit() -> None:
"""A valid circuit with all supported basis gates."""
qc = QuantumCircuit(2)
qc.r(pi / 2, 0, 0)
qc.rz(pi / 5, 1)
qc.rxx(pi / 2, 0, 1)
qc.measure_all()
result = circuits_to_aqt_job([qc], shots=1)
expected = api_models.SubmitJobRequest(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
root=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.rz(phi=0.2, qubit=1),
api_models.Operation.rxx(theta=0.5, qubits=[0, 1]),
api_models.Operation.measure(),
]
),
),
]
),
)
assert result == expected
def test_invalid_gates_in_circuit() -> None:
"""Circuits must already be in the target basis when they are converted
to the AQT wire format.
"""
qc = QuantumCircuit(1)
qc.h(0) # not an AQT-resource basis gate
qc.measure_all()
with pytest.raises(ValueError, match="not in basis gate set"):
circuits_to_aqt_job([qc], shots=1)
def test_invalid_measurements() -> None:
"""Measurement operations can only be located at the end of the circuit."""
qc_invalid = QuantumCircuit(2, 2)
qc_invalid.r(pi / 2, 0.0, 0)
qc_invalid.measure([0], [0])
qc_invalid.r(pi / 2, 0.0, 1)
qc_invalid.measure([1], [1])
with pytest.raises(ValueError, match="at the end of the circuit"):
circuits_to_aqt_job([qc_invalid], shots=1)
# same circuit as above, but with the measurements at the end is valid
qc = QuantumCircuit(2, 2)
qc.r(pi / 2, 0.0, 0)
qc.r(pi / 2, 0.0, 1)
qc.measure([0], [0])
qc.measure([1], [1])
result = circuits_to_aqt_job([qc], shots=1)
expected = api_models.SubmitJobRequest(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
root=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.r(theta=0.5, phi=0.0, qubit=1),
api_models.Operation.measure(),
]
),
),
]
),
)
assert result == expected
def test_convert_multiple_circuits() -> None:
"""Convert multiple circuits. Check that the order is conserved."""
qc0 = QuantumCircuit(2)
qc0.r(pi / 2, 0.0, 0)
qc0.rxx(pi / 2, 0, 1)
qc0.measure_all()
qc1 = QuantumCircuit(1)
qc1.r(pi / 4, 0.0, 0)
qc1.measure_all()
result = circuits_to_aqt_job([qc0, qc1], shots=1)
expected = api_models.SubmitJobRequest(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
root=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.rxx(theta=0.5, qubits=[0, 1]),
api_models.Operation.measure(),
]
),
),
api_models.QuantumCircuit(
number_of_qubits=1,
repetitions=1,
quantum_circuit=api_models.Circuit(
root=[
api_models.Operation.r(theta=0.25, phi=0.0, qubit=0),
api_models.Operation.measure(),
]
),
),
],
),
)
assert result == expected
@pytest.mark.parametrize(
"circuit",
[
pytest.param(empty_circuit(2, with_final_measurement=False), id="empty-2"),
pytest.param(random_circuit(2, with_final_measurement=False), id="random-2"),
pytest.param(random_circuit(3, with_final_measurement=False), id="random-3"),
pytest.param(random_circuit(5, with_final_measurement=False), id="random-5"),
pytest.param(qft_circuit(5), id="qft-5"),
],
)
def test_convert_circuit_round_trip(
circuit: QuantumCircuit, offline_simulator_no_noise: AQTResource
) -> None:
"""Check that transpiled qiskit circuits can be round-tripped through the API format."""
trans_qc = qiskit.transpile(circuit, offline_simulator_no_noise)
# There's no measurement in the circuit, so unitary operator equality
# can be used to check the transpilation result.
assert_circuits_equivalent(trans_qc, circuit)
# Add the measurement operation to allow conversion to the AQT API format.
trans_qc.measure_all()
aqt_circuit = qiskit_to_aqt_circuit(trans_qc)
trans_qc_back = aqt_to_qiskit_circuit(aqt_circuit, trans_qc.num_qubits)
# transpiled circuits can be exactly reconstructed, up to the global
# phase which is irrelevant for execution
assert_circuits_equal_ignore_global_phase(trans_qc_back, trans_qc)
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.pyplot import arrow
from mpl_toolkits.axisartist.axislines import SubplotZero
from matplotlib.patches import Arc
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
def get_line_plot(angle, *, linewidth=1, linestyle="-", color="black"):
angle = math.radians(angle)
return Line2D([0, math.cos(angle) * 0.92], [0, math.sin(angle) * 0.92],
linewidth=linewidth, linestyle=linestyle, color=color)
def get_angle_plot(line1, line2, *, offset=1, color=None, origin=(0, 0),
len_x_axis = 1, len_y_axis = 1):
l1xy = line1.get_xydata()
# Angle between line1 and x-axis
y1 = l1xy[1][1] - l1xy[0][1]
x1 = l1xy[1][0] - l1xy[0][0]
slope1 = y1 / float(x1)
# Allows you to use this in different quadrants
angle1 = math.degrees(math.atan2(y1, x1))
l2xy = line2.get_xydata()
# Angle between line2 and x-axis
y2 = l2xy[1][1] - l2xy[0][1]
x2 = l2xy[1][0] - l2xy[0][0]
slope2 = y2 / float(x2)
angle2 = math.degrees(math.atan2(y2, x2))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if angle > 180:
angle = 360 - angle
theta1 = 360 + theta1
if theta1 > theta2:
theta1, theta2 = theta2, theta1
if color is None:
color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0,
theta1, theta2, color=color,
label = r'${:.4}^\circ$'.format(float(angle)))
def get_angle_text(angle_plot):
angle = angle_plot.get_label()
# angle = r'${:.4}^\circ$'.format(angle) # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = angle_plot.get_verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][1] + vertices[-1][1]) / 2.0
separation_radius = max(x_width / 2.0, y_width / 2.0)
return [x_width + separation_radius, y_width + separation_radius, angle]
class AnglePoltter:
def __init__(self):
self.lines = []
self.arcs = []
self.angles = []
def add_line(self, angle, *, linewidth=1, linestyle="-", color="black"):
line = get_line_plot(angle, linewidth=linewidth, linestyle=linestyle, color=color)
self.lines.append(
[
line.get_xdata()[0], line.get_ydata()[0], line.get_xdata()[1], line.get_ydata()[1],
linewidth, linestyle, color
]
)
return line
def add_angle(self, line1, line2, *, text=False, **kwargs):
angle = get_angle_plot(line1, line2, **kwargs)
self.arcs.append(angle)
if text:
self.angles.append(get_angle_text(angle))
def plot(self, *, title, fontsize=18):
fig = plt.figure()
ax = SubplotZero(fig, 1, 1, 1)
# draw a circle
theta = np.linspace(0, 2 * np.pi, 200)
x = np.cos(theta)
y = np.sin(theta)
ax.plot(x, y, color="#CCCCCC", linewidth=1.5)
fig.add_subplot(ax)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('-|>')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for line in self.lines:
if line[4] != 0:
ax.arrow(line[0], line[1], line[2], line[3],
head_width=0.06, head_length=0.06,
linewidth=line[4], linestyle=line[5], color=line[6])
for arc in self.arcs:
ax.add_patch(arc)
for angle in self.angles:
ax.text(*angle)
if title != None:
fig.suptitle(title, fontsize=fontsize)
plt.axis([-1.8, 1.8, -1.35, 1.35])
plt.grid()
plt.legend()
return ax
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(150, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
plotter.add_angle(line_5, line_3, offset=0.6)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x, 0], [y, -1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
theta = math.degrees(math.asin(1/(8 ** 0.5)))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(7 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
plotter.add_angle(line_5, line_4, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
x2 = math.cos(math.radians(3 * 45))
y2 = math.sin(math.radians(3 * 45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF9900")
line_4 = plotter.add_line(5 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.plot(title="Grover reflections - initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.add_angle(line_O_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 1")
x = math.cos(math.radians(25))
y = math.sin(math.radians(25))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 2")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, linestyle=":", color="#FF9900")
line_mRO_phi = plotter.add_line(105, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
plotter.add_angle(line_mRO_phi, line_phi, offset=1)
ax = plotter.plot(title="Grover reflections - reflection3")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(92, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(50, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend = FakeVigo()
# Construct quantum circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
sim_ideal = AerSimulator()
# Execute and get counts
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts = result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
sim_vigo = AerSimulator.from_backend(device_backend)
# Transpile the circuit for the noisy basis gates
tcirc = transpile(circ, sim_vigo)
# Execute noisy simulation and get counts
result_noise = sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise,
title="Counts for 3-qubit GHZ state with device noise model")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Tests for PauliList class."""
import itertools
import unittest
from test import combine
import numpy as np
from ddt import ddt
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.circuit.library import (
CXGate,
CYGate,
CZGate,
HGate,
IGate,
SdgGate,
SGate,
SwapGate,
XGate,
YGate,
ZGate,
)
from qiskit.quantum_info.operators import (
Clifford,
Operator,
Pauli,
PauliList,
PauliTable,
StabilizerTable,
)
from qiskit.quantum_info.random import random_clifford, random_pauli_list
from qiskit.test import QiskitTestCase
from .test_pauli import pauli_group_labels
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
if label[0:2] == "-i":
mat *= -1j
label = label[2:]
elif label[0] == "-":
mat *= -1
label = label[1:]
elif label[0] == "i":
mat *= 1j
label = label[1:]
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestPauliListInit(QiskitTestCase):
"""Tests for PauliList initialization."""
def test_array_init(self):
"""Test array initialization."""
# Matrix array initialization
with self.subTest(msg="Empty array"):
x = np.array([], dtype=bool).reshape((1, 0))
z = np.array([], dtype=bool).reshape((1, 0))
pauli_list = PauliList.from_symplectic(x, z)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array"):
z = np.array([[False], [True]])
x = np.array([[False], [True]])
pauli_list = PauliList.from_symplectic(z, x)
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="bool array no copy"):
z = np.array([[False], [True]])
x = np.array([[True], [True]])
pauli_list = PauliList.from_symplectic(z, x)
z[0, 0] = not z[0, 0]
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
def test_string_init(self):
"""Test string initialization."""
# String initialization
with self.subTest(msg='str init "I"'):
pauli_list = PauliList("I")
z = np.array([[False]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "X"'):
pauli_list = PauliList("X")
z = np.array([[False]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Y"'):
pauli_list = PauliList("Y")
z = np.array([[True]])
x = np.array([[True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "Z"'):
pauli_list = PauliList("Z")
z = np.array([[True]])
x = np.array([[False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZ"'):
pauli_list = PauliList("iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-Z"'):
pauli_list = PauliList("-Z")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([2])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "-iZ"'):
pauli_list = PauliList("-iZ")
z = np.array([[True]])
x = np.array([[False]])
phase = np.array([1])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "IX"'):
pauli_list = PauliList("IX")
z = np.array([[False, False]])
x = np.array([[True, False]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "XI"'):
pauli_list = PauliList("XI")
z = np.array([[False, False]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "YZ"'):
pauli_list = PauliList("YZ")
z = np.array([[True, True]])
x = np.array([[False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg='str init "iZY"'):
pauli_list = PauliList("iZY")
z = np.array([[True, True]])
x = np.array([[True, False]])
phase = np.array([3])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
np.testing.assert_equal(pauli_list.phase, phase)
with self.subTest(msg='str init "XIZ"'):
pauli_list = PauliList("XIZ")
z = np.array([[True, False, False]])
x = np.array([[False, False, True]])
np.testing.assert_equal(pauli_list.z, z)
np.testing.assert_equal(pauli_list.x, x)
with self.subTest(msg="str init prevent broadcasting"):
with self.assertRaises(ValueError):
PauliList(["XYZ", "I"])
def test_list_init(self):
"""Test list initialization."""
with self.subTest(msg="PauliList"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliList no copy"):
target = PauliList(["iXI", "IX", "IZ"])
value = PauliList(target)
value[0] = "-iII"
self.assertEqual(value, target)
def test_pauli_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_stabilizer_table_init(self):
"""Test table initialization."""
with self.subTest(msg="PauliTable"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+II", "-XZ"])
value = PauliList(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
with self.assertWarns(DeprecationWarning):
target = StabilizerTable.from_labels(["+YY", "-XZ", "XI"])
value = PauliList(target)
value[0] = "II"
self.assertEqual(value, target)
def test_init_from_settings(self):
"""Test initializing from the settings dictionary."""
pauli_list = PauliList(["IX", "-iYZ", "YY"])
from_settings = PauliList(**pauli_list.settings)
self.assertEqual(pauli_list, from_settings)
@ddt
class TestPauliListProperties(QiskitTestCase):
"""Tests for PauliList properties."""
def test_x_property(self):
"""Test X property"""
with self.subTest(msg="X"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.x == array))
with self.subTest(msg="set X"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.x = val
self.assertEqual(pauli, PauliList(["II", "iXY"]))
with self.subTest(msg="set X raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.x = val
def test_z_property(self):
"""Test Z property"""
with self.subTest(msg="Z"):
pauli = PauliList(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.z == array))
with self.subTest(msg="set Z"):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.z = val
self.assertEqual(pauli, PauliList(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.z = val
def test_phase_property(self):
"""Test phase property"""
with self.subTest(msg="phase"):
pauli = PauliList(["XI", "IZ", "YY", "YI"])
array = np.array([0, 0, 0, 0], dtype=int)
np.testing.assert_equal(pauli.phase, array)
with self.subTest(msg="set phase"):
pauli = PauliList(["XI", "IZ"])
val = np.array([2, 3], dtype=int)
pauli.phase = val
self.assertEqual(pauli, PauliList(["-XI", "iIZ"]))
with self.subTest(msg="set Z raises"):
with self.assertRaises(Exception):
pauli = PauliList(["XI", "IZ"])
val = np.array([1, 2, 3], dtype=int)
pauli.phase = val
def test_shape_property(self):
"""Test shape property"""
shape = (3, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.shape, shape)
@combine(j=range(1, 10))
def test_size_property(self, j):
"""Test size property"""
shape = (j, 4)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(len(pauli), j)
@combine(j=range(1, 10))
def test_n_qubit_property(self, j):
"""Test n_qubit property"""
shape = (5, j)
pauli = PauliList.from_symplectic(np.zeros(shape), np.zeros(shape))
self.assertEqual(pauli.num_qubits, j)
def test_eq(self):
"""Test __eq__ method."""
pauli1 = PauliList(["II", "XI"])
pauli2 = PauliList(["XI", "II"])
self.assertEqual(pauli1, pauli1)
self.assertNotEqual(pauli1, pauli2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
pauli = PauliList(labels)
self.assertEqual(len(pauli), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["XXI", "IXX"]
labels2 = ["XXI", "ZZI", "ZYZ"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
target = PauliList(labels1 + labels2)
self.assertEqual(target, pauli1 + pauli2)
def test_add_qargs(self):
"""Test add method with qargs."""
pauli1 = PauliList(["IIII", "YYYY"])
pauli2 = PauliList(["XY", "YZ"])
pauli3 = PauliList(["X", "Y", "Z"])
with self.subTest(msg="qargs=[0, 1]"):
target = PauliList(["IIII", "YYYY", "IIXY", "IIYZ"])
self.assertEqual(pauli1 + pauli2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
target = PauliList(["IIII", "YYYY", "XIIY", "YIIZ"])
self.assertEqual(pauli1 + pauli2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
target = PauliList(["IIII", "YYYY", "IYXI", "IZYI"])
self.assertEqual(pauli1 + pauli2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
target = PauliList(["IIII", "YYYY", "YIXI", "ZIYI"])
self.assertEqual(pauli1 + pauli2([3, 1]), target)
with self.subTest(msg="qargs=[0]"):
target = PauliList(["IIII", "YYYY", "IIIX", "IIIY", "IIIZ"])
self.assertEqual(pauli1 + pauli3([0]), target)
with self.subTest(msg="qargs=[1]"):
target = PauliList(["IIII", "YYYY", "IIXI", "IIYI", "IIZI"])
self.assertEqual(pauli1 + pauli3([1]), target)
with self.subTest(msg="qargs=[2]"):
target = PauliList(["IIII", "YYYY", "IXII", "IYII", "IZII"])
self.assertEqual(pauli1 + pauli3([2]), target)
with self.subTest(msg="qargs=[3]"):
target = PauliList(["IIII", "YYYY", "XIII", "YIII", "ZIII"])
self.assertEqual(pauli1 + pauli3([3]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(labels)
self.assertEqual(pauli[0], PauliList(labels[0]))
self.assertEqual(pauli[1], PauliList(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
inds = [0, 3]
self.assertEqual(pauli[inds], PauliList(labels[inds]))
inds = np.array([4, 1])
self.assertEqual(pauli[inds], PauliList(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
pauli = PauliList(labels)
self.assertEqual(pauli[:], pauli)
self.assertEqual(pauli[1:3], PauliList(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["XI", "IY"]
pauli = PauliList(["XI", "IY"])
pauli[0] = "II"
self.assertEqual(pauli[0], PauliList("II"))
pauli[1] = "-iXX"
self.assertEqual(pauli[1], PauliList("-iXX"))
with self.assertRaises(Exception):
# Wrong size Pauli
pauli[0] = "XXX"
with self.subTest(msg="__setitem__ array"):
labels = np.array(["XI", "IY", "IZ"])
pauli = PauliList(labels)
target = PauliList(["II", "ZZ"])
inds = [2, 0]
pauli[inds] = target
self.assertEqual(pauli[inds], target)
with self.assertRaises(Exception):
pauli[inds] = PauliList(["YY", "ZZ", "XX"])
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["III"])
pauli = PauliList(labels)
target = PauliList(5 * ["XXX"])
pauli[:] = target
self.assertEqual(pauli[:], target)
target = PauliList(2 * ["ZZZ"])
pauli[1:3] = target
self.assertEqual(pauli[1:3], target)
class TestPauliListLabels(QiskitTestCase):
"""Tests PauliList label representation conversions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "Z", "Z", "X", "Y"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_1q_with_phase(self):
"""Test 1-qubit from_labels method with phase."""
labels = ["-I", "iZ", "iZ", "X", "-iY"]
target = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 3, 0, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_2q_with_phase(self):
"""Test 2-qubit from_labels method."""
labels = ["iII", "iYY", "-iXZ"]
target = PauliList.from_symplectic(
np.array([[False, False], [True, True], [True, False]]),
np.array([[False, False], [True, True], [False, True]]),
np.array([3, 3, 1]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
target = PauliList.from_symplectic(
np.array([[False] * 5, [False] * 5, [True] * 5, [True] * 5]),
np.array([[False] * 5, [True] * 5, [True] * 5, [False] * 5]),
)
value = PauliList(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_with_phase(self):
"""Test 1-qubit to_labels method with phase."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([1, 3, 2, 3, 1]),
)
target = ["-iI", "iZ", "-Z", "iX", "-iY"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_to_labels_1q_array_with_phase(self):
"""Test 1-qubit to_labels method w/ array=True."""
pauli = PauliList.from_symplectic(
np.array([[False], [True], [True], [False], [True]]),
np.array([[False], [False], [False], [True], [True]]),
np.array([2, 3, 0, 1, 0]),
)
target = np.array(["-I", "iZ", "Z", "-iX", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
value = PauliList(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ", "-iZIX", "-IYX"]
target = np.array(labels)
value = PauliList(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliListMatrix(QiskitTestCase):
"""Tests PauliList matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
value = PauliList(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q_with_phase(self):
"""Test 5-qubit to_matrix method with phase."""
labels = ["iIXIXI", "-YZIXI", "-iIIXYZ"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse_with_phase(self):
"""Test 5-qubit to_matrix method w/ sparse=True with phase."""
labels = ["iXXXYY", "-IXIZY", "-iZYXIX"]
targets = [pauli_mat(i) for i in labels]
values = PauliList(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliListIteration(QiskitTestCase):
"""Tests for PauliList iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli):
self.assertEqual(i, PauliList(labels[idx]))
def test_iter(self):
"""Test iter with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(iter(pauli)):
self.assertEqual(i, PauliList(labels[idx]))
def test_zip(self):
"""Test zip with PauliList."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for label, i in zip(labels, pauli):
self.assertEqual(i, PauliList(label))
def test_label_iter(self):
"""Test PauliList label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliList dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliList sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
pauli = PauliList(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliListOperator(QiskitTestCase):
"""Tests for PauliList base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList([l1 + l2 for l1 in labels1 for l2 in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_tensor_with_phase(self, j):
"""Test tensor method j={j} with phase."""
labels1 = ["XX", "iYY"]
labels2 = [j * "I", "i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.tensor(pauli2)
target = PauliList(["XX" + "I" * j, "iXX" + "Z" * j, "iYY" + "I" * j, "-YY" + "Z" * j])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand_with_phase(self, j):
"""Test expand method j={j}."""
labels1 = ["-XX", "iYY"]
labels2 = ["i" + j * "I", "-i" + j * "Z"]
pauli1 = PauliList(labels1)
pauli2 = PauliList(labels2)
value = pauli1.expand(pauli2)
target = PauliList(
["-i" + "I" * j + "XX", "-" + "I" * j + "YY", "i" + "Z" * j + "XX", "Z" * j + "YY"]
)
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
target = PauliList(["X", "I", "iZ", "-iY"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
target = PauliList(["Y", "-iZ", "I", "iX"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
target = PauliList(["Z", "iY", "-iX", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
pauli = PauliList(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
target = PauliList(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
target = PauliList(["X", "I", "-iZ", "iY"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
target = PauliList(["Y", "iZ", "I", "-iX"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
target = PauliList(["Z", "-iY", "iX", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "iXXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
target = PauliList(["IZI", "iXYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
target = PauliList(["ZII", "iYXX"])
value = pauli1.compose(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_dot_1q(self):
"""Test 1-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
target = PauliList(["IIZ", "-iXXY"])
value = pauli1.dot(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
target = PauliList(["IZI", "-iXYX"])
value = pauli1.dot(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[2]"):
target = PauliList(["ZII", "-iYXX"])
value = pauli1.dot(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_compose_2q(self):
"""Test 2-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.compose(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.compose(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.compose(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.compose(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_dot_2q(self):
"""Test 2-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
target = PauliList(["IZY", "XYZ"])
value = pauli1.dot(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[1, 0]"):
target = PauliList(["IYZ", "XZY"])
value = pauli1.dot(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[0, 2]"):
target = PauliList(["ZIY", "YXZ"])
value = pauli1.dot(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
target = PauliList(["YIZ", "ZXY"])
value = pauli1.dot(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_compose_3q(self):
"""Test 3-qubit compose method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="compose 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2)
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.compose(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.compose(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.compose(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
def test_qargs_dot_3q(self):
"""Test 3-qubit dot method with qargs."""
pauli1 = PauliList(["III", "XXX"])
pauli2 = PauliList("XYZ")
with self.subTest(msg="dot 3-qubit qargs=None"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
target = PauliList(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
target = PauliList(["ZYX", "YZI"])
value = pauli1.dot(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"):
target = PauliList(["XZY", "IYZ"])
value = pauli1.dot(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
@ddt
class TestPauliListMethods(QiskitTestCase):
"""Tests for PauliList utility methods class."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit standard order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "-iI", "-I", "iI", "X", "X", "Y", "-iY", "Z", "Z"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight & phase order"):
unsrt = ["X", "Z", "I", "Y", "-iI", "X", "Z", "iI", "-I", "-iY"]
srt = ["I", "X", "X", "Y", "Z", "Z", "-iI", "-iY", "-I", "iI"]
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YI",
"YI",
"-YI",
"YX",
"-iYX",
"YY",
"-iYY",
"-YY",
"iYY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"iIZ",
"XI",
"YI",
"YI",
"-YI",
"ZI",
"XX",
"XX",
"iXX",
"XY",
"XZ",
"iXZ",
"YX",
"-iYX",
"YY",
"YY",
"-YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XX",
"XY",
"XZ",
"YI",
"YI",
"YX",
"YY",
"YY",
"YZ",
"ZI",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight & phase order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"YI",
"YI",
"ZI",
"XX",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
"-iYX",
"-YI",
"-YY",
"iIZ",
"iXX",
"iXZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit standard order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"-IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"iIXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"-iXXX",
"XXY",
"XXZ",
"XYX",
"iXYX",
"XYY",
"XYZ",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"iZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
"-iXXX",
"-IIY",
"iIXY",
"iXYX",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(phase=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight & phase order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IYI",
"IZI",
"XII",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZYI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
"-iZIZ",
"-iXXX",
"-IIY",
"iIXI",
"iIXY",
"iYXI",
"iXYX",
"iXYZ",
"iZXX",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
target = PauliList(srt)
value = PauliList(unsrt).sort(weight=True, phase=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"]
unique = ["X", "Z", "I", "Y"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"]
unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", 10 * "I"]
target = PauliList(unique)
value = PauliList(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
pauli = PauliList([j * "X", j * "Y"])
self.assertEqual(pauli.delete(0), PauliList(j * "Y"))
self.assertEqual(pauli.delete(1), PauliList(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
pauli = PauliList([j * "X", "-i" + j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z"))
with self.subTest(msg="single qubit"):
pauli = PauliList(["IIX", "iIYI", "ZII"])
value = pauli.delete(0, qubit=True)
target = PauliList(["II", "iIY", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(1, qubit=True)
target = PauliList(["IX", "iII", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(2, qubit=True)
target = PauliList(["IX", "iYI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
pauli = PauliList(["IIX", "IYI", "-ZII"])
value = pauli.delete([0, 1], qubit=True)
target = PauliList(["I", "I", "-Z"])
self.assertEqual(value, target)
value = pauli.delete([1, 2], qubit=True)
target = PauliList(["X", "I", "-I"])
self.assertEqual(value, target)
value = pauli.delete([0, 2], qubit=True)
target = PauliList(["I", "Y", "-I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
pauli = PauliList(j * "X")
target0 = PauliList([j * "I", j * "X"])
target1 = PauliList([j * "X", j * "I"])
with self.subTest(msg=f"single row from str ({j})"):
value0 = pauli.insert(0, j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from PauliList ({j})"):
value0 = pauli.insert(0, PauliList(j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList(j * "I"))
self.assertEqual(value1, target1)
target0 = PauliList(["i" + j * "I", j * "X"])
target1 = PauliList([j * "X", "i" + j * "I"])
with self.subTest(msg=f"single row with phase from str ({j})"):
value0 = pauli.insert(0, "i" + j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, "i" + j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row with phase from PauliList ({j})"):
value0 = pauli.insert(0, PauliList("i" + j * "I"))
self.assertEqual(value0, target0)
value1 = pauli.insert(1, PauliList("i" + j * "I"))
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
pauli = PauliList("i" + j * "X")
insert = PauliList([j * "I", j * "Y", j * "Z", "-i" + j * "X"])
target0 = insert + pauli
target1 = pauli + insert
with self.subTest(msg=f"multiple-rows from PauliList ({j})"):
value0 = pauli.insert(0, insert)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert)
self.assertEqual(value1, target1)
# Insert single column
pauli = PauliList(["X", "Y", "Z", "-iI"])
for i in ["I", "X", "Y", "Z", "iY"]:
phase = "" if len(i) == 1 else i[0]
p = i if len(i) == 1 else i[1]
target0 = PauliList(
[
phase + "X" + p,
phase + "Y" + p,
phase + "Z" + p,
("" if phase else "-i") + "I" + p,
]
)
target1 = PauliList(
[
i + "X",
i + "Y",
i + "Z",
("" if phase else "-i") + p + "I",
]
)
with self.subTest(msg="single-column single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
pauli = PauliList(["X", "Y", "iZ"])
for i in [["I", "X", "Y"], ["X", "iY", "Z"], ["Y", "Z", "I"]]:
target0 = PauliList(
["X" + i[0], "Y" + i[1] if len(i[1]) == 1 else i[1][0] + "Y" + i[1][1], "iZ" + i[2]]
)
target1 = PauliList([i[0] + "X", i[1] + "Y", "i" + i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
pauli = PauliList(["X", "iY", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", "i" + j * "Z"]:
phase = "" if len(i) == j else i[0]
p = i if len(i) == j else i[1:]
target0 = PauliList(
[
phase + "X" + p,
("-" if phase else "i") + "Y" + p,
phase + "Z" + p,
]
)
target1 = PauliList([i + "X", ("-" if phase else "i") + p + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
pauli = PauliList(["X", "Y", "-iZ"])
for j in range(1, 5):
for i in [
[j * "I", j * "X", j * "Y"],
[j * "X", j * "Z", "i" + j * "Y"],
[j * "Y", j * "Z", j * "I"],
]:
target0 = PauliList(
[
"X" + i[0],
"Y" + i[1],
("-i" if len(i[2]) == j else "") + "Z" + i[2][-j:],
]
)
target1 = PauliList(
[
i[0] + "X",
i[1] + "Y",
("-i" if len(i[2]) == j else "") + i[2][-j:] + "Z",
]
)
with self.subTest(msg="multiple-column multiple-vals from PauliList"):
value = pauli.insert(0, PauliList(i), qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, PauliList(i), qubit=True)
self.assertEqual(value, target1)
def test_commutes(self):
"""Test commutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes single-Pauli I"):
value = list(pauli.commutes("I"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli X"):
value = list(pauli.commutes("X"))
target = [True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Y"):
value = list(pauli.commutes("Y"))
target = [True, False, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Z"):
value = list(pauli.commutes("Z"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iZ"):
value = list(pauli.commutes("iZ"))
target = [True, False, False, True, False]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "-iYY"])
with self.subTest(msg="commutes single-Pauli II"):
value = list(pauli.commutes("II"))
target = [True, True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IX"):
value = list(pauli.commutes("IX"))
target = [True, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XI"):
value = list(pauli.commutes("XI"))
target = [True, True, False, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YI"):
value = list(pauli.commutes("YI"))
target = [True, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IY"):
value = list(pauli.commutes("IY"))
target = [True, False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XY"):
value = list(pauli.commutes("XY"))
target = [True, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YX"):
value = list(pauli.commutes("YX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli ZZ"):
value = list(pauli.commutes("ZZ"))
target = [True, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli iYX"):
value = list(pauli.commutes("iYX"))
target = [True, True, True, True, True, False]
self.assertEqual(value, target)
def test_anticommutes(self):
"""Test anticommutes method."""
# Single qubit Pauli
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes single-Pauli I"):
value = list(pauli.anticommutes("I"))
target = [False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli X"):
value = list(pauli.anticommutes("X"))
target = [False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Y"):
value = list(pauli.anticommutes("Y"))
target = [False, True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli Z"):
value = list(pauli.anticommutes("Z"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iZ"):
value = list(pauli.anticommutes("iZ"))
target = [False, True, True, False, True]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes single-Pauli II"):
value = list(pauli.anticommutes("II"))
target = [False, False, False, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IX"):
value = list(pauli.anticommutes("IX"))
target = [False, False, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XI"):
value = list(pauli.anticommutes("XI"))
target = [False, False, True, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YI"):
value = list(pauli.anticommutes("YI"))
target = [False, False, False, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli IY"):
value = list(pauli.anticommutes("IY"))
target = [False, True, False, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli XY"):
value = list(pauli.anticommutes("XY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli YX"):
value = list(pauli.anticommutes("YX"))
target = [False, False, False, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli ZZ"):
value = list(pauli.anticommutes("ZZ"))
target = [False, True, True, False, False, True]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes single-Pauli iXY"):
value = list(pauli.anticommutes("iXY"))
target = [False, True, True, False, False, False]
self.assertEqual(value, target)
def test_commutes_with_all(self):
"""Test commutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="commutes_with_all [I]"):
value = list(pauli.commutes_with_all("I"))
target = [0, 1, 2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [X]"):
value = list(pauli.commutes_with_all("X"))
target = [0, 1]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Y]"):
value = list(pauli.commutes_with_all("Y"))
target = [0, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Z]"):
value = list(pauli.commutes_with_all("Z"))
target = [0, 3]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [iY]"):
value = list(pauli.commutes_with_all("iY"))
target = [0, 2, 4]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iXY"])
with self.subTest(msg="commutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [-iYX, iZZ]"):
other = PauliList(["-iYX", "iZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4, 5]
self.assertEqual(value, target)
def test_anticommutes_with_all(self):
"""Test anticommutes_with_all method."""
# 1-qubit
pauli = PauliList(["I", "X", "Y", "Z", "-iY"])
with self.subTest(msg="anticommutes_with_all [I]"):
value = list(pauli.anticommutes_with_all("I"))
target = []
self.assertEqual(value, target)
with self.subTest(msg="antianticommutes_with_all [X]"):
value = list(pauli.anticommutes_with_all("X"))
target = [2, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Y]"):
value = list(pauli.anticommutes_with_all("Y"))
target = [1, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Z]"):
value = list(pauli.anticommutes_with_all("Z"))
target = [1, 2, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [iY]"):
value = list(pauli.anticommutes_with_all("iY"))
target = [1, 3]
self.assertEqual(value, target)
# 2-qubit Pauli
pauli = PauliList(["II", "IX", "YI", "XY", "ZZ", "iZX"])
with self.subTest(msg="anticommutes_with_all [IX, YI]"):
other = PauliList(["IX", "YI"])
value = list(pauli.anticommutes_with_all(other))
target = [3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, ZZ]"):
other = PauliList(["XY", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [1, 2]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, ZZ]"):
other = PauliList(["YX", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [5]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, YX]"):
other = PauliList(["XY", "YX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, IX]"):
other = PauliList(["XY", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, IX]"):
other = PauliList(["YX", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
@combine(
gate=(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
Clifford(IGate()),
Clifford(XGate()),
Clifford(YGate()),
Clifford(ZGate()),
Clifford(HGate()),
Clifford(SGate()),
Clifford(SdgGate()),
)
)
def test_evolve_clifford1(self, gate):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(1, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
@combine(
gate=(
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
Clifford(CXGate()),
Clifford(CYGate()),
Clifford(CZGate()),
Clifford(SwapGate()),
)
)
def test_evolve_clifford2(self, gate):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli_list = PauliList(pauli_group_labels(2, True))
value = [Operator(pauli) for pauli in pauli_list.evolve(gate)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(gate, frame="s")]
if isinstance(gate, Clifford):
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.adjoint())]
else:
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(gate.inverse())]
target = [op.adjoint().dot(pauli).dot(op) for pauli in pauli_list]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_phase_dtype_evolve_clifford(self):
"""Test phase dtype during evolve method for Clifford gates."""
gates = (
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
)
dtypes = [
int,
np.int8,
np.uint8,
np.int16,
np.uint16,
np.int32,
np.uint32,
np.int64,
np.uint64,
]
for gate, dtype in itertools.product(gates, dtypes):
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
@combine(phase=(True, False))
def test_evolve_clifford_qargs(self, phase):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli_list = random_pauli_list(5, 3, seed=10, phase=phase)
qargs = [3, 0, 1]
value = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs)]
value_inv = [Operator(pauli) for pauli in pauli_list.evolve(cliff.adjoint(), qargs=qargs)]
value_h = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="h")]
value_s = [Operator(pauli) for pauli in pauli_list.evolve(cliff, qargs=qargs, frame="s")]
target = [
Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
for pauli in pauli_list
]
self.assertListEqual(value, target)
self.assertListEqual(value, value_h)
self.assertListEqual(value_inv, value_s)
def test_group_qubit_wise_commuting(self):
"""Test grouping qubit-wise commuting operators"""
def qubitwise_commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and all(a.commutes(b) for a, b in zip(left, right))
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
groups = pauli_list.group_qubit_wise_commuting()
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator qubit-wise commutes with every other operator.
for group in groups:
self.assertTrue(
all(
qubitwise_commutes(pauli1, pauli2)
for pauli1, pauli2 in itertools.combinations(group, 2)
)
)
# For every pair of groups, at least one element from one does not qubit-wise commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
qubitwise_commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
def test_group_commuting(self):
"""Test general grouping commuting operators"""
def commutes(left: Pauli, right: Pauli) -> bool:
return len(left) == len(right) and left.commutes(right)
input_labels = ["IY", "ZX", "XZ", "YI", "YX", "YY", "YZ", "ZI", "ZX", "ZY", "iZZ", "II"]
np.random.shuffle(input_labels)
pauli_list = PauliList(input_labels)
# if qubit_wise=True, equivalent to test_group_qubit_wise_commuting
groups = pauli_list.group_commuting(qubit_wise=False)
# checking that every input Pauli in pauli_list is in a group in the ouput
output_labels = [pauli.to_label() for group in groups for pauli in group]
self.assertListEqual(sorted(output_labels), sorted(input_labels))
# Within each group, every operator commutes with every other operator.
for group in groups:
self.assertTrue(
all(commutes(pauli1, pauli2) for pauli1, pauli2 in itertools.combinations(group, 2))
)
# For every pair of groups, at least one element from one group does not commute with
# at least one element of the other.
for group1, group2 in itertools.combinations(groups, 2):
self.assertFalse(
all(
commutes(group1_pauli, group2_pauli)
for group1_pauli, group2_pauli in itertools.product(group1, group2)
)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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 for qiskit.quantum_info.analysis"""
import unittest
import qiskit
from qiskit import BasicAer
from qiskit.quantum_info.analysis.average import average_data
from qiskit.quantum_info.analysis.make_observable import make_dict_observable
from qiskit.quantum_info.analysis import hellinger_fidelity
from qiskit.test import QiskitTestCase
class TestAnalyzation(QiskitTestCase):
"""Test qiskit.Result API"""
def test_average_data_dict_observable(self):
"""Test average_data for dictionary observable input"""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = {"00": 1, "11": 1, "01": -1, "10": -1}
mean_zz = average_data(counts=counts, observable=observable)
observable = {"00": 1, "11": -1, "01": 1, "10": -1}
mean_zi = average_data(counts, observable)
observable = {"00": 1, "11": -1, "01": -1, "10": 1}
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_average_data_list_observable(self):
"""Test average_data for list observable input."""
qr = qiskit.QuantumRegister(3)
cr = qiskit.ClassicalRegister(3)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[0], qr[2])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.measure(qr[2], cr[2])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [1, -1, -1, 1, -1, 1, 1, -1]
mean_zzz = average_data(counts=counts, observable=observable)
observable = [1, 1, 1, 1, -1, -1, -1, -1]
mean_zii = average_data(counts, observable)
observable = [1, 1, -1, -1, 1, 1, -1, -1]
mean_izi = average_data(counts, observable)
observable = [1, 1, -1, -1, -1, -1, 1, 1]
mean_zzi = average_data(counts, observable)
self.assertAlmostEqual(mean_zzz, 0, places=1)
self.assertAlmostEqual(mean_zii, 0, places=1)
self.assertAlmostEqual(mean_izi, 0, places=1)
self.assertAlmostEqual(mean_zzi, 1, places=1)
def test_average_data_matrix_observable(self):
"""Test average_data for matrix observable input."""
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr, name="qc")
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
shots = 10000
backend = BasicAer.get_backend("qasm_simulator")
result = qiskit.execute(qc, backend, shots=shots).result()
counts = result.get_counts(qc)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]
mean_zz = average_data(counts=counts, observable=observable)
observable = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
mean_zi = average_data(counts, observable)
observable = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]
mean_iz = average_data(counts, observable)
self.assertAlmostEqual(mean_zz, 1, places=1)
self.assertAlmostEqual(mean_zi, 0, places=1)
self.assertAlmostEqual(mean_iz, 0, places=1)
def test_make_dict_observable(self):
"""Test make_dict_observable."""
list_in = [1, 1, -1, -1]
list_out = make_dict_observable(list_in)
list_expected = {"00": 1, "01": 1, "10": -1, "11": -1}
matrix_in = [[4, 0, 0, 0], [0, -3, 0, 0], [0, 0, 2, 0], [0, 0, 0, -1]]
matrix_out = make_dict_observable(matrix_in)
matrix_expected = {"00": 4, "01": -3, "10": 2, "11": -1}
long_list_in = [1, 1, -1, -1, -1, -1, 1, 1]
long_list_out = make_dict_observable(long_list_in)
long_list_expected = {
"000": 1,
"001": 1,
"010": -1,
"011": -1,
"100": -1,
"101": -1,
"110": 1,
"111": 1,
}
self.assertEqual(list_out, list_expected)
self.assertEqual(matrix_out, matrix_expected)
self.assertEqual(long_list_out, long_list_expected)
def test_hellinger_fidelity_same(self):
"""Test hellinger fidelity is one for same dist."""
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res = qiskit.execute(qc, sim).result()
ans = hellinger_fidelity(res.get_counts(), res.get_counts())
self.assertEqual(ans, 1.0)
def test_hellinger_fidelity_no_overlap(self):
"""Test hellinger fidelity is zero for no overlap."""
# ┌───┐ ┌─┐
# q_0: ──────────┤ X ├─────┤M├────────────
# ┌───┐└─┬─┘ └╥┘┌─┐
# q_1: ─────┤ X ├──■────────╫─┤M├─────────
# ┌───┐└─┬─┘ ║ └╥┘┌─┐
# q_2: ┤ H ├──■────■────────╫──╫─┤M├──────
# └───┘ ┌─┴─┐ ║ ║ └╥┘┌─┐
# q_3: ──────────┤ X ├──■───╫──╫──╫─┤M├───
# └───┘┌─┴─┐ ║ ║ ║ └╥┘┌─┐
# q_4: ───────────────┤ X ├─╫──╫──╫──╫─┤M├
# └───┘ ║ ║ ║ ║ └╥┘
# c: 5/═════════════════════╩══╩══╩══╩══╩═
# 0 1 2 3 4
qc = qiskit.QuantumCircuit(5, 5)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 3)
qc.cx(3, 4)
qc.cx(1, 0)
qc.measure(range(5), range(5))
# ┌───┐ ┌─┐
# q_0: ──────────┤ X ├─────┤M├─────────
# ┌───┐└─┬─┘ └╥┘┌─┐
# q_1: ─────┤ X ├──■────────╫─┤M├──────
# ┌───┐└─┬─┘┌───┐ ║ └╥┘┌─┐
# q_2: ┤ H ├──■──┤ Y ├──■───╫──╫─┤M├───
# └───┘ └───┘┌─┴─┐ ║ ║ └╥┘┌─┐
# q_3: ───────────────┤ X ├─╫──╫──╫─┤M├
# ┌─┐ └───┘ ║ ║ ║ └╥┘
# q_4: ─┤M├─────────────────╫──╫──╫──╫─
# └╥┘ ║ ║ ║ ║
# c: 5/══╩══════════════════╩══╩══╩══╩═
# 4 0 1 2 3
qc2 = qiskit.QuantumCircuit(5, 5)
qc2.h(2)
qc2.cx(2, 1)
qc2.y(2)
qc2.cx(2, 3)
qc2.cx(1, 0)
qc2.measure(range(5), range(5))
sim = BasicAer.get_backend("qasm_simulator")
res1 = qiskit.execute(qc, sim).result()
res2 = qiskit.execute(qc2, sim).result()
ans = hellinger_fidelity(res1.get_counts(), res2.get_counts())
self.assertEqual(ans, 0.0)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
import pennylane as qml
from pennylane import numpy as np
# Basis State preparation
def state_preparation(basis_id, n_qubits):
bits = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
return qml.BasisStatePreparation(bits, wires=range(n_qubits))
#Testing
state_preparation(3,5)
# Swappping of quantum circuits
def swap_bits(n_qubits):
"""A circuit that reverses the order of qubits, i.e.,
performs a SWAP such that [q1, q2, ..., qn] -> [qn, ... q2, q1].
Args:
n_qubits (int): An integer value identifying the number of qubits.
"""
for i in range(int(n_qubits/2)):
qml.SWAP(wires=[i,n_qubits-1-i])
# Conditional Rotation matrix
def qft_rotations(n_qubits):
"""A circuit performs the QFT rotations on the specified qubits.
Args:
n_qubits (int): An integer value identifying the number of qubits.
"""
n = n_qubits
for i in range(n):
qml.Hadamard(wires=i)
for jj in range(i+1,n,1):
qml.ControlledPhaseShift(np.pi/(2**(jj-i)), wires=[jj,i])
pass
def qft_node(basis_id, basis_id2, n_qubits):
''' A circuit performs addition of two numbers
Args:
basis_id (int): An integer value specifying the first number to be added.
basis_id2 (int): An integer value specifying the second number to be added.
n_qubits (int): An integer value identifying the number of qubits.
'''
# Prepare the basis state |basis_id>
bits = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
qml.BasisStatePreparation(bits, wires=range(n_qubits))
bits2 = [int(x) for x in np.binary_repr(basis_id2, width=n_qubits)]
qml.BasisStatePreparation(bits2, wires=range(n_qubits, 2*(n_qubits),1))
qft_rotations(n_qubits)
for i in range(0,n_qubits,1):
k=0
for j in range(i+n_qubits,(2*n_qubits),1):
qml.ControlledPhaseShift((np.pi/(2**(k))), wires=[j,i])
k+=1
(qml.adjoint)(qft_rotations)(n_qubits)
return qml.sample(wires=[x for x in range(n_qubits)])
# basis_id stores a, basis_id2 stores b
basis_id = int(input("Enter number a: "))
basis_id2 = int(input("Enter number b: "))
if len(np.binary_repr(basis_id))>len(np.binary_repr(basis_id2)):
n_qubits = len(np.binary_repr(basis_id)) + 1
else:
n_qubits = len(np.binary_repr(basis_id2)) + 1
dev = qml.device('default.qubit', wires=(2*n_qubits), shots=10)
qnode = qml.QNode(qft_node, dev)
k = qnode(basis_id, basis_id2, n_qubits)
poww, summ = 0, 0
for l in reversed(k[0]):
summ = summ + (2**poww)*l
poww+=1
print(summ)
def multiplier(basis_id, basis_id2, n_qubits):
''' A circuit performs multiplication of two numbers
Args:
basis_id (int): An integer value specifying the first number to be multiplied.
basis_id2 (int): An integer value specifying the second number to be multiplied.
n_qubits (int): An integer value identifying the number of qubits.
'''
# Basis state preparation for 0, a, b respectively
bits1 = [int(x) for x in np.binary_repr(0, width=2*n_qubits)]
qml.BasisStatePreparation(bits1, wires=range(2*(n_qubits)))
bits2 = [int(x) for x in np.binary_repr(basis_id, width=n_qubits)]
qml.BasisStatePreparation(bits2, wires=range(2*n_qubits, 3*n_qubits))
bits3 = [int(x) for x in np.binary_repr(basis_id2, width=n_qubits)]
qml.BasisStatePreparation(bits3, wires=range(3*n_qubits, 4*(n_qubits),1))
# Applying QFT on first 2*n_qubits as they store the basis state for |0>
qft_rotations(2*n_qubits)
# Applying Conditional Rotation operator with controls a_j and b_m and target as |0>
for i in range(3*n_qubits, 4*n_qubits,1):
for j in range(2*n_qubits, 3*n_qubits,1):
for m in range(2*n_qubits):
qml.ctrl(qml.PhaseShift(np.pi/(2**(-(5*n_qubits)-m+j+i+1)), wires=m),control=[j,i])
# Applying inverse QFT 2*n_qubits
(qml.adjoint)(qft_rotations)(2*n_qubits)
return qml.sample(wires=[x for x in range(2*n_qubits)])
# basis_id stores a, basis_id2 stores b
basis_id = int(input("Enter number a: "))
basis_id2 = int(input("Enter number b: "))
# n_qubits takes the value of the number whose binary representation is the greatest among the two
if len(np.binary_repr(basis_id))>len(np.binary_repr(basis_id2)):
n_qubits = len(np.binary_repr(basis_id))
else:
n_qubits = len(np.binary_repr(basis_id2))
# Creating QNode
dev = qml.device('default.qubit', wires=(4*n_qubits), shots=10)
qnode = qml.QNode(multiplier, dev)
# Below code returns the sample containing measurements on the wires
# print(qnode(basis_id,basis_id2,n_qubits))
# Below prints quantum circuit
# print(qml.draw(qnode)(basis_id,basis_id2,n_qubits))
# k stores the sample of measurement values on each wire
k = qnode(basis_id, basis_id2, n_qubits)
# Converting k[0] to integer value
# Considering only k[0] as all elements of the sample are identical
poww, summ = 0, 0
for l in reversed(k[0]):
summ = summ + (2**poww)*l
poww+=1
print(summ)
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
# Importing Packages
from qiskit import QuantumCircuit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
def encode(qc, qubit, msg):
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
# Circuit for Superdense coding
qc = QuantumCircuit(2)
# Generating entangled state
qc.h(1)
qc.cx(1, 0)
qc.barrier()
# Encoding message
message = '11'
qc = encode(qc, 1, message)
qc.barrier()
# Decoding Message
qc.cx(1, 0)
qc.h(1)
# Measuring qubits
qc.measure_all()
qc.draw(output="mpl", style=style)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc)
result = aer_sim.run(qobj).result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secret_number = '101001'
# here work is happen like buttom to up
for position,value in enumerate(reversed(secret_number)):
if value == '1':
print(position, value)
circuit = QuantumCircuit(6+1, 6)
circuit.h([0,1,2,3,4,5])
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h([0,1,2,3,4,5])
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([i for i in range(5)],[i for i in range(5)])
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)
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)
def find_secret_number(secter_number):
secret_number = str(secter_number)
# Using Bernstein Vazirani Algorithm
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)
secret_number = int(input("enter number(digits should be 0 or 1): "))
find_secret_number(secret_number)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import BasicAer
from qiskit.transpiler import PassManager
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver, IQPE
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.initial_states.var_form_based import VarFormBased
pauli_dict = {
'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
{"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "IZ"},
{"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "ZI"},
{"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
{"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
]
}
qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
result_reference = NumPyMinimumEigensolver(qubit_op).run()
print('The reference ground energy level is {}.'.format(result_reference.eigenvalue.real))
random_seed = 0
np.random.seed(random_seed)
backend = BasicAer.get_backend('qasm_simulator')
var_form_depth = 3
var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'], 'cz', reps=var_form_depth)
spsa_max_trials=10
optimizer = SPSA(max_trials=spsa_max_trials)
vqe = VQE(qubit_op, var_form, optimizer)
quantum_instance = QuantumInstance(backend)
result_vqe = vqe.run(quantum_instance)
print('VQE estimated the ground energy to be {}.'.format(result_vqe.eigenvalue.real))
state_in = VarFormBased(var_form, result_vqe.optimal_point)
num_time_slices = 1
num_iterations = 6
iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations,
expansion_mode='suzuki', expansion_order=2,
shallow_circuit_concat=True)
quantum_instance = QuantumInstance(backend, shots=100, seed_simulator=random_seed, seed_transpiler=random_seed)
result_iqpe = iqpe.run(quantum_instance)
print("Continuing with VQE's result, IQPE estimated the ground energy to be {}.".format(
result_iqpe.eigenvalue.real))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
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=IQXSimple())
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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=invalid-name,no-name-in-module,ungrouped-imports
"""A circuit library widget module"""
import ipywidgets as wid
from IPython.display import display
from qiskit import QuantumCircuit
from qiskit.utils import optionals as _optionals
from qiskit.utils.deprecation import deprecate_func
@_optionals.HAS_MATPLOTLIB.require_in_call
def _generate_circuit_library_visualization(circuit: QuantumCircuit):
import matplotlib.pyplot as plt
circuit = circuit.decompose()
ops = circuit.count_ops()
num_nl = circuit.num_nonlocal_gates()
_fig, (ax0, ax1) = plt.subplots(2, 1)
circuit.draw("mpl", ax=ax0)
ax1.axis("off")
ax1.grid(visible=None)
ax1.table(
[[circuit.name], [circuit.width()], [circuit.depth()], [sum(ops.values())], [num_nl]],
rowLabels=["Circuit Name", "Width", "Depth", "Total Gates", "Non-local Gates"],
)
plt.tight_layout()
plt.show()
@deprecate_func(
since="0.25.0",
additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.",
)
def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML:
"""Create a HTML table widget for a given quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
"""
circuit = circuit.decompose()
ops = circuit.count_ops()
num_nl = circuit.num_nonlocal_gates()
html = "<table>"
html += """<style>
table {
font-family: "IBM Plex Sans", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border-left: 2px solid #212121;
}
th {
text-align: left;
padding: 5px 5px 5px 5px;
width: 100%;
background-color: #988AFC;
color: #fff;
font-size: 14px;
border-left: 2px solid #988AFC;
}
td {
text-align: left;
padding: 5px 5px 5px 5px;
width: 100%;
font-size: 12px;
font-weight: medium;
}
tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
html += f"<tr><th>{circuit.name}</th><th></tr>"
html += f"<tr><td>Width</td><td>{circuit.width()}</td></tr>"
html += f"<tr><td>Depth</td><td>{circuit.depth()}</td></tr>"
html += f"<tr><td>Total Gates</td><td>{sum(ops.values())}</td></tr>"
html += f"<tr><td>Non-local Gates</td><td>{num_nl}</td></tr>"
html += "</table>"
out_wid = wid.HTML(html)
return out_wid
head_style = (
"font-family: IBM Plex Sans, Arial, Helvetica, sans-serif;"
" font-size: 20px; font-weight: medium;"
)
property_label = wid.HTML(
f"<p style='{head_style}'>Circuit Properties</p>",
layout=wid.Layout(margin="0px 0px 10px 0px"),
)
@deprecate_func(
since="0.25.0",
additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.",
)
def properties_widget(circuit: QuantumCircuit) -> wid.VBox:
"""Create a HTML table widget with header for a given quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
"""
properties = wid.VBox(
children=[property_label, circuit_data_table(circuit)],
layout=wid.Layout(width="40%", height="auto"),
)
return properties
@_optionals.HAS_PYGMENTS.require_in_call
@deprecate_func(
since="0.25.0",
additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.",
)
def qasm_widget(circuit: QuantumCircuit) -> wid.VBox:
"""Generate a QASM widget with header for a quantum circuit.
Args:
circuit: Input quantum circuit.
Returns:
Output widget.
"""
import pygments
from pygments.formatters import HtmlFormatter
from qiskit.qasm.pygments import QasmHTMLStyle, OpenQASMLexer
qasm_code = circuit.qasm()
code = pygments.highlight(qasm_code, OpenQASMLexer(), HtmlFormatter())
html_style = HtmlFormatter(style=QasmHTMLStyle).get_style_defs(".highlight")
code_style = (
"""
<style>
.highlight
{
font-family: monospace;
font-size: 14px;
line-height: 1.7em;
}
.highlight .err { color: #000000; background-color: #FFFFFF }
%s
</style>
"""
% html_style
)
out = wid.HTML(
code_style + code,
layout=wid.Layout(max_height="500px", height="auto", overflow="scroll scroll"),
)
out_label = wid.HTML(
f"<p style='{head_style}'>OpenQASM</p>",
layout=wid.Layout(margin="0px 0px 10px 0px"),
)
qasm = wid.VBox(
children=[out_label, out],
layout=wid.Layout(
height="auto", max_height="500px", width="60%", margin="0px 0px 0px 20px"
),
)
qasm._code_length = len(qasm_code.split("\n"))
return qasm
@deprecate_func(
since="0.25.0",
additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.",
)
def circuit_diagram_widget() -> wid.Box:
"""Create a circuit diagram widget.
Returns:
Output widget.
"""
# The max circuit height corresponds to a 20Q circuit with flat
# classical register.
top_out = wid.Output(
layout=wid.Layout(
width="100%",
height="auto",
max_height="1000px",
overflow="hidden scroll",
)
)
top = wid.Box(children=[top_out], layout=wid.Layout(width="100%", height="auto"))
return top
@deprecate_func(
since="0.25.0",
additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.",
)
def circuit_library_widget(circuit: QuantumCircuit) -> None:
"""Create a circuit library widget.
Args:
circuit: Input quantum circuit.
"""
qasm_wid = qasm_widget(circuit)
sep_length = str(min(20 * qasm_wid._code_length, 495))
# The separator widget
sep = wid.HTML(
f"<div style='border-left: 3px solid #212121;height: {sep_length}px;'></div>",
layout=wid.Layout(height="auto", max_height="495px", margin="40px 0px 0px 20px"),
)
bottom = wid.HBox(
children=[properties_widget(circuit), sep, qasm_widget(circuit)],
layout=wid.Layout(max_height="550px", height="auto"),
)
top = circuit_diagram_widget()
with top.children[0]:
display(circuit.decompose().draw(output="mpl"))
display(wid.VBox(children=[top, bottom], layout=wid.Layout(width="100%", height="auto")))
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_ibm_runtime import IBMRuntimeService
# Option 1 - Save default accounts per channel
IBMRuntimeService.save_account(channel="ibm_quantum", token="<IBM Quantum API token>")
IBMRuntimeService.save_account(
channel="ibm_cloud",
token="<IBM Cloud API key>",
instance="<CRN> or <Service Instance Name>",
)
# Option 2 - Save account by name
IBMRuntimeService.save_account(name="backup-account", channel="ibm_quantum", token="<IBM Quantum API token>")
IBMRuntimeService.saved_accounts()
IBMRuntimeService.delete_account(name="backup-account")
# Option 1 - Based on saved default accounts per channel
service = IBMRuntimeService(channel="ibm_quantum")
service = IBMRuntimeService(channel="ibm_cloud")
# Option 2 - Based on saved named account
service = IBMRuntimeService(name="backup-account")
# Option 3 - By passing account credentials
service = IBMRuntimeService(channel="ibm_quantum", token="<IBM Quantum API token>")
service = IBMRuntimeService(channel="ibm_cloud", token="<IBM Cloud API key>", instance="<CRN> or <Service Instance Name>")
# Option 4 - By reading from environment variables
service = IBMRuntimeService() # requires environment configuration via QISKIT_IBM_TOKEN, QISKIT_IBM_URL, QISKIT_IBM_INSTANCE
service.pprint_programs()
service.programs()
program = service.program("sampler")
print(program)
service.backends()
service.backends(operational=True, min_num_qubits=64)
service.least_busy()
from qiskit import QuantumCircuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
bell.draw()
# Specify the program inputs here.
program_inputs = {
"circuits": bell,
"circuit_indices": [0],
}
job = service.run(
program_id="sampler",
inputs=program_inputs,
)
# Printing the job ID in case we need to retrieve it later.
print(f"Job ID: {job.job_id}")
# Get the job result - this is blocking and control may not return immediately.
result = job.result()
print(result)
# see which backend the job was executed on
print(job.backend)
backend = service.backend("ibmq_qasm_simulator")
backend
backend.name
backend.num_qubits
backend.max_circuits
backend.basis_gates
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# here is a list holding all even numbers between 10 and 20
L = [10, 12, 14, 16, 18, 20]
# let's print the list
print(L)
# let's print each element by using its index but in reverse order
print(L[5],L[4],L[3],L[2],L[1],L[0])
# let's print the length (size) of list
print(len(L))
# let's print each element and its index in the list
# we use a for-loop, and the number of iteration is determined by the length of the list
# everthing is automatical :-)
L = [10, 12, 14, 16, 18, 20]
for i in range(len(L)):
print(L[i],"is the element in our list with the index",i)
# let's replace each number in the above list with its double value
# L = [10, 12, 14, 16, 18, 20]
# let's print the list before doubling operation
print("the list before doubling operation is",L)
for i in range(len(L)):
current_element=L[i] # get the value of the i-th element
L[i] = 2 * current_element # update the value of the i-th element
# let's shorten the code as
#L[i] = 2 * L[i]
# or
#L[i] *= 2
# let's print the list after doubling operation
print("the list after doubling operation is",L)
# after each execution of this cell, the latest values will be doubled
# so the values in the list will be exponentially increased
# let's define two lists
L1 = [1,2,3,4]
L2 = [-5,-6,-7,-8]
# two lists can be concatenated
# the result is a new list
print("the concatenation of L1 and L2 is",L1+L2)
# the order of terms is important
print("the concatenation of L2 and L1 is",L2+L1) # this is a different list than L1+L2
# we can add a new element to a list, which increases its length/size by 1
L = [10, 12, 14, 16, 18, 20]
print(L,"the current length is",len(L))
# we add two values by showing two different methods
# L.append(value) directly adds the value as a new element to the list
L.append(-4)
# we can also use concatenation operator +
L = L + [-8] # here [-8] is a list having a single element
print(L,"the new length is",len(L))
# a list can be multiplied with an integer
L = [1,2]
# we can consider the multiplication of L by an integer as a repeated summation (concatenation) of L by itself
# L * 1 is the list itself
# L * 2 is L + L (the concatenation of L with itself)
# L * 3 is L + L + L (the concatenation of L with itself twice)
# L * m is L + ... + L (the concatenation of L with itself m-1 times)
# L * 0 is the empty list
# L * i is the same as i * L
# let's print the different cases
for i in range(6):
print(i,"* L is",i*L)
# this operation can be useful when initializing a list with the same value(s)
# let's create a list of prime numbers less than 100
# here is a function that determines whether a given number is prime or not
def prime(number):
if number < 2: return False
if number == 2: return True
if number % 2 == 0: return False
for i in range(3,number,2):
if number % i == 0: return False
return True
# end of a function
# let's start with an empty list
L=[]
# what can the length of this list be?
print("my initial length is",len(L))
for i in range(2,100):
if prime(i):
L.append(i)
# alternative methods:
#L = L + [i]
#L += [i]
# print the final list
print(L)
print("my final length is",len(L))
# let's define the list with S(0)
L = [0]
# let's iteratively define n and S
# initial values
n = 0
S = 0
# the number of iterations
N = 20
while n <= N: # we iterate all values from 1 to 20
n = n + 1
S = S + n
L.append(S)
# print the final list
print(L)
#
# your solution is here
# the first and second elements are 1 and 1
F = [1,1]
for i in range(2,30):
F.append(F[i-1] + F[i-2])
# print the final list
print(F)
# the following list stores certain information about Asja
# name, surname, age, profession, height, weight, partner(s) if any, kid(s) if any, the creation date of list
ASJA = ['Asja','Sarkane',34,'musician',180,65.5,[],['Eleni','Fyodor'],"October 24, 2018"]
print(ASJA)
# Remark that an element of a list can be another list as well.
#
# your solution is here
#
# define an empty list
N = []
for i in range(11):
N.append([ i , i*i , i*i*i , i*i + i*i*i ]) # a list having four elements is added to the list N
# Alternatively:
#N.append([i , i**2 , i**3 , i**2 + i**3]) # ** is the exponent operator
#N = N + [ [i , i*i , i*i*i , i*i + i*i*i] ] # Why using double brackets?
#N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brackets?
# In the last two alternative solutions, you may try with a single bracket,
# and then see why double brackets are needed for the exact answer.
# print the final list
print(N)
# let's print the list N element by element
for i in range(len(N)):
print(N[i])
# let's print the list N element by element by using an alternative method
for el in N: # el will iteratively takes the values of elements in N
print(el)
# let's define a dictionary pairing a person with her/his age
ages = {
'Asja':32,
'Balvis':28,
'Fyodor':43
}
# let print all keys
for person in ages:
print(person)
# let's print the values
for person in ages:
print(ages[person])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
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())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ggridin/QiskitTests
|
ggridin
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer
from QuantumPlatform import QuantumPlatform
# Set up the program
def get_quantum_spy_circuit():
alice = QuantumRegister(1, name='alice')
fiber = QuantumRegister(1, name='fiber')
bob = QuantumRegister(1, name='bob')
alice_had = ClassicalRegister(1, name='ahad')
alice_val = ClassicalRegister(1, name='aval')
fiber_val = ClassicalRegister(1, name='fval')
bob_had = ClassicalRegister(1, name='bhad')
bob_val = ClassicalRegister(1, name='bval')
qc = QuantumCircuit(alice, fiber, bob, alice_had, alice_val, fiber_val, bob_had, bob_val)
# Use Alice's QPU to generate two random bits
qc.reset(alice) # write the value 0
qc.h(alice)
qc.measure(alice, alice_had)
qc.reset(alice) # write the value 0
qc.h(alice)
qc.measure(alice, alice_val)
# Prepare Alice's qubit
qc.reset(alice) # write the value 0
qc.x(alice).c_if(alice_val, 1)
qc.h(alice).c_if(alice_had, 1)
# Send the qubit!
qc.swap(alice, fiber)
# Activate the spy
spy_is_present = True
if spy_is_present:
qc.barrier()
spy_had = True
if spy_had:
qc.h(fiber)
qc.measure(fiber, fiber_val)
qc.reset(fiber)
qc.x(fiber).c_if(fiber_val, 1)
if spy_had:
qc.h(fiber)
qc.barrier()
# Use Bob's QPU to generate a random bit
qc.reset(bob)
qc.h(bob)
qc.measure(bob, bob_had)
# Receive the qubit!
qc.swap(fiber, bob)
qc.h(bob).c_if(bob_had, 1)
qc.measure(bob, bob_val)
return qc
def main():
qc = get_quantum_spy_circuit()
platform_backend = QuantumPlatform(Aer, 'statevector_simulator')
job = platform_backend.schedule_job(qc)
result = job.result()
# Now Alice emails Bob to tell
# him her had setting and value.
# If the had setting matches and the
# value does not, there's a spy!
counts = result.get_counts(qc)
print('counts:',counts)
caught = False
for key,val in counts.items():
ahad,aval,f,bhad,bval = (int(x) for x in key.split(' '))
if ahad == bhad:
if aval != bval:
print('Caught a spy!')
caught = True
if not caught:
print('No spies detected.')
outputstate = result.get_statevector(qc, decimals=3)
print(outputstate)
# qc.draw() # draw the circuit
main()
|
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/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.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction
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_T^1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_T^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 = 3.5
# map strike price from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price = (
(strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price
basket_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 = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits
objective_index = u.num_qubits
basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar)
basket_option.append(u, qr_state)
basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux])
basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas])
print(basket_option.draw())
print("objective qubit index", objective_index)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = np.linspace(sum(low), sum(high))
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
exact_value = np.dot(
u.probabilities[sum_values >= strike_price],
sum_values[sum_values >= strike_price] - strike_price,
)
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(basket_option, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
basket_option_measure = basket_option.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(basket_option_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 = (
basket_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=basket_option,
objective_qubits=[objective_index],
post_processing=basket_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=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/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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.
"""A module for visualizing device coupling maps."""
import math
from typing import List
import numpy as np
from qiskit.exceptions import MissingOptionalLibraryError, QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError
from qiskit.visualization.utils import matplotlib_close_if_inline
def plot_gate_map(
backend,
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
qubit_coordinates=None,
):
"""Plots the gate map of a device.
Args:
backend (BaseBackend): The backend instance that will be used to plot the device
gate map.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
QiskitError: if tried to pass a simulator, or if the backend is None,
but one of num_qubits, mpl_data, or cmap is None.
MissingOptionalLibraryError: if matplotlib not installed.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_gate_map
%matplotlib inline
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q')
backend = accountProvider.get_backend('ibmq_vigo')
plot_gate_map(backend)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_gate_map",
pip_install="pip install matplotlib",
)
if isinstance(backend, BackendV2):
pass
elif backend.configuration().simulator:
raise QiskitError("Requires a device backend, not simulator.")
qubit_coordinates_map = {}
qubit_coordinates_map[1] = [[0, 0]]
qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]]
qubit_coordinates_map[20] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 0],
[3, 1],
[3, 2],
[3, 3],
[3, 4],
]
qubit_coordinates_map[15] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 7],
[1, 6],
[1, 5],
[1, 4],
[1, 3],
[1, 2],
[1, 1],
[1, 0],
]
qubit_coordinates_map[16] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
]
qubit_coordinates_map[27] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
[3, 6],
[0, 7],
[1, 7],
[3, 7],
[4, 7],
[1, 8],
[3, 8],
[1, 9],
[2, 9],
[3, 9],
[3, 10],
]
qubit_coordinates_map[28] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
]
qubit_coordinates_map[53] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[5, 2],
[5, 6],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[7, 0],
[7, 4],
[7, 8],
[8, 0],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[9, 2],
[9, 6],
]
qubit_coordinates_map[65] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[0, 7],
[0, 8],
[0, 9],
[1, 0],
[1, 4],
[1, 8],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[2, 9],
[2, 10],
[3, 2],
[3, 6],
[3, 10],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[4, 9],
[4, 10],
[5, 0],
[5, 4],
[5, 8],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[6, 9],
[6, 10],
[7, 2],
[7, 6],
[7, 10],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[8, 9],
[8, 10],
]
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
coupling_map = backend.plot_coupling_map
else:
config = backend.configuration()
num_qubits = config.n_qubits
coupling_map = config.coupling_map
# don't reference dictionary if provided as a parameter
if qubit_coordinates is None:
qubit_coordinates = qubit_coordinates_map.get(num_qubits)
# try to adjust num_qubits to match the next highest hardcoded grid size
if qubit_coordinates is None:
if any([num_qubits < key for key in qubit_coordinates_map.keys()]):
num_qubits_roundup = max(qubit_coordinates_map.keys())
for key in qubit_coordinates_map.keys():
if key < num_qubits_roundup and key > num_qubits:
num_qubits_roundup = key
qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup)
return plot_coupling_map(
num_qubits,
qubit_coordinates,
coupling_map,
figsize,
plot_directed,
label_qubits,
qubit_size,
line_width,
font_size,
qubit_color,
qubit_labels,
line_color,
font_color,
ax,
filename,
)
def plot_coupling_map(
num_qubits: int,
qubit_coordinates: List[List[int]],
coupling_map: List[List[int]],
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
):
"""Plots an arbitrary coupling map of qubits (embedded in a plane).
Args:
num_qubits (int): The number of qubits defined and plotted.
qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested
list being the planar coordinates in a 0-based square grid where each qubit is located.
coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested
list being the qubit numbers of the bonds to be plotted.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
MissingOptionalLibraryError: if matplotlib not installed.
QiskitError: If length of qubit labels does not match number of qubits.
Example:
.. jupyter-execute::
from qiskit.visualization import plot_coupling_map
%matplotlib inline
num_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
plot_coupling_map(num_qubits, coupling_map, qubit_coordinates)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_coupling_map",
pip_install="pip install matplotlib",
)
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
input_axes = False
if ax:
input_axes = True
if font_size is None:
font_size = 12
if qubit_size is None:
qubit_size = 24
if num_qubits > 20:
qubit_size = 28
font_size = 10
if qubit_labels is None:
qubit_labels = list(range(num_qubits))
else:
if len(qubit_labels) != num_qubits:
raise QiskitError("Length of qubit labels does not equal number of qubits.")
if qubit_coordinates is not None:
grid_data = qubit_coordinates
else:
if not input_axes:
fig, ax = plt.subplots(figsize=(5, 5))
ax.axis("off")
if filename:
fig.savefig(filename)
return fig
x_max = max(d[1] for d in grid_data)
y_max = max(d[0] for d in grid_data)
max_dim = max(x_max, y_max)
if figsize is None:
if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33):
figsize = (5, 5)
else:
figsize = (9, 3)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
ax.axis("off")
# set coloring
if qubit_color is None:
qubit_color = ["#648fff"] * num_qubits
if line_color is None:
line_color = ["#648fff"] * len(coupling_map) if coupling_map else []
# Add lines for couplings
if num_qubits != 1:
for ind, edge in enumerate(coupling_map):
is_symmetric = False
if edge[::-1] in coupling_map:
is_symmetric = True
y_start = grid_data[edge[0]][0]
x_start = grid_data[edge[0]][1]
y_end = grid_data[edge[1]][0]
x_end = grid_data[edge[1]][1]
if is_symmetric:
if y_start == y_end:
x_end = (x_end - x_start) / 2 + x_start
elif x_start == x_end:
y_end = (y_end - y_start) / 2 + y_start
else:
x_end = (x_end - x_start) / 2 + x_start
y_end = (y_end - y_start) / 2 + y_start
ax.add_artist(
plt.Line2D(
[x_start, x_end],
[-y_start, -y_end],
color=line_color[ind],
linewidth=line_width,
zorder=0,
)
)
if plot_directed:
dx = x_end - x_start
dy = y_end - y_start
if is_symmetric:
x_arrow = x_start + dx * 0.95
y_arrow = -y_start - dy * 0.95
dx_arrow = dx * 0.01
dy_arrow = -dy * 0.01
head_width = 0.15
else:
x_arrow = x_start + dx * 0.5
y_arrow = -y_start - dy * 0.5
dx_arrow = dx * 0.2
dy_arrow = -dy * 0.2
head_width = 0.2
ax.add_patch(
mpatches.FancyArrow(
x_arrow,
y_arrow,
dx_arrow,
dy_arrow,
head_width=head_width,
length_includes_head=True,
edgecolor=None,
linewidth=0,
facecolor=line_color[ind],
zorder=1,
)
)
# Add circles for qubits
for var, idx in enumerate(grid_data):
# add check if num_qubits had been rounded up
if var >= num_qubits:
break
_idx = [idx[1], -idx[0]]
ax.add_artist(
mpatches.Ellipse(
_idx,
qubit_size / 48,
qubit_size / 48, # This is here so that the changes
color=qubit_color[var],
zorder=1,
)
) # to how qubits are plotted does
if label_qubits: # not affect qubit size kwarg.
ax.text(
*_idx,
s=qubit_labels[var],
horizontalalignment="center",
verticalalignment="center",
color=font_color,
size=font_size,
weight="bold",
)
ax.set_xlim([-1, x_max + 1])
ax.set_ylim([-(y_max + 1), 1])
ax.set_aspect("equal")
if not input_axes:
matplotlib_close_if_inline(fig)
if filename:
fig.savefig(filename)
return fig
return None
def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None):
"""Plot the layout of a circuit transpiled for a given target backend.
Args:
circuit (QuantumCircuit): Input quantum circuit.
backend (BaseBackend): Target backend.
view (str): Layout view: either 'virtual' or 'physical'.
Returns:
Figure: A matplotlib figure showing layout.
Raises:
QiskitError: Invalid view type given.
VisualizationError: Circuit has no layout attribute.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
import numpy as np
from qiskit import QuantumCircuit, IBMQ, transpile
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
"""
if circuit._layout is None:
raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.")
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
else:
num_qubits = backend.configuration().n_qubits
qubits = []
qubit_labels = [None] * num_qubits
bit_locations = {
bit: {"register": register, "index": index}
for register in circuit._layout.get_registers()
for index, bit in enumerate(register)
}
for index, qubit in enumerate(circuit._layout.get_virtual_bits()):
if qubit not in bit_locations:
bit_locations[qubit] = {"register": None, "index": index}
if view == "virtual":
for key, val in circuit._layout.get_virtual_bits().items():
bit_register = bit_locations[key]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(val)
qubit_labels[val] = bit_locations[key]["index"]
elif view == "physical":
for key, val in circuit._layout.get_physical_bits().items():
bit_register = bit_locations[val]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(key)
qubit_labels[key] = key
else:
raise VisualizationError("Layout view must be 'virtual' or 'physical'.")
qcolors = ["#648fff"] * num_qubits
for k in qubits:
qcolors[k] = "k"
if isinstance(backend, BackendV2):
cmap = backend.plot_coupling_map
else:
cmap = backend.configuration().coupling_map
lcolors = ["#648fff"] * len(cmap)
for idx, edge in enumerate(cmap):
if edge[0] in qubits and edge[1] in qubits:
lcolors[idx] = "k"
fig = plot_gate_map(
backend,
qubit_color=qcolors,
qubit_labels=qubit_labels,
line_color=lcolors,
qubit_coordinates=qubit_coordinates,
)
return fig
def plot_error_map(backend, figsize=(12, 9), show_title=True):
"""Plots the error map of a given backend.
Args:
backend (IBMQBackend): Given backend.
figsize (tuple): Figure size in inches.
show_title (bool): Show the title or not.
Returns:
Figure: A matplotlib figure showing error map.
Raises:
VisualizationError: Input is not IBMQ backend.
VisualizationError: The backend does not provide gate errors for the 'sx' gate.
MissingOptionalLibraryError: If seaborn is not installed
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_error_map
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
plot_error_map(backend)
"""
try:
import seaborn as sns
except ImportError as ex:
raise MissingOptionalLibraryError(
libname="seaborn",
name="plot_error_map",
pip_install="pip install seaborn",
) from ex
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_error_map",
pip_install="pip install matplotlib",
)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import gridspec, ticker
color_map = sns.cubehelix_palette(reverse=True, as_cmap=True)
props = backend.properties().to_dict()
config = backend.configuration().to_dict()
num_qubits = config["n_qubits"]
# sx error rates
single_gate_errors = [0] * num_qubits
for gate in props["gates"]:
if gate["gate"] == "sx":
_qubit = gate["qubits"][0]
for param in gate["parameters"]:
if param["name"] == "gate_error":
single_gate_errors[_qubit] = param["value"]
break
else:
raise VisualizationError(
f"Backend '{backend}' did not supply an error for the 'sx' gate."
)
# Convert to percent
single_gate_errors = 100 * np.asarray(single_gate_errors)
avg_1q_err = np.mean(single_gate_errors)
single_norm = matplotlib.colors.Normalize(
vmin=min(single_gate_errors), vmax=max(single_gate_errors)
)
q_colors = [color_map(single_norm(err)) for err in single_gate_errors]
cmap = config["coupling_map"]
directed = False
line_colors = []
if cmap:
directed = False
if num_qubits < 20:
for edge in cmap:
if [edge[1], edge[0]] not in cmap:
directed = True
break
cx_errors = []
for line in cmap:
for item in props["gates"]:
if item["qubits"] == line:
cx_errors.append(item["parameters"][0]["value"])
break
else:
continue
# Convert to percent
cx_errors = 100 * np.asarray(cx_errors)
avg_cx_err = np.mean(cx_errors)
cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors))
line_colors = [color_map(cx_norm(err)) for err in cx_errors]
# Measurement errors
read_err = []
for qubit in range(num_qubits):
for item in props["qubits"][qubit]:
if item["name"] == "readout_error":
read_err.append(item["value"])
read_err = 100 * np.asarray(read_err)
avg_read_err = np.mean(read_err)
max_read_err = np.max(read_err)
fig = plt.figure(figsize=figsize)
gridspec.GridSpec(nrows=2, ncols=3)
grid_spec = gridspec.GridSpec(
12,
12,
height_ratios=[1] * 11 + [0.5],
width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2],
)
left_ax = plt.subplot(grid_spec[2:10, :1])
main_ax = plt.subplot(grid_spec[:11, 1:11])
right_ax = plt.subplot(grid_spec[2:10, 11:])
bleft_ax = plt.subplot(grid_spec[-1, :5])
if cmap:
bright_ax = plt.subplot(grid_spec[-1, 7:])
qubit_size = 28
if num_qubits <= 5:
qubit_size = 20
plot_gate_map(
backend,
qubit_color=q_colors,
line_color=line_colors,
qubit_size=qubit_size,
line_width=5,
plot_directed=directed,
ax=main_ax,
)
main_ax.axis("off")
main_ax.set_aspect(1)
if cmap:
single_cb = matplotlib.colorbar.ColorbarBase(
bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
single_cb.locator = tick_locator
single_cb.update_ticks()
single_cb.update_ticks()
bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]")
if cmap is None:
bleft_ax.axis("off")
bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}")
if cmap:
cx_cb = matplotlib.colorbar.ColorbarBase(
bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
cx_cb.locator = tick_locator
cx_cb.update_ticks()
bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]")
if num_qubits < 10:
num_left = num_qubits
num_right = 0
else:
num_left = math.ceil(num_qubits / 2)
num_right = num_qubits - num_left
left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA")
left_ax.axvline(avg_read_err, linestyle="--", color="#212121")
left_ax.set_yticks(range(num_left))
left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12)
left_ax.invert_yaxis()
left_ax.set_title("Readout Error (%)", fontsize=12)
for spine in left_ax.spines.values():
spine.set_visible(False)
if num_right:
right_ax.barh(
range(num_left, num_qubits),
read_err[num_left:],
align="center",
color="#DDBBBA",
)
right_ax.axvline(avg_read_err, linestyle="--", color="#212121")
right_ax.set_yticks(range(num_left, num_qubits))
right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
right_ax.set_yticklabels(
[str(kk) for kk in range(num_left, num_qubits)], fontsize=12
)
right_ax.invert_yaxis()
right_ax.invert_xaxis()
right_ax.yaxis.set_label_position("right")
right_ax.yaxis.tick_right()
right_ax.set_title("Readout Error (%)", fontsize=12)
else:
right_ax.axis("off")
for spine in right_ax.spines.values():
spine.set_visible(False)
if show_title:
fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9)
matplotlib_close_if_inline(fig)
return fig
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
from qiskit.primitives import Estimator
estimator = Estimator()
import numpy as np
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
# we will iterate over these different optimizers
optimizers = [COBYLA(maxiter=80), L_BFGS_B(maxiter=60), SLSQP(maxiter=60)]
converge_counts = np.empty([len(optimizers)], dtype=object)
converge_vals = np.empty([len(optimizers)], dtype=object)
for i, optimizer in enumerate(optimizers):
print("\rOptimizer: {} ".format(type(optimizer).__name__), end="")
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(estimator, ansatz, optimizer, callback=store_intermediate_result)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
converge_counts[i] = np.asarray(counts)
converge_vals[i] = np.asarray(values)
print("\rOptimization complete ");
import pylab
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(converge_counts[i], converge_vals[i], label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence for various optimizers")
pylab.legend(loc="upper right");
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
for i, optimizer in enumerate(optimizers):
pylab.plot(
converge_counts[i],
abs(ref_value - converge_vals[i]),
label=type(optimizer).__name__,
)
pylab.xlabel("Eval count")
pylab.ylabel("Energy difference from solution reference value")
pylab.title("Energy convergence for various optimizers")
pylab.yscale("log")
pylab.legend(loc="upper right");
from qiskit.algorithms.gradients import FiniteDiffEstimatorGradient
estimator = Estimator()
gradient = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
algorithm_globals.random_seed = 50
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer = SLSQP(maxiter=100)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
vqe = VQE(
estimator, ansatz, optimizer, callback=store_intermediate_result, gradient=gradient
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"Value using Gradient: {result.eigenvalue.real:.5f}")
pylab.rcParams["figure.figsize"] = (12, 8)
pylab.plot(counts, values, label=type(optimizer).__name__)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Energy convergence using Gradient")
pylab.legend(loc="upper right");
print(result)
cost_function_evals = result.cost_function_evals
initial_pt = result.optimal_point
estimator1 = Estimator()
gradient1 = FiniteDiffEstimatorGradient(estimator, epsilon=0.01)
ansatz1 = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
optimizer1 = SLSQP(maxiter=1000)
vqe1 = VQE(
estimator1, ansatz1, optimizer1, gradient=gradient1, initial_point=initial_pt
)
result1 = vqe1.compute_minimum_eigenvalue(operator=H2_op)
print(result1)
cost_function_evals1 = result1.cost_function_evals
print()
print(
f"cost_function_evals is {cost_function_evals1} with initial point versus {cost_function_evals} without it."
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
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)
dj_circuit.draw()
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(balanced_oracle)
dj_circuit.draw()
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(balanced_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)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/farhad-abdi/InSilicoQ
|
farhad-abdi
|
# Quantum Kernel Machine Learning Functions
import numpy as np
## Utilities
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from typing import Optional, Callable, List, Union
from functools import reduce
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.visualization import *
# Qiskit imports
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap, PauliFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
#Qiskit Machine Learning imports
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import QuantumKernel
from qiskit_machine_learning.datasets import ad_hoc_data
# seed for ramdomization, to keep outputs consistent
seed = 123456
#Quantum Computing Backend used in Quantum Kernels
qcomp_backend = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024,
seed_simulator=seed, seed_transpiler=seed)
"""
The following functions are implementations of ref[2] and the corresponding equations are numberd according to the paper.
"""
def data_map_eq8(x: np.ndarray) -> float:
"""
Define a function map from R^n to R.
Args:
x: data
Returns:
float: the mapped value
"""
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*(m * n), x)
return coeff
def data_map_eq9(x: np.ndarray) -> float:
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: (np.pi/2)*(m * n), 1 - x)
return coeff
def data_map_eq10(x: np.ndarray) -> float:
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*np.exp(((m - n)*(m - n))/8), x)
return coeff
def data_map_eq11(x: np.ndarray) -> float:
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: (np.pi/3)*(m * n), 1/(np.cos(x)))
return coeff
def data_map_eq12(x: np.ndarray) -> float:
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*(m * n), np.cos(x))
return coeff
#Define Quantum Kernels Functions
def qkern_default():
qfm_default = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full')
return QuantumKernel(feature_map=qfm_default, quantum_instance=qcomp_backend)
def qkern_eq8():
qfm_eq8 = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full', data_map_func=data_map_eq8)
return QuantumKernel(feature_map=qfm_eq8, quantum_instance=qcomp_backend)
def qkern_eq9():
qfm_eq9 = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full', data_map_func=data_map_eq9)
return QuantumKernel(feature_map=qfm_eq9, quantum_instance=qcomp_backend)
def qkern_eq10():
qfm_eq10 = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full', data_map_func=data_map_eq10)
return QuantumKernel(feature_map=qfm_eq10, quantum_instance=qcomp_backend)
def qkern_eq11():
qfm_eq11 = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full', data_map_func=data_map_eq11)
return QuantumKernel(feature_map=qfm_eq11, quantum_instance=qcomp_backend)
def qkern_eq12():
qfm_eq12 = PauliFeatureMap(feature_dimension=2,
paulis = ['ZI','IZ','ZZ'],
reps=2, entanglement='full', data_map_func=data_map_eq12)
return QuantumKernel(feature_map=qfm_eq12, quantum_instance=qcomp_backend)
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
from qiskit.quantum_info import DensityMatrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
from qCircuit import createInputCircuit, createModelCircuit, createNoisyModelCircuit
from qLipschitz import QLipschitz
from qDistance import d, D
import warnings
warnings.filterwarnings('ignore')
X_train, Y_train = datasets.make_circles(n_samples=500, noise=0.09, factor=0.4)
X_test, Y_test = datasets.make_circles(n_samples=200, 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)
X, Y = datasets.load_iris(return_X_y=True)
X_train_0 = X[0:30]
X_train_1 = X[50:80]
X_train_iris = np.vstack((X_train_0, X_train_1))
Y_train_0 = Y[0:30]
Y_train_1 = Y[50:80]
Y_train_iris = np.vstack((Y_train_0, Y_train_1)).flatten()
X, Y = datasets.load_iris(return_X_y=True)
X_test_0 = X[30:50]
X_test_1 = X[80:100]
X_test_iris = np.vstack((X_test_0, X_test_1))
Y_test_0 = Y[30:50]
Y_test_1 = Y[80:100]
Y_test_iris = np.vstack((Y_test_0, Y_test_1)).flatten()
X_train_iris = (X_train_iris - X_train_iris.min(axis=0)) / (X_train_iris.max(axis=0) - X_train_iris.min(axis=0))
X_test_iris = (X_test_iris - X_test_iris.min(axis=0)) / (X_test_iris.max(axis=0) - X_test_iris.min(axis=0))
import qiskit
from qiskit import Aer, execute
qasm_backend = Aer.get_backend('qasm_simulator')
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_iris = [
[[-3.42142600e-02, -5.45047534e-03, 8.11905347e-01],
[-1.52484152e+00, 1.49884676e+00, -1.25408626e-02],
[-1.89515860e-03, 1.35760410e-02, 8.22999582e-03],
[ 1.39102114e+00, 4.19729865e-01, 1.60000380e-04]],
[[ 7.88431068e-01, -8.86177264e-01, 1.33830291e-02],
[-3.71228143e-03, -1.12994101e-02, -1.27897783e-02],
[ 9.45954683e-03, -3.34659883e-03, 1.17217829e-02],
[ 1.98256181e-02, -1.07358054e-02, 7.53621360e-03]]
]
# Test 1: createModelCircuit
createModelCircuit(params).draw(output='mpl')
def predict(model, data):
qubits_num = len(data)
input_circuit = createInputCircuit(data)
qcircuit = input_circuit.compose(model)
# the measurement
qcircuit.measure(list(range(qubits_num)), list(range(qubits_num)))
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = 0
for i in range(2 ** (qubits_num - 1)):
comb = str(bin(i + 2 ** (qubits_num - 1))[2:])
p1 += counts.get(comb, 0)
p1 /= shots
if p1 > 0.5:
return 1
else:
return 0
def accuracy(model, datas, labels):
predictions = [ predict(model, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
def evaluate(model, X_test, Y_test):
acc = accuracy(model, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
# Test 2: evaluate noiseless model
test2_circuit = createModelCircuit(params_iris)
evaluate(test2_circuit, X_train_iris, Y_train_iris)
evaluate(test2_circuit, X_test_iris, Y_test_iris)
# Test 3: create noisy model circuit - circle
test3_p = 0.001
test3_circuit = createNoisyModelCircuit(params, test3_p, 'phase_flip')
test3_circuit.draw(output='mpl')
# Test 4: evaluate noisy model - circle
test4_p = 0.001
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
test4_circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, test4_p, 'bit_flip'),
createNoisyModelCircuit(params, test4_p, 'phase_flip'),
createNoisyModelCircuit(params, test4_p, 'depolarizing')
]
for i, model_type in enumerate(models_type):
print(f'Evaluate <{model_type}>: ')
evaluate(test4_circuits[i], X_test2, Y_test)
print()
# Test 5: calculate lipschitz constant
print('Classifier for centric circle: ')
test5_1_circuit = createModelCircuit(params)
test5_1_qlipschitz = QLipschitz(test5_1_circuit, [0, 1])
print(test5_1_qlipschitz.constant)
print('\nClassifier for Iris: ')
test5_2_circuit = createModelCircuit(params_iris)
test5_2_qlipschitz = QLipschitz(test5_2_circuit, [0, 1])
print(test5_2_qlipschitz.constant)
# Test 6-1: calculate lipschitz constant in noisy model
test6_p = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for centric circle: ')
for p in test6_p:
test6_1_circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, p, 'bit_flip'),
createNoisyModelCircuit(params, p, 'phase_flip'),
createNoisyModelCircuit(params, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
test6_1_qlipschitz = QLipschitz(test6_1_circuits[i], [0, 1])
print(f'{model_type} model: {test6_1_qlipschitz.constant[0]}')
print()
# Test 6-2: calculate lipschitz constant in noisy model
test6_p = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for Iris: ')
for p in test6_p:
test6_2_circuits = [
createModelCircuit(params_iris),
createNoisyModelCircuit(params_iris, p, 'bit_flip'),
createNoisyModelCircuit(params_iris, p, 'phase_flip'),
createNoisyModelCircuit(params_iris, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
test6_2_qlipschitz = QLipschitz(test6_2_circuits[i], [0, 1])
print(f'{model_type} model: {test6_2_qlipschitz.constant[0]}')
print()
# Test 7-1: find proper epsilon - circle
import random
# D(rou, sigma) <= epsilon
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train2) - 1)
b = random.randint(0, len(X_train2) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]]))
distances.append(D(rou, sigma))
print('find proper epsilon - centric circle')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 7-2: find proper epsilon - iris
# D(rou, sigma) <= epsilon
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train_iris) - 1)
b = random.randint(0, len(X_train_iris) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]]))
distances.append(D(rou, sigma))
print('find proper epsilon - centric iris')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 8-1: find proper delta - circle
test8_1_circuit = createModelCircuit(params)
test8_1_qlipschitz = QLipschitz(test8_1_circuit, [0, 1])
test8_1_A = test8_1_qlipschitz.A
# d(A(rou), A(sigma)) <= delta
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train2) - 1)
b = random.randint(0, len(X_train2) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]]))
distances.append(d(test8_1_A, rou, sigma))
print('find proper delta - circle')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 8-2: find proper delta - circle
test8_2_circuit = createModelCircuit(params_iris)
test8_2_qlipschitz = QLipschitz(test8_2_circuit, [0, 1])
test8_2_A = test8_2_qlipschitz.A
# d(A(rou), A(sigma)) <= delta
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train_iris) - 1)
b = random.randint(0, len(X_train_iris) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]]))
distances.append(d(test8_2_A, rou, sigma))
print('find proper delta - iris')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 9-1: fairness verifying - circle
test9_1_circuit = createNoisyModelCircuit(params, p=0.001, errorType='bit_flip')
test9_1_qlipschitz = QLipschitz(test9_1_circuit, [0, 1])
print(f'Lipschitz constant: {test9_1_qlipschitz.constant[0]}\n')
test9_1_fairness_params = [
# epsilon, delta
[1, 1], [0.9, 0.89], [0.6, 0.58], [0.6, 0.59]
]
for epsilon, delta in test9_1_fairness_params:
flag, kernel = test9_1_qlipschitz.fairVeriQ(epsilon, delta)
print(f'A is ({epsilon},{delta})-fair: <{flag}>')
if not flag:
print(f' - bias kernel pair is: {kernel}')
print()
# Test 9-2: fairness verifying - iris
test9_2_circuit = createNoisyModelCircuit(params_iris, p=0.001, errorType='phase_flip')
test9_2_qlipschitz = QLipschitz(test9_2_circuit, [0, 1])
print(f'Lipschitz constant: {test9_2_qlipschitz.constant[0]}\n')
test9_2_fairness_params = [
# epsilon, delta
[1, 0.99], [0.8, 0.79], [0.5, 0.3]
]
for epsilon, delta in test9_2_fairness_params:
flag, kernel = test9_1_qlipschitz.fairVeriQ(epsilon, delta)
print(f'A is ({epsilon},{delta})-fair: <{flag}>')
if not flag:
print(f' - bias kernel pair is: {kernel}')
print()
# Test 10: generate bias pair
test10_circuit = createNoisyModelCircuit(params_iris, p=0.01, errorType='depolarizing')
test10_qlipschitz = QLipschitz(test10_circuit, [0, 1])
print(f'Lipschitz constant: {test10_qlipschitz.constant[0]}\n')
flag, kernel = test10_qlipschitz.fairVeriQ(epsilon=0.9, delta=0.3)
print(f'fairness: {flag}')
assert (not flag)
test10_sigma = getDensityMatrix(createInputCircuit(X_train_iris[11]))
test10_bias_pair = test10_qlipschitz.generateBiasPair(test10_sigma, kernel, epsilon=0.9)
test10_rou_psi, test10_rou_phi = test10_bias_pair
# print(test10_bias_pair)
print(f'epsilon=0.9, delta=0.3')
print('D: ', D(test10_rou_psi, test10_rou_phi))
print('d: ', d(test10_qlipschitz.A, test10_rou_psi, test10_rou_phi))
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
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)
dj_circuit.draw()
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(balanced_oracle)
dj_circuit.draw()
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(balanced_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)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from warnings import filterwarnings
filterwarnings('ignore')
import json
import numpy.random as npr
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# mpl.rcParams["figure.dpi"] = 300
# plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
from qiskit.circuit.library import TwoLocal
from qiskit.circuit.random import random_circuit
circuits = [
TwoLocal(2, rotation_blocks=["ry", "rz"], entanglement_blocks="cz").decompose(reps=1),
random_circuit(2, 4, seed=1).decompose(reps=1),
random_circuit(2, 2, seed=0).decompose(reps=1)
]
_ = [display(c.draw("mpl")) for c in circuits]
from qiskit.quantum_info import SparsePauliOp
observables = [
SparsePauliOp("ZZ"),
SparsePauliOp("XX"),
SparsePauliOp("YY"),
]
from qiskit.primitives import Estimator, BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi as Backend
estimator = BackendEstimator(backend=Backend())
# measure expectation values of observable-0 and 1 on circuit-0 (with specified parameters)
job_0 = estimator.run(
circuits=[circuits[0]] * len(observables),
observables=observables,
parameter_values=[[*npr.random(16)]] * len(observables),
shots=2048,
)
# measure expectation values of observable-0 and 1 on circuit-1
job_1 = estimator.run(
circuits=[circuits[1]] * len(observables),
observables=observables,
shots=2048,
)
result_1 = job_1.result()
result_1
result_1 # print again for comparison on consecutive runs
from zne import zne
ZNEEstimator = zne(BackendEstimator) # Any implementation of BaseEstimator can be passed
from zne import ZNEStrategy
# from zne.noise_amplification import GlobalFoldingAmplifier, LocalFoldingAmplifier
# from zne.extrapolation import LinearExtrapolator, PolynomialExtrapolator
zne_strategy = ZNEStrategy(
noise_factors=(1, 3, 5),
# noise_amplifier = LocalFoldingAmplifier()
# extrapolator = LinearExtrapolator()
)
estimator = ZNEEstimator(
backend=Backend(),
zne_strategy=zne_strategy # !!!
)
# measure expectation values of observable-0 and 1 on circuit-0 (with specified parameters)
job_0 = estimator.run(
circuits=[circuits[0]] * len(observables),
observables=observables,
parameter_values=[[*npr.random(16)]] * len(observables),
shots=2048,
)
# measure expectation values of observable-0 and 1 on circuit-1
job_1 = estimator.run(
circuits=[circuits[1]] * len(observables),
observables=observables,
shots=2048,
)
result_1 = job_1.result()
result_1
from zne.utils.serialization import EstimatorResultEncoder
print(EstimatorResultEncoder.dumps(result_1, indent=2))
from zne import NOISE_AMPLIFIER_LIBRARY
NOISE_AMPLIFIER_LIBRARY.keys()
from zne.noise_amplification import GlobalFoldingAmplifier, LocalFoldingAmplifier
mpl.rcParams["figure.dpi"] = 300
plt.rcParams.update({"text.usetex": True, "font.family": "Computer Modern Roman"})
noise_amplifier = GlobalFoldingAmplifier()
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=1)
display(noisy_circuit.draw("mpl", plot_barriers=True))
noise_amplifier = LocalFoldingAmplifier()
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=1)
display(noisy_circuit.draw("mpl", plot_barriers=False))
noise_amplifier = GlobalFoldingAmplifier(
sub_folding_option = "from_first",
# random_seed = 123,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=4)
display(noisy_circuit.draw("mpl", plot_barriers=True))
noise_amplifier = LocalFoldingAmplifier(
sub_folding_option = "from_first",
# random_seed = 123,
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=4)
display(noisy_circuit.draw("mpl", plot_barriers=False))
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold = 2, # Two-qubit gates
# gates_to_fold = "cx",
# gates_to_fold = ["cx", "rz"],
# gates_to_fold = [2, "rz"],
)
noisy_circuit = noise_amplifier.amplify_circuit_noise(circuit=circuits[2], noise_factor=3)
display(noisy_circuit.draw("mpl", plot_barriers=False))
from zne.extrapolation import Extrapolator, ReckoningResult
from zne.noise_amplification import NoiseAmplifier
############################ NOISE AMPLIFIER ############################
class CustomAmplifier(NoiseAmplifier):
def amplify_circuit_noise(self, circuit, noise_factor):
return circuit.copy() # Dummy, nonperforming
def amplify_dag_noise(self, dag, noise_factor):
return super().amplify_dag_noise(dag, noise_factor)
############################ EXTRAPOLATOR ############################
class CustomExtrapolator(Extrapolator):
@property
def min_points(self):
return 2
def _extrapolate_zero(self, x_data, y_data, sigma_x, sigma_y):
value = 1.0
std_error = 1.0
metadata = {"meta": "data"}
return ReckoningResult(value, std_error, metadata) # Dummy, nonperforming
zne_strategy = ZNEStrategy(
noise_amplifier=CustomAmplifier(),
noise_factors=(1, 3),
extrapolator=CustomExtrapolator(),
)
estimator = ZNEEstimator(backend=Backend(), zne_strategy=zne_strategy)
job = estimator.run(
circuits=circuits[1],
observables=observables[1],
)
result = job.result()
print(EstimatorResultEncoder.dumps(result, indent=2))
cir = circuits[1]
display(cir.draw("mpl"))
obs = observables[0]
print(obs)
noise_factors = range(1,9)
list(noise_factors)
from zne.extrapolation import PolynomialExtrapolator
## ZNE STRATEGY
noise_amplifier = LocalFoldingAmplifier(
gates_to_fold=2,
sub_folding_option='from_first',
)
extrapolator = PolynomialExtrapolator(
degree=2,
)
zne_strategy = ZNEStrategy(
noise_factors=noise_factors,
noise_amplifier=noise_amplifier,
extrapolator=extrapolator,
)
## CALCULATION
estimator = ZNEEstimator(backend=Backend(), zne_strategy=zne_strategy)
job = estimator.run(
circuits=cir,
observables=obs,
)
result = job.result()
############################ DATA ############################
exact = Estimator().run(cir, obs).result().values[0]
mitigated = result.values[0]
noise_factors = result.metadata[0]["zne"]["noise_amplification"]["noise_factors"]
noisy_values = result.metadata[0]["zne"]["noise_amplification"]["values"]
############################ PLOT ############################
plt.rcParams["figure.figsize"] = (5,3.5)
plt.grid(which='major',axis='both')
plt.plot([0, noise_factors[-1]], [exact, exact], "--", label=f"Exact", color="#000000")
plt.scatter(0, mitigated, label=f"Mitigated", marker="x", color="#785ef0")
if noise_factors[0] == 1:
plt.scatter(
noise_factors[0], noisy_values[0],
label=f"Unmitigated", marker="s", color="#dc267f",
)
plt.plot(
noise_factors, noisy_values,
label=f"Amplified", marker="o", color="#dc267f",
)
plt.title("Zero noise extrapolation")
plt.xlabel("Noise Factor ($n$)")
plt.ylabel(f"Expectation Value ($\langle ZZ \\rangle$)")
plt.legend()
plt.show()
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import numpy as np
import matplotlib.pyplot as plt
# Define parameters^M
frequency = 100 # Hz (cycles per second)^M
sampling_rate = 10000 # Samples per second^M
duration = 1 # Seconds^M
time = np.linspace(0, duration, sampling_rate)
# Generate signal^M
signal = np.sin(2 * np.pi * frequency * time)
# Calculate average^M
average = np.mean(signal)
# Print average^M
print("Average of the signal:", average)
# Plot signal^M
plt.plot(time, signal)
plt.xlabel("Time (s)")
plt.ylabel("Signal")
plt.title("Fast-Oscillating Signal (Average: {:.4f})".format(average))
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
w_0 = 1e-1
w = np.linspace(0, 1e3, 1000)
func = np.exp(1j*(w_0 - 1*w))
plt.figure(figsize=(10,4))
plt.plot(w, func)
plt.grid()
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# Create a Quantum Circuit with 3 qubits
qc = QuantumCircuit(3, 3)
# Create the Bell state
qc.h(1)
qc.cx(1, 2)
# Prepare the state to be teleported
qc.x(0) # Example: teleporting |1>
# Entangle the qubit to be teleported with the first qubit of the Bell pair
qc.cx(0, 1)
qc.h(0)
# Measure the qubits
qc.measure([0, 1], [0, 1])
# Apply conditional operations based on the measurement results
qc.cx(1, 2)
qc.cz(0, 2)
# Measure the teleported qubit
qc.measure(2, 2)
# Simulate the circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=1024).result()
# Get the counts of the measurement results
counts = result.get_counts()
# Plot the results
plot_histogram(counts, title="Standard Quantum Teleportation")
qc.draw(output='mpl')
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.providers.aer import noise
# Create a Quantum Circuit with 3 qubits
qc_mixed = QuantumCircuit(3, 3)
# Create the Bell state
qc_mixed.h(1)
qc_mixed.cx(1, 2)
# Prepare the state to be teleported
qc_mixed.x(0) # Example: teleporting |1>
# Entangle the qubit to be teleported with the first qubit of the noisy Bell pair
qc_mixed.cx(0, 1)
qc_mixed.h(0)
# Measure the qubits
qc_mixed.measure([0, 1], [0, 1])
# Apply conditional operations based on the measurement results
qc_mixed.cx(1, 2)
qc_mixed.cz(0, 2)
# Measure the teleported qubit
qc_mixed.measure(2, 2)
# Define a noise model with bit-flip noise
bit_flip_prob = 0.2
bit_flip_noise = noise.pauli_error([('X', bit_flip_prob), ('I', 1 - bit_flip_prob)])
# Create a noise model
noise_model = noise.NoiseModel()
noise_model.add_all_qubit_quantum_error(bit_flip_noise, ['x', 'h'])
# Add single-qubit noise to the circuit to simulate the mixed state
qc_noisy = qc_mixed.copy()
qc_noisy.append(bit_flip_noise.to_instruction(), [1])
qc_noisy.append(bit_flip_noise.to_instruction(), [2])
# Simulate the circuit with noise
simulator = Aer.get_backend('qasm_simulator')
result_mixed = execute(qc_noisy, backend=simulator, shots=1024, noise_model=noise_model).result()
# Get the counts of the measurement results
counts_mixed = result_mixed.get_counts()
# Plot the results
plot_histogram(counts_mixed, title="Teleportation with Mixed State Resource")
import numpy as np
import matplotlib.pyplot as plt
# Define parameters
omega_0 = 1.0 # Resonant frequency of the two-level atom
gamma = 0.1 # Width of the Lorentzian peak for resonant interaction
gamma_off = 0.3 # Width of the off-resonant interaction
omega_off = 1.5 # Center frequency for off-resonant interaction
# Frequency range
omega = np.linspace(0, 2, 1000)
# Lorentzian spectral density function for resonant interaction
def J_resonant(omega, omega_0, gamma):
return gamma**2 / ((omega - omega_0)**2 + gamma**2)
# Lorentzian spectral density function for off-resonant interaction
def J_off_resonant(omega, omega_off, gamma_off):
return gamma_off**2 / ((omega - omega_off)**2 + gamma_off**2)
# Total spectral density
def J_total(omega, omega_0, gamma, omega_off, gamma_off):
return J_resonant(omega, omega_0, gamma) + J_off_resonant(omega, omega_off, gamma_off)
# Compute spectral densities
J_omega_resonant = J_resonant(omega, omega_0, gamma)
J_omega_off_resonant = J_off_resonant(omega, omega_off, gamma_off)
J_omega_total = J_total(omega, omega_0, gamma, omega_off, gamma_off)
# Plot the spectral densities
plt.figure(figsize=(10, 6))
plt.plot(omega, J_omega_resonant, label='Resonant Interaction $J_{\\text{res}}(\\omega)$')
plt.plot(omega, J_omega_off_resonant, label='Off-Resonant Interaction $J_{\\text{off-res}}(\\omega)$')
plt.plot(omega, J_omega_total, label='Total Spectral Density $J_{\\text{total}}(\\omega)$', linestyle='--')
plt.axvline(x=omega_0, color='r', linestyle='--', label='$\\omega_0$ (Resonant Frequency)')
plt.axvline(x=omega_off, color='g', linestyle='--', label='$\\omega_{\\text{off}}$ (Off-Resonant Frequency)')
plt.xlabel('$\\omega$ (Frequency)')
plt.ylabel('$J(\\omega)$ (Spectral Density)')
plt.title('Spectral Density for Two-Level Atom with Resonant and Off-Resonant Interactions')
plt.legend()
plt.grid(True)
plt.show()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/avkhadiev/schwinger-vqe
|
avkhadiev
|
Energy evaluation 1 returned -0.314419 +/- 0.038533
Energy evaluation 2 returned -0.034149 +/- 0.036455
Energy evaluation 3 returned -0.252537 +/- 0.036098
Energy evaluation 4 returned -0.015569 +/- 0.041661
Energy evaluation 5 returned -0.284201 +/- 0.035386
Energy evaluation 6 returned -0.004501 +/- 0.042106
Energy evaluation 7 returned -0.004931 +/- 0.037232
Energy evaluation 8 returned -0.277657 +/- 0.038728
Energy evaluation 9 returned -0.285717 +/- 0.038541
Energy evaluation 10 returned -0.076791 +/- 0.036352
Energy evaluation 11 returned -0.061213 +/- 0.036020
Energy evaluation 12 returned -0.306550 +/- 0.038751
Energy evaluation 13 returned -0.222509 +/- 0.038363
Energy evaluation 14 returned -0.070618 +/- 0.036528
Energy evaluation 15 returned -0.039417 +/- 0.041066
Energy evaluation 16 returned -0.306513 +/- 0.035928
Energy evaluation 17 returned -0.296036 +/- 0.036557
Energy evaluation 18 returned -0.034967 +/- 0.038903
Energy evaluation 19 returned -0.014590 +/- 0.042304
Energy evaluation 20 returned -0.255674 +/- 0.036446
Energy evaluation 21 returned -0.360293 +/- 0.039284
Energy evaluation 22 returned -0.100509 +/- 0.036138
Energy evaluation 23 returned -0.340962 +/- 0.042083
Energy evaluation 24 returned -0.010969 +/- 0.036061
Energy evaluation 25 returned -0.274148 +/- 0.038141
Energy evaluation 26 returned -0.051694 +/- 0.036584
Energy evaluation 27 returned -0.026856 +/- 0.041999
Energy evaluation 28 returned -0.238935 +/- 0.035605
Energy evaluation 29 returned -0.007813 +/- 0.036288
Energy evaluation 30 returned -0.245291 +/- 0.042334
Energy evaluation 31 returned -0.077277 +/- 0.036349
Energy evaluation 32 returned -0.299390 +/- 0.038325
Energy evaluation 33 returned -0.244863 +/- 0.036762
Energy evaluation 34 returned -0.123679 +/- 0.038950
Energy evaluation 35 returned -0.304524 +/- 0.036613
Energy evaluation 36 returned -0.030690 +/- 0.039158
Energy evaluation 37 returned -0.096245 +/- 0.036339
Energy evaluation 38 returned -0.322952 +/- 0.038412
Energy evaluation 39 returned -0.227033 +/- 0.034959
Energy evaluation 40 returned -0.042812 +/- 0.042150
Energy evaluation 41 returned -0.050591 +/- 0.034910
Energy evaluation 42 returned -0.233218 +/- 0.042512
Energy evaluation 43 returned -0.089703 +/- 0.038503
Energy evaluation 44 returned -0.326966 +/- 0.036690
Energy evaluation 45 returned -0.262048 +/- 0.042559
Energy evaluation 46 returned -0.026316 +/- 0.035945
Energy evaluation 47 returned -0.204359 +/- 0.036694
Energy evaluation 48 returned 0.020287 +/- 0.042867
Energy evaluation 49 returned -0.289152 +/- 0.038433
Energy evaluation 50 returned -0.094473 +/- 0.036482
Energy evaluation 51 returned -0.048750 +/- 0.038764
Energy evaluation 52 returned -0.340434 +/- 0.036239
Energy evaluation 53 returned 0.241486 +/- 0.040902
Energy evaluation 54 returned -0.396109 +/- 0.036407
Energy evaluation 55 returned 2.755252 +/- 0.034989
Energy evaluation 56 returned 2.451752 +/- 0.046300
Energy evaluation 57 returned 0.617239 +/- 0.058144
Energy evaluation 58 returned 0.954188 +/- 0.060074
Energy evaluation 59 returned 0.447600 +/- 0.036744
Energy evaluation 60 returned 0.258387 +/- 0.039346
Energy evaluation 61 returned 0.037581 +/- 0.047261
Energy evaluation 62 returned 0.169163 +/- 0.037793
Energy evaluation 63 returned -0.017572 +/- 0.049549
Energy evaluation 64 returned 0.333352 +/- 0.052784
Energy evaluation 65 returned -0.537248 +/- 0.039097
Energy evaluation 66 returned -0.203030 +/- 0.048513
Energy evaluation 67 returned -0.501960 +/- 0.035612
Energy evaluation 68 returned -0.026316 +/- 0.038832
Energy evaluation 69 returned -0.497420 +/- 0.045825
Energy evaluation 70 returned -0.509203 +/- 0.044074
Energy evaluation 71 returned -0.425120 +/- 0.044529
Energy evaluation 72 returned -0.666494 +/- 0.042247
Energy evaluation 73 returned -0.588548 +/- 0.037761
Energy evaluation 74 returned -0.689551 +/- 0.041281
Energy evaluation 75 returned -0.565480 +/- 0.042151
Energy evaluation 76 returned -0.709236 +/- 0.041800
Energy evaluation 77 returned -0.749831 +/- 0.041553
Energy evaluation 78 returned -0.692665 +/- 0.040703
Energy evaluation 79 returned -0.777060 +/- 0.041852
Energy evaluation 80 returned -0.726131 +/- 0.040768
Energy evaluation 81 returned -0.706200 +/- 0.042219
Energy evaluation 82 returned -0.697409 +/- 0.043357
Energy evaluation 83 returned -0.555009 +/- 0.045526
Energy evaluation 84 returned -0.756471 +/- 0.039474
Energy evaluation 85 returned -0.641371 +/- 0.036647
Energy evaluation 86 returned -0.708978 +/- 0.040471
Energy evaluation 87 returned -0.759841 +/- 0.039266
Energy evaluation 88 returned -0.714643 +/- 0.038788
Energy evaluation 89 returned -0.777053 +/- 0.039972
Energy evaluation 90 returned -0.662277 +/- 0.040555
Energy evaluation 91 returned -0.741532 +/- 0.041389
Energy evaluation 92 returned -0.709092 +/- 0.039435
Energy evaluation 93 returned -0.803988 +/- 0.035729
Energy evaluation 94 returned -0.750954 +/- 0.043295
Energy evaluation 95 returned -0.801802 +/- 0.036859
Energy evaluation 96 returned -0.796823 +/- 0.038786
Energy evaluation 97 returned -0.781198 +/- 0.038059
Energy evaluation 98 returned -0.836939 +/- 0.038834
Energy evaluation 99 returned -0.896372 +/- 0.037187
Energy evaluation 100 returned -0.769736 +/- 0.037996
Energy evaluation 101 returned -0.884862 +/- 0.037113
Energy evaluation 102 returned -0.855735 +/- 0.037939
Energy evaluation 103 returned -0.796620 +/- 0.040837
Energy evaluation 104 returned -0.844414 +/- 0.035505
Energy evaluation 105 returned -0.790673 +/- 0.035822
Energy evaluation 106 returned -0.836877 +/- 0.039194
Energy evaluation 107 returned -0.845762 +/- 0.035188
Energy evaluation 108 returned -0.759944 +/- 0.041047
Energy evaluation 109 returned -0.896422 +/- 0.035738
Energy evaluation 110 returned -0.814654 +/- 0.035935
Energy evaluation 111 returned -0.849734 +/- 0.035598
Energy evaluation 112 returned -0.930865 +/- 0.035603
Energy evaluation 113 returned -0.878019 +/- 0.032635
Energy evaluation 114 returned -0.837757 +/- 0.039473
Energy evaluation 115 returned -0.930090 +/- 0.033083
Energy evaluation 116 returned -0.918484 +/- 0.035569
Energy evaluation 117 returned -0.870833 +/- 0.033283
Energy evaluation 118 returned -0.884911 +/- 0.037352
Energy evaluation 119 returned -0.798788 +/- 0.038355
Energy evaluation 120 returned -0.866350 +/- 0.033119
Energy evaluation 121 returned -0.826328 +/- 0.035390
Energy evaluation 122 returned -0.986659 +/- 0.032752
Energy evaluation 123 returned -0.887663 +/- 0.032878
Energy evaluation 124 returned -0.872651 +/- 0.036840
Energy evaluation 125 returned -0.882326 +/- 0.033825
Energy evaluation 126 returned -0.929125 +/- 0.033515
Energy evaluation 127 returned -1.001759 +/- 0.033453
Energy evaluation 128 returned -0.908909 +/- 0.033250
Energy evaluation 129 returned -0.972004 +/- 0.034969
Energy evaluation 130 returned -0.950699 +/- 0.031468
Energy evaluation 131 returned -0.937912 +/- 0.035330
Energy evaluation 132 returned -0.916773 +/- 0.032410
Energy evaluation 133 returned -0.923081 +/- 0.032368
Energy evaluation 134 returned -0.979786 +/- 0.034977
Energy evaluation 135 returned -0.842778 +/- 0.039373
Energy evaluation 136 returned -0.980387 +/- 0.031376
Energy evaluation 137 returned -0.931943 +/- 0.031225
Energy evaluation 138 returned -0.961333 +/- 0.033090
Energy evaluation 139 returned -0.893452 +/- 0.031355
Energy evaluation 140 returned -0.982632 +/- 0.032894
Energy evaluation 141 returned -0.993145 +/- 0.032234
Energy evaluation 142 returned -0.923592 +/- 0.033731
Energy evaluation 143 returned -0.907517 +/- 0.034382
Energy evaluation 144 returned -0.972998 +/- 0.030526
Energy evaluation 145 returned -0.964261 +/- 0.032776
Energy evaluation 146 returned -1.010649 +/- 0.029539
Energy evaluation 147 returned -1.033455 +/- 0.030128
Energy evaluation 148 returned -1.029202 +/- 0.032279
Energy evaluation 149 returned -0.895641 +/- 0.030169
Energy evaluation 150 returned -0.947901 +/- 0.034433
Energy evaluation 151 returned -0.950785 +/- 0.033793
Energy evaluation 152 returned -1.000621 +/- 0.032060
Energy evaluation 153 returned -0.912934 +/- 0.030065
Energy evaluation 154 returned -0.949362 +/- 0.036167
Energy evaluation 155 returned -0.935753 +/- 0.032433
Energy evaluation 156 returned -0.973807 +/- 0.033926
Energy evaluation 157 returned -0.965741 +/- 0.032311
Energy evaluation 158 returned -0.986501 +/- 0.034828
Energy evaluation 159 returned -1.002078 +/- 0.031970
Energy evaluation 160 returned -0.963456 +/- 0.035203
Energy evaluation 161 returned -0.981760 +/- 0.036019
Energy evaluation 162 returned -0.893087 +/- 0.030171
Energy evaluation 163 returned -1.016767 +/- 0.033179
Energy evaluation 164 returned -0.930183 +/- 0.035200
Energy evaluation 165 returned -0.913683 +/- 0.036609
Energy evaluation 166 returned -0.961411 +/- 0.033617
Energy evaluation 167 returned -0.848942 +/- 0.038371
Energy evaluation 168 returned -0.959859 +/- 0.030518
Energy evaluation 169 returned -0.972236 +/- 0.029401
Energy evaluation 170 returned -0.944359 +/- 0.035231
Energy evaluation 171 returned -0.926911 +/- 0.029834
Energy evaluation 172 returned -0.942219 +/- 0.034955
Energy evaluation 173 returned -0.938858 +/- 0.030810
Energy evaluation 174 returned -0.965214 +/- 0.035725
Energy evaluation 175 returned -0.985691 +/- 0.031211
Energy evaluation 176 returned -0.970937 +/- 0.032578
Energy evaluation 177 returned -1.037661 +/- 0.032930
Energy evaluation 178 returned -0.954307 +/- 0.031281
Energy evaluation 179 returned -0.986713 +/- 0.030774
Energy evaluation 180 returned -0.931088 +/- 0.035303
Energy evaluation 181 returned -0.960684 +/- 0.033088
Energy evaluation 182 returned -0.996380 +/- 0.031083
Energy evaluation 183 returned -0.972511 +/- 0.030284
Energy evaluation 184 returned -0.944405 +/- 0.034428
Energy evaluation 185 returned -0.971349 +/- 0.033983
Energy evaluation 186 returned -0.931737 +/- 0.032552
Energy evaluation 187 returned -1.017673 +/- 0.032189
Energy evaluation 188 returned -0.993811 +/- 0.032376
Energy evaluation 189 returned -1.021794 +/- 0.031756
Energy evaluation 190 returned -0.979901 +/- 0.032631
Energy evaluation 191 returned -0.986764 +/- 0.032344
Energy evaluation 192 returned -0.981282 +/- 0.032125
Energy evaluation 193 returned -0.933521 +/- 0.035778
Energy evaluation 194 returned -0.945435 +/- 0.030417
Energy evaluation 195 returned -0.975347 +/- 0.029266
Energy evaluation 196 returned -0.974304 +/- 0.035900
Energy evaluation 197 returned -1.008231 +/- 0.033745
Energy evaluation 198 returned -0.930056 +/- 0.032316
Energy evaluation 199 returned -0.961197 +/- 0.034382
Energy evaluation 200 returned -0.966274 +/- 0.032741
Energy evaluation 201 returned -0.950879 +/- 0.031305
Energy evaluation 202 returned -0.959500 +/- 0.034598
Energy evaluation 203 returned -0.976293 +/- 0.032974
Energy evaluation 204 returned -0.982877 +/- 0.033685
Energy evaluation 205 returned -0.964974 +/- 0.033429
Energy evaluation 206 returned -1.025090 +/- 0.032110
Energy evaluation 207 returned -0.916041 +/- 0.036830
Energy evaluation 208 returned -0.932845 +/- 0.030836
Energy evaluation 209 returned -0.929876 +/- 0.030874
Energy evaluation 210 returned -0.960441 +/- 0.035735
Energy evaluation 211 returned -1.002527 +/- 0.033479
Energy evaluation 212 returned -0.961805 +/- 0.033020
Energy evaluation 213 returned -0.992272 +/- 0.030848
Energy evaluation 214 returned -1.007284 +/- 0.034102
Energy evaluation 215 returned -0.981967 +/- 0.029777
Energy evaluation 216 returned -0.936929 +/- 0.036198
Energy evaluation 217 returned -0.973293 +/- 0.035213
Energy evaluation 218 returned -0.939441 +/- 0.030462
Energy evaluation 219 returned -0.967215 +/- 0.035747
Energy evaluation 220 returned -0.999228 +/- 0.030963
Energy evaluation 221 returned -1.023688 +/- 0.034020
Energy evaluation 222 returned -0.963705 +/- 0.030884
Energy evaluation 223 returned -0.939745 +/- 0.031560
Energy evaluation 224 returned -0.892028 +/- 0.037064
Energy evaluation 225 returned -0.880389 +/- 0.038096
Energy evaluation 226 returned -0.973223 +/- 0.029987
Energy evaluation 227 returned -0.965879 +/- 0.029503
Energy evaluation 228 returned -1.007509 +/- 0.032544
Energy evaluation 229 returned -1.016328 +/- 0.031103
Energy evaluation 230 returned -1.042828 +/- 0.030372
Energy evaluation 231 returned -0.983961 +/- 0.032488
Energy evaluation 232 returned -0.989788 +/- 0.030779
Energy evaluation 233 returned -0.991819 +/- 0.031338
Energy evaluation 234 returned -0.981511 +/- 0.031787
Energy evaluation 235 returned -0.984419 +/- 0.029837
Energy evaluation 236 returned -1.011387 +/- 0.032164
Energy evaluation 237 returned -0.990560 +/- 0.032270
Energy evaluation 238 returned -1.017317 +/- 0.029765
Energy evaluation 239 returned -0.969015 +/- 0.031655
Energy evaluation 240 returned -0.989907 +/- 0.030564
Energy evaluation 241 returned -0.965055 +/- 0.029232
Energy evaluation 242 returned -0.892362 +/- 0.035967
Energy evaluation 243 returned -0.968725 +/- 0.030035
Energy evaluation 244 returned -1.023148 +/- 0.031765
Energy evaluation 245 returned -0.960270 +/- 0.030299
Energy evaluation 246 returned -1.019015 +/- 0.033144
Energy evaluation 247 returned -0.970927 +/- 0.031626
Energy evaluation 248 returned -0.993521 +/- 0.030745
Energy evaluation 249 returned -0.975590 +/- 0.032999
Energy evaluation 250 returned -1.012290 +/- 0.029461
Energy evaluation 251 returned -1.008661 +/- 0.033915
Energy evaluation 252 returned -0.942275 +/- 0.028185
Energy evaluation 253 returned -0.977620 +/- 0.035437
Energy evaluation 254 returned -1.020543 +/- 0.028695
Energy evaluation 255 returned -0.946430 +/- 0.029240
Energy evaluation 256 returned -0.978012 +/- 0.035111
Energy evaluation 257 returned -0.974300 +/- 0.032797
Energy evaluation 258 returned -1.009957 +/- 0.028860
Energy evaluation 259 returned -1.025348 +/- 0.033198
Energy evaluation 260 returned -0.997949 +/- 0.030080
Energy evaluation 261 returned -1.023380 +/- 0.034890
Energy evaluation 262 returned -0.986950 +/- 0.028785
Energy evaluation 263 returned -1.017399 +/- 0.031175
Energy evaluation 264 returned -0.987522 +/- 0.031239
Energy evaluation 265 returned -1.011958 +/- 0.033280
Energy evaluation 266 returned -1.013210 +/- 0.030774
Energy evaluation 267 returned -0.990175 +/- 0.030109
Energy evaluation 268 returned -0.989369 +/- 0.034477
Energy evaluation 269 returned -0.939258 +/- 0.029811
Energy evaluation 270 returned -0.925432 +/- 0.036554
Energy evaluation 271 returned -0.976931 +/- 0.034468
Energy evaluation 272 returned -0.989865 +/- 0.030288
Energy evaluation 273 returned -0.994962 +/- 0.032813
Energy evaluation 274 returned -0.936370 +/- 0.030540
Energy evaluation 275 returned -0.954380 +/- 0.035355
Energy evaluation 276 returned -0.982644 +/- 0.029184
Energy evaluation 277 returned -1.034801 +/- 0.031721
Energy evaluation 278 returned -0.976806 +/- 0.030472
Energy evaluation 279 returned -0.905336 +/- 0.036010
Energy evaluation 280 returned -0.978917 +/- 0.029414
Energy evaluation 281 returned -0.990523 +/- 0.033888
Energy evaluation 282 returned -0.974197 +/- 0.029001
Energy evaluation 283 returned -1.019514 +/- 0.031819
Energy evaluation 284 returned -0.986109 +/- 0.029892
Energy evaluation 285 returned -1.038095 +/- 0.031488
Energy evaluation 286 returned -0.989012 +/- 0.032727
Energy evaluation 287 returned -0.991693 +/- 0.031039
Energy evaluation 288 returned -0.991788 +/- 0.031443
Energy evaluation 289 returned -0.966597 +/- 0.032483
Energy evaluation 290 returned -1.012247 +/- 0.029887
Energy evaluation 291 returned -0.977269 +/- 0.029577
Energy evaluation 292 returned -1.013340 +/- 0.033126
Energy evaluation 293 returned -1.003906 +/- 0.031146
Energy evaluation 294 returned -1.002292 +/- 0.032231
Energy evaluation 295 returned -1.038868 +/- 0.031098
Energy evaluation 296 returned -1.042260 +/- 0.031038
Energy evaluation 297 returned -0.984846 +/- 0.035439
Energy evaluation 298 returned -0.996117 +/- 0.028658
Energy evaluation 299 returned -0.992387 +/- 0.030391
Energy evaluation 300 returned -1.090005 +/- 0.030371
Energy evaluation 301 returned -0.969032 +/- 0.033259
Energy evaluation 302 returned -0.993847 +/- 0.029276
Energy evaluation 303 returned -0.980092 +/- 0.029920
Energy evaluation 304 returned -0.934418 +/- 0.032683
Energy evaluation 305 returned -0.978137 +/- 0.029191
Energy evaluation 306 returned -1.010691 +/- 0.033322
Energy evaluation 307 returned -0.978313 +/- 0.030963
Energy evaluation 308 returned -0.984335 +/- 0.032698
Energy evaluation 309 returned -0.974643 +/- 0.035178
Energy evaluation 310 returned -1.002443 +/- 0.028646
Energy evaluation 311 returned -0.975769 +/- 0.029122
Energy evaluation 312 returned -0.969579 +/- 0.031847
Energy evaluation 313 returned -0.992971 +/- 0.028803
Energy evaluation 314 returned -0.972081 +/- 0.034370
Energy evaluation 315 returned -0.967637 +/- 0.032781
Energy evaluation 316 returned -0.977754 +/- 0.029631
Energy evaluation 317 returned -0.982747 +/- 0.029460
Energy evaluation 318 returned -1.059103 +/- 0.031870
Energy evaluation 319 returned -0.986167 +/- 0.033370
Energy evaluation 320 returned -0.933559 +/- 0.031090
Energy evaluation 321 returned -1.040134 +/- 0.029543
Energy evaluation 322 returned -1.050525 +/- 0.032291
Energy evaluation 323 returned -1.044234 +/- 0.028190
Energy evaluation 324 returned -1.022210 +/- 0.034596
Energy evaluation 325 returned -0.955185 +/- 0.029623
Energy evaluation 326 returned -0.957992 +/- 0.033132
Energy evaluation 327 returned -0.914438 +/- 0.030901
Energy evaluation 328 returned -0.962628 +/- 0.033450
Energy evaluation 329 returned -1.046471 +/- 0.032636
Energy evaluation 330 returned -0.958410 +/- 0.030376
Energy evaluation 331 returned -0.966327 +/- 0.035549
Energy evaluation 332 returned -0.964599 +/- 0.029960
Energy evaluation 333 returned -0.979234 +/- 0.029194
Energy evaluation 334 returned -1.005067 +/- 0.034639
Energy evaluation 335 returned -0.962701 +/- 0.031089
Energy evaluation 336 returned -1.038116 +/- 0.032001
Energy evaluation 337 returned -1.001709 +/- 0.029983
Energy evaluation 338 returned -1.036319 +/- 0.034661
Energy evaluation 339 returned -1.023273 +/- 0.034908
Energy evaluation 340 returned -1.002423 +/- 0.031209
Energy evaluation 341 returned -0.983429 +/- 0.036064
Energy evaluation 342 returned -0.992937 +/- 0.030883
Energy evaluation 343 returned -0.924520 +/- 0.035950
Energy evaluation 344 returned -0.965919 +/- 0.031982
Energy evaluation 345 returned -0.915517 +/- 0.036566
Energy evaluation 346 returned -0.984700 +/- 0.029966
Energy evaluation 347 returned -0.902882 +/- 0.036939
Energy evaluation 348 returned -1.040770 +/- 0.029299
Energy evaluation 349 returned -0.940645 +/- 0.029890
Energy evaluation 350 returned -0.995147 +/- 0.032542
Energy evaluation 351 returned -0.995874 +/- 0.031939
Energy evaluation 352 returned -0.973731 +/- 0.030407
Energy evaluation 353 returned -1.046024 +/- 0.030832
Energy evaluation 354 returned -1.018609 +/- 0.031002
Energy evaluation 355 returned -0.965663 +/- 0.030782
Energy evaluation 356 returned -1.023519 +/- 0.030212
Energy evaluation 357 returned -1.008912 +/- 0.028315
Energy evaluation 358 returned -0.970109 +/- 0.034566
Energy evaluation 359 returned -0.985041 +/- 0.034438
Energy evaluation 360 returned -1.011831 +/- 0.028795
Energy evaluation 361 returned -1.012877 +/- 0.032924
Energy evaluation 362 returned -1.028021 +/- 0.027528
Energy evaluation 363 returned -0.973566 +/- 0.032376
Energy evaluation 364 returned -0.995673 +/- 0.028795
Energy evaluation 365 returned -0.984455 +/- 0.032977
Energy evaluation 366 returned -0.986222 +/- 0.028958
Energy evaluation 367 returned -1.006734 +/- 0.031021
Energy evaluation 368 returned -0.992785 +/- 0.029153
Energy evaluation 369 returned -1.015728 +/- 0.029072
Energy evaluation 370 returned -1.021096 +/- 0.032105
Energy evaluation 371 returned -1.006909 +/- 0.029965
Energy evaluation 372 returned -1.005781 +/- 0.030206
Energy evaluation 373 returned -1.054606 +/- 0.029743
Energy evaluation 374 returned -1.010810 +/- 0.030485
Energy evaluation 375 returned -0.932473 +/- 0.033166
Energy evaluation 376 returned -0.981597 +/- 0.029141
Energy evaluation 377 returned -1.027567 +/- 0.031684
Energy evaluation 378 returned -0.989801 +/- 0.027801
Energy evaluation 379 returned -1.032312 +/- 0.029860
Energy evaluation 380 returned -1.000099 +/- 0.029224
Energy evaluation 381 returned -1.010365 +/- 0.031103
Energy evaluation 382 returned -0.946082 +/- 0.030083
Energy evaluation 383 returned -1.019525 +/- 0.030242
Energy evaluation 384 returned -0.976086 +/- 0.031397
Energy evaluation 385 returned -1.003141 +/- 0.028965
Energy evaluation 386 returned -1.034498 +/- 0.032193
Energy evaluation 387 returned -1.020009 +/- 0.033092
Energy evaluation 388 returned -1.024942 +/- 0.027733
Energy evaluation 389 returned -1.041128 +/- 0.031350
Energy evaluation 390 returned -0.980532 +/- 0.030055
Energy evaluation 391 returned -0.975529 +/- 0.030025
Energy evaluation 392 returned -1.044269 +/- 0.032214
Energy evaluation 393 returned -0.964225 +/- 0.031401
Energy evaluation 394 returned -1.055833 +/- 0.030284
Energy evaluation 395 returned -1.071592 +/- 0.033151
Energy evaluation 396 returned -0.984460 +/- 0.028675
Energy evaluation 397 returned -0.944889 +/- 0.030351
Energy evaluation 398 returned -1.000204 +/- 0.034567
Energy evaluation 399 returned -1.072046 +/- 0.033391
Energy evaluation 400 returned -1.010406 +/- 0.031249
Energy evaluation 401 returned -1.013944 +/- 0.033792
Energy evaluation 402 returned -0.967404 +/- 0.031813
Energy evaluation 403 returned -0.964138 +/- 0.034261
Energy evaluation 404 returned -1.089823 +/- 0.030496
Energy evaluation 405 returned -0.925980 +/- 0.036125
Energy evaluation 406 returned -1.017361 +/- 0.029648
Energy evaluation 407 returned -1.032020 +/- 0.028656
Energy evaluation 408 returned -0.948430 +/- 0.034790
Energy evaluation 409 returned -0.996406 +/- 0.034668
Energy evaluation 410 returned -0.945592 +/- 0.028796
Energy evaluation 411 returned -1.029799 +/- 0.033047
Energy evaluation 412 returned -0.992684 +/- 0.030930
Energy evaluation 413 returned -1.002690 +/- 0.033667
Energy evaluation 414 returned -0.969467 +/- 0.031150
Energy evaluation 415 returned -1.044256 +/- 0.029752
Energy evaluation 416 returned -0.989328 +/- 0.033298
Energy evaluation 417 returned -0.993618 +/- 0.035052
Energy evaluation 418 returned -0.988272 +/- 0.029111
Energy evaluation 419 returned -0.976979 +/- 0.030490
Energy evaluation 420 returned -0.971057 +/- 0.033926
Energy evaluation 421 returned -0.986030 +/- 0.031548
Energy evaluation 422 returned -1.001391 +/- 0.031195
Energy evaluation 423 returned -0.963039 +/- 0.029232
Energy evaluation 424 returned -1.021754 +/- 0.034420
Energy evaluation 425 returned -1.013567 +/- 0.031970
Energy evaluation 426 returned -0.969036 +/- 0.032961
Energy evaluation 427 returned -0.966730 +/- 0.033462
Energy evaluation 428 returned -0.966388 +/- 0.031023
Energy evaluation 429 returned -1.005050 +/- 0.031340
Energy evaluation 430 returned -0.997072 +/- 0.032413
Energy evaluation 431 returned -1.047329 +/- 0.030640
Energy evaluation 432 returned -1.040273 +/- 0.031596
Energy evaluation 433 returned -1.036418 +/- 0.033234
Energy evaluation 434 returned -0.973810 +/- 0.031930
Energy evaluation 435 returned -0.987738 +/- 0.033974
Energy evaluation 436 returned -1.041633 +/- 0.030800
Energy evaluation 437 returned -1.003653 +/- 0.029542
Energy evaluation 438 returned -1.039195 +/- 0.033755
Energy evaluation 439 returned -1.033529 +/- 0.032045
Energy evaluation 440 returned -1.044798 +/- 0.032164
Energy evaluation 441 returned -0.976127 +/- 0.036049
Energy evaluation 442 returned -1.002969 +/- 0.029743
Energy evaluation 443 returned -1.006420 +/- 0.035515
Energy evaluation 444 returned -0.982368 +/- 0.029373
Energy evaluation 445 returned -0.964947 +/- 0.033148
Energy evaluation 446 returned -0.937968 +/- 0.034143
Energy evaluation 447 returned -1.006509 +/- 0.032840
Energy evaluation 448 returned -0.957410 +/- 0.032633
Energy evaluation 449 returned -1.014134 +/- 0.030123
Energy evaluation 450 returned -0.983561 +/- 0.033592
Energy evaluation 451 returned -0.980554 +/- 0.031279
Energy evaluation 452 returned -1.050600 +/- 0.033505
Energy evaluation 453 returned -0.993651 +/- 0.032879
Energy evaluation 454 returned -1.074560 +/- 0.032001
Energy evaluation 455 returned -1.029234 +/- 0.030294
Energy evaluation 456 returned -1.003847 +/- 0.034213
Energy evaluation 457 returned -0.950252 +/- 0.035070
Energy evaluation 458 returned -1.028179 +/- 0.030379
Energy evaluation 459 returned -0.987700 +/- 0.034023
Energy evaluation 460 returned -0.981527 +/- 0.031284
Energy evaluation 461 returned -0.989066 +/- 0.034299
Energy evaluation 462 returned -1.000623 +/- 0.031202
Energy evaluation 463 returned -0.977427 +/- 0.031713
Energy evaluation 464 returned -1.012188 +/- 0.032250
Energy evaluation 465 returned -0.967973 +/- 0.036625
Energy evaluation 466 returned -0.923976 +/- 0.030984
Energy evaluation 467 returned -1.029864 +/- 0.030466
Energy evaluation 468 returned -1.002377 +/- 0.034042
Energy evaluation 469 returned -0.878645 +/- 0.034058
Energy evaluation 470 returned -1.020950 +/- 0.032586
Energy evaluation 471 returned -0.974169 +/- 0.032483
Energy evaluation 472 returned -1.005770 +/- 0.033422
Energy evaluation 473 returned -0.976655 +/- 0.034523
Energy evaluation 474 returned -1.013175 +/- 0.031325
Energy evaluation 475 returned -0.928425 +/- 0.036282
Energy evaluation 476 returned -0.976816 +/- 0.030044
Energy evaluation 477 returned -0.987502 +/- 0.030663
Energy evaluation 478 returned -0.993940 +/- 0.033243
Energy evaluation 479 returned -1.040751 +/- 0.033380
Energy evaluation 480 returned -1.016890 +/- 0.030555
Energy evaluation 481 returned -0.997512 +/- 0.032322
Energy evaluation 482 returned -1.096973 +/- 0.030969
Energy evaluation 483 returned -1.014311 +/- 0.029794
Energy evaluation 484 returned -1.004891 +/- 0.034609
Energy evaluation 485 returned -1.048068 +/- 0.031611
Energy evaluation 486 returned -0.961648 +/- 0.032815
Energy evaluation 487 returned -1.025263 +/- 0.031735
Energy evaluation 488 returned -1.016035 +/- 0.032308
Energy evaluation 489 returned -1.071246 +/- 0.032941
Energy evaluation 490 returned -0.996000 +/- 0.030892
Energy evaluation 491 returned -1.057613 +/- 0.030503
Energy evaluation 492 returned -0.956940 +/- 0.034917
Energy evaluation 493 returned -1.059492 +/- 0.029583
Energy evaluation 494 returned -1.013948 +/- 0.033787
Energy evaluation 495 returned -0.994675 +/- 0.035504
Energy evaluation 496 returned -0.992800 +/- 0.029146
Energy evaluation 497 returned -1.022280 +/- 0.031587
Energy evaluation 498 returned -0.984216 +/- 0.032121
Energy evaluation 499 returned -0.965070 +/- 0.029694
Energy evaluation 500 returned -0.953302 +/- 0.035433
Energy evaluation 501 returned -1.035340 +/- 0.033660
Energy evaluation 502 returned -1.001688 +/- 0.029450
Energy evaluation 503 returned -0.959789 +/- 0.031297
Energy evaluation 504 returned -1.013799 +/- 0.032944
Energy evaluation 505 returned -0.995515 +/- 0.033172
Energy evaluation 506 returned -1.051521 +/- 0.030207
Energy evaluation 507 returned -0.972944 +/- 0.030614
Energy evaluation 508 returned -1.048456 +/- 0.032678
Energy evaluation 509 returned -1.006209 +/- 0.033392
Energy evaluation 510 returned -0.960848 +/- 0.030923
Energy evaluation 511 returned -0.969968 +/- 0.033746
Energy evaluation 512 returned -1.010864 +/- 0.031346
Energy evaluation 513 returned -0.957659 +/- 0.036303
Energy evaluation 514 returned -1.050995 +/- 0.028719
Energy evaluation 515 returned -0.951850 +/- 0.031649
Energy evaluation 516 returned -1.014952 +/- 0.031061
Energy evaluation 517 returned -0.939665 +/- 0.032013
Energy evaluation 518 returned -0.955058 +/- 0.032624
Energy evaluation 519 returned -1.067582 +/- 0.031208
Energy evaluation 520 returned -1.039710 +/- 0.031412
Energy evaluation 521 returned -0.993945 +/- 0.028773
Energy evaluation 522 returned -0.943741 +/- 0.035908
Energy evaluation 523 returned -1.045390 +/- 0.027814
Energy evaluation 524 returned -0.965730 +/- 0.034288
Energy evaluation 525 returned -1.003305 +/- 0.031317
Energy evaluation 526 returned -1.018857 +/- 0.030095
Energy evaluation 527 returned -1.010540 +/- 0.031156
Energy evaluation 528 returned -0.991946 +/- 0.030360
Energy evaluation 529 returned -0.979156 +/- 0.029014
Energy evaluation 530 returned -1.016292 +/- 0.030647
Energy evaluation 531 returned -1.022724 +/- 0.028941
Energy evaluation 532 returned -0.988778 +/- 0.032371
Energy evaluation 533 returned -1.011546 +/- 0.032738
Energy evaluation 534 returned -0.980756 +/- 0.029701
Energy evaluation 535 returned -0.952508 +/- 0.029945
Energy evaluation 536 returned -1.018182 +/- 0.031490
Energy evaluation 537 returned -0.999212 +/- 0.030024
Energy evaluation 538 returned -1.027207 +/- 0.031778
Energy evaluation 539 returned -1.025887 +/- 0.033347
Energy evaluation 540 returned -0.963410 +/- 0.029249
Energy evaluation 541 returned -1.001434 +/- 0.031549
Energy evaluation 542 returned -1.023199 +/- 0.030787
Energy evaluation 543 returned -1.028214 +/- 0.029520
Energy evaluation 544 returned -1.089364 +/- 0.032002
Energy evaluation 545 returned -0.963328 +/- 0.029420
Energy evaluation 546 returned -1.006060 +/- 0.034298
Energy evaluation 547 returned -1.004926 +/- 0.030784
Energy evaluation 548 returned -0.936162 +/- 0.034047
Energy evaluation 549 returned -0.987594 +/- 0.030723
Energy evaluation 550 returned -0.973283 +/- 0.033399
Energy evaluation 551 returned -1.023130 +/- 0.031903
Energy evaluation 552 returned -1.009196 +/- 0.031835
Energy evaluation 553 returned -1.027381 +/- 0.029082
Energy evaluation 554 returned -1.017901 +/- 0.034015
Energy evaluation 555 returned -1.039330 +/- 0.031891
Energy evaluation 556 returned -0.944196 +/- 0.031919
Energy evaluation 557 returned -0.979869 +/- 0.034114
Energy evaluation 558 returned -1.026812 +/- 0.030751
Energy evaluation 559 returned -0.995032 +/- 0.029004
Energy evaluation 560 returned -1.010751 +/- 0.034615
Energy evaluation 561 returned -1.034300 +/- 0.030509
Energy evaluation 562 returned -0.999724 +/- 0.032972
Energy evaluation 563 returned -1.030567 +/- 0.031390
Energy evaluation 564 returned -1.028057 +/- 0.031698
Energy evaluation 565 returned -0.983225 +/- 0.031516
Energy evaluation 566 returned -0.981437 +/- 0.032229
Energy evaluation 567 returned -0.991819 +/- 0.031917
Energy evaluation 568 returned -0.971221 +/- 0.032305
Energy evaluation 569 returned -0.987603 +/- 0.033334
Energy evaluation 570 returned -0.990186 +/- 0.030241
Energy evaluation 571 returned -0.929368 +/- 0.032397
Energy evaluation 572 returned -1.012252 +/- 0.031809
Energy evaluation 573 returned -1.036311 +/- 0.030772
Energy evaluation 574 returned -0.972394 +/- 0.032450
Energy evaluation 575 returned -1.076663 +/- 0.034213
Energy evaluation 576 returned -0.970258 +/- 0.029165
Energy evaluation 577 returned -1.046261 +/- 0.034306
Energy evaluation 578 returned -1.009718 +/- 0.032290
Energy evaluation 579 returned -0.972293 +/- 0.032586
Energy evaluation 580 returned -0.891893 +/- 0.034608
Energy evaluation 581 returned -0.996240 +/- 0.032876
Energy evaluation 582 returned -1.024206 +/- 0.031540
Energy evaluation 583 returned -0.929837 +/- 0.033739
Energy evaluation 584 returned -0.971852 +/- 0.032720
Energy evaluation 585 returned -0.972019 +/- 0.034334
Energy evaluation 586 returned -1.031714 +/- 0.030253
Energy evaluation 587 returned -1.000786 +/- 0.034823
Energy evaluation 588 returned -0.992489 +/- 0.030302
Energy evaluation 589 returned -1.049408 +/- 0.031914
Energy evaluation 590 returned -1.036746 +/- 0.031921
Energy evaluation 591 returned -1.009492 +/- 0.029426
Energy evaluation 592 returned -0.983450 +/- 0.034687
Energy evaluation 593 returned -0.986823 +/- 0.034395
Energy evaluation 594 returned -0.955310 +/- 0.031437
Energy evaluation 595 returned -0.969234 +/- 0.033622
Energy evaluation 596 returned -1.002952 +/- 0.030711
Energy evaluation 597 returned -0.995221 +/- 0.029093
Energy evaluation 598 returned -0.933211 +/- 0.035834
Energy evaluation 599 returned -0.936643 +/- 0.030695
Energy evaluation 600 returned -0.979818 +/- 0.034666
Energy evaluation 601 returned -0.984730 +/- 0.031350
Energy evaluation 602 returned -1.042079 +/- 0.032905
Energy evaluation 603 returned -1.027927 +/- 0.031557
Energy evaluation 604 returned -1.036683 +/- 0.032508
Energy evaluation 605 returned -1.074637 +/- 0.029606
Energy evaluation 606 returned -0.928519 +/- 0.035209
Energy evaluation 607 returned -1.039397 +/- 0.029376
Energy evaluation 608 returned -1.010675 +/- 0.032600
Energy evaluation 609 returned -0.974155 +/- 0.032483
Energy evaluation 610 returned -1.006290 +/- 0.032286
Energy evaluation 611 returned -0.956239 +/- 0.035438
Energy evaluation 612 returned -0.993433 +/- 0.028643
Energy evaluation 613 returned -0.965238 +/- 0.031499
Energy evaluation 614 returned -1.020369 +/- 0.031257
Energy evaluation 615 returned -0.969603 +/- 0.029712
Energy evaluation 616 returned -1.009274 +/- 0.034099
Energy evaluation 617 returned -1.005207 +/- 0.031170
Energy evaluation 618 returned -0.999903 +/- 0.031753
Energy evaluation 619 returned -1.054106 +/- 0.032258
Energy evaluation 620 returned -0.942992 +/- 0.031452
Energy evaluation 621 returned -0.943677 +/- 0.029239
Energy evaluation 622 returned -0.988561 +/- 0.033565
Energy evaluation 623 returned -1.001683 +/- 0.030746
Energy evaluation 624 returned -1.007030 +/- 0.033233
Energy evaluation 625 returned -0.976863 +/- 0.034788
Energy evaluation 626 returned -0.957005 +/- 0.030099
Energy evaluation 627 returned -0.918693 +/- 0.035358
Energy evaluation 628 returned -1.031175 +/- 0.030598
Energy evaluation 629 returned -0.989867 +/- 0.035789
Energy evaluation 630 returned -0.979748 +/- 0.029361
Energy evaluation 631 returned -0.975632 +/- 0.029311
Energy evaluation 632 returned -0.966509 +/- 0.034548
Energy evaluation 633 returned -0.984557 +/- 0.031173
Energy evaluation 634 returned -0.994839 +/- 0.033105
Energy evaluation 635 returned -0.949819 +/- 0.033577
Energy evaluation 636 returned -0.991537 +/- 0.030511
Energy evaluation 637 returned -0.931647 +/- 0.029839
Energy evaluation 638 returned -1.017722 +/- 0.034335
Energy evaluation 639 returned -1.029145 +/- 0.029456
Energy evaluation 640 returned -0.948801 +/- 0.036204
Energy evaluation 641 returned -0.959679 +/- 0.031221
Energy evaluation 642 returned -0.999159 +/- 0.032920
Energy evaluation 643 returned -0.918685 +/- 0.033690
Energy evaluation 644 returned -0.978681 +/- 0.031986
Energy evaluation 645 returned -0.962767 +/- 0.034981
Energy evaluation 646 returned -0.993459 +/- 0.029786
Energy evaluation 647 returned -0.972128 +/- 0.029595
Energy evaluation 648 returned -0.978744 +/- 0.034792
Energy evaluation 649 returned -0.977396 +/- 0.030370
Energy evaluation 650 returned -1.049111 +/- 0.033010
Energy evaluation 651 returned -0.978840 +/- 0.033113
Energy evaluation 652 returned -0.984712 +/- 0.031440
Energy evaluation 653 returned -1.036778 +/- 0.031908
Energy evaluation 654 returned -1.019459 +/- 0.031034
Energy evaluation 655 returned -1.058992 +/- 0.030549
Energy evaluation 656 returned -1.074926 +/- 0.031189
Energy evaluation 657 returned -0.952937 +/- 0.031955
Energy evaluation 658 returned -0.992718 +/- 0.033537
Energy evaluation 659 returned -0.973436 +/- 0.033886
Energy evaluation 660 returned -0.985200 +/- 0.031059
Energy evaluation 661 returned -1.049019 +/- 0.032863
Energy evaluation 662 returned -0.994951 +/- 0.030617
Energy evaluation 663 returned -0.921898 +/- 0.036989
Energy evaluation 664 returned -1.038529 +/- 0.028634
Energy evaluation 665 returned -0.993090 +/- 0.028645
Energy evaluation 666 returned -0.986769 +/- 0.035376
Energy evaluation 667 returned -1.007652 +/- 0.034412
Energy evaluation 668 returned -0.934283 +/- 0.030143
Energy evaluation 669 returned -0.987199 +/- 0.035112
Energy evaluation 670 returned -1.007441 +/- 0.029554
Energy evaluation 671 returned -0.999794 +/- 0.031547
Energy evaluation 672 returned -1.007346 +/- 0.031205
Energy evaluation 673 returned -1.032093 +/- 0.033564
Energy evaluation 674 returned -1.042363 +/- 0.029741
Energy evaluation 675 returned -1.001997 +/- 0.029051
Energy evaluation 676 returned -1.014303 +/- 0.034685
Energy evaluation 677 returned -0.972362 +/- 0.032336
Energy evaluation 678 returned -0.980537 +/- 0.032768
Energy evaluation 679 returned -0.953759 +/- 0.033697
Energy evaluation 680 returned -0.979535 +/- 0.030478
Energy evaluation 681 returned -0.973782 +/- 0.031959
Energy evaluation 682 returned -0.976236 +/- 0.032698
Energy evaluation 683 returned -0.980629 +/- 0.035398
Energy evaluation 684 returned -0.984031 +/- 0.028788
Energy evaluation 685 returned -0.980808 +/- 0.035333
Energy evaluation 686 returned -0.965896 +/- 0.030832
Energy evaluation 687 returned -1.042597 +/- 0.033426
Energy evaluation 688 returned -0.999065 +/- 0.030225
Energy evaluation 689 returned -0.969973 +/- 0.030716
Energy evaluation 690 returned -0.943360 +/- 0.034709
Energy evaluation 691 returned -0.959710 +/- 0.034933
Energy evaluation 692 returned -0.971909 +/- 0.029123
Energy evaluation 693 returned -1.024716 +/- 0.030861
Energy evaluation 694 returned -1.060949 +/- 0.032082
Energy evaluation 695 returned -1.007178 +/- 0.029946
Energy evaluation 696 returned -0.930918 +/- 0.035992
Energy evaluation 697 returned -1.011320 +/- 0.030011
Energy evaluation 698 returned -0.993373 +/- 0.032298
Energy evaluation 699 returned -0.996451 +/- 0.029783
Energy evaluation 700 returned -0.918388 +/- 0.033902
Energy evaluation 701 returned -1.019353 +/- 0.030803
Energy evaluation 702 returned -1.073879 +/- 0.029856
Energy evaluation 703 returned -0.972164 +/- 0.033206
Energy evaluation 704 returned -1.051799 +/- 0.028810
Energy evaluation 705 returned -0.999437 +/- 0.032129
Energy evaluation 706 returned -0.980088 +/- 0.029926
Energy evaluation 707 returned -0.966663 +/- 0.029118
Energy evaluation 708 returned -0.974849 +/- 0.033914
Energy evaluation 709 returned -0.993400 +/- 0.030968
Energy evaluation 710 returned -1.000463 +/- 0.031809
Energy evaluation 711 returned -0.975266 +/- 0.031663
Energy evaluation 712 returned -0.972005 +/- 0.031418
Energy evaluation 713 returned -0.963563 +/- 0.030811
Energy evaluation 714 returned -0.977604 +/- 0.032697
Energy evaluation 715 returned -0.982693 +/- 0.033093
Energy evaluation 716 returned -1.024791 +/- 0.028784
Energy evaluation 717 returned -0.987277 +/- 0.031107
Energy evaluation 718 returned -0.992344 +/- 0.030684
Energy evaluation 719 returned -0.989957 +/- 0.031046
Energy evaluation 720 returned -0.992341 +/- 0.030713
Energy evaluation 721 returned -1.000068 +/- 0.033326
Energy evaluation 722 returned -0.895167 +/- 0.030186
Energy evaluation 723 returned -1.002746 +/- 0.033865
Energy evaluation 724 returned -1.051960 +/- 0.030034
Energy evaluation 725 returned -1.016700 +/- 0.032136
Energy evaluation 726 returned -1.008865 +/- 0.031153
Energy evaluation 727 returned -0.951339 +/- 0.030567
Energy evaluation 728 returned -0.929524 +/- 0.034660
Energy evaluation 729 returned -0.985642 +/- 0.033689
Energy evaluation 730 returned -1.052020 +/- 0.028033
Energy evaluation 731 returned -0.971969 +/- 0.030807
Energy evaluation 732 returned -0.929532 +/- 0.031724
Energy evaluation 733 returned -0.988612 +/- 0.030512
Energy evaluation 734 returned -0.989589 +/- 0.032019
Energy evaluation 735 returned -1.004770 +/- 0.032072
Energy evaluation 736 returned -0.993128 +/- 0.029444
Energy evaluation 737 returned -0.990498 +/- 0.031154
Energy evaluation 738 returned -0.977570 +/- 0.031867
Energy evaluation 739 returned -0.990868 +/- 0.028780
Energy evaluation 740 returned -0.958024 +/- 0.035400
Energy evaluation 741 returned -0.970288 +/- 0.033572
Energy evaluation 742 returned -0.913655 +/- 0.029127
Energy evaluation 743 returned -1.026623 +/- 0.033780
Energy evaluation 744 returned -1.002492 +/- 0.028294
Energy evaluation 745 returned -0.996699 +/- 0.030633
Energy evaluation 746 returned -0.965894 +/- 0.033199
Energy evaluation 747 returned -0.997163 +/- 0.030490
Energy evaluation 748 returned -0.981813 +/- 0.032343
Energy evaluation 749 returned -1.041569 +/- 0.027856
Energy evaluation 750 returned -0.959162 +/- 0.034511
Energy evaluation 751 returned -0.994574 +/- 0.033209
Energy evaluation 752 returned -0.961525 +/- 0.029210
Energy evaluation 753 returned -1.026168 +/- 0.033079
Energy evaluation 754 returned -0.988586 +/- 0.028943
Energy evaluation 755 returned -0.975484 +/- 0.030840
Energy evaluation 756 returned -0.985998 +/- 0.032522
Energy evaluation 757 returned -1.032955 +/- 0.030877
Energy evaluation 758 returned -0.997871 +/- 0.031025
Energy evaluation 759 returned -1.047527 +/- 0.033414
Energy evaluation 760 returned -1.004757 +/- 0.028784
Energy evaluation 761 returned -0.982824 +/- 0.032117
Energy evaluation 762 returned -0.951649 +/- 0.032909
Energy evaluation 763 returned -1.003190 +/- 0.032192
Energy evaluation 764 returned -0.997364 +/- 0.031216
Energy evaluation 765 returned -1.023945 +/- 0.032904
Energy evaluation 766 returned -1.003769 +/- 0.029624
Energy evaluation 767 returned -1.013126 +/- 0.031193
Energy evaluation 768 returned -1.011417 +/- 0.031433
Energy evaluation 769 returned -1.016887 +/- 0.032008
Energy evaluation 770 returned -0.962909 +/- 0.031238
Energy evaluation 771 returned -1.059198 +/- 0.029801
Energy evaluation 772 returned -0.967365 +/- 0.033954
Energy evaluation 773 returned -1.042015 +/- 0.029561
Energy evaluation 774 returned -1.022986 +/- 0.032939
Energy evaluation 775 returned -1.033502 +/- 0.030646
Energy evaluation 776 returned -1.013076 +/- 0.031431
Energy evaluation 777 returned -0.971543 +/- 0.029432
Energy evaluation 778 returned -1.017103 +/- 0.034101
Energy evaluation 779 returned -0.979708 +/- 0.033835
Energy evaluation 780 returned -0.985553 +/- 0.030280
Energy evaluation 781 returned -0.947871 +/- 0.029605
Energy evaluation 782 returned -1.002736 +/- 0.034119
Energy evaluation 783 returned -0.965405 +/- 0.032359
Energy evaluation 784 returned -0.980855 +/- 0.031951
Energy evaluation 785 returned -0.981987 +/- 0.033888
Energy evaluation 786 returned -0.960744 +/- 0.032261
Energy evaluation 787 returned -0.984188 +/- 0.030049
Energy evaluation 788 returned -0.969833 +/- 0.034628
Energy evaluation 789 returned -1.010905 +/- 0.028469
Energy evaluation 790 returned -0.980266 +/- 0.034341
Energy evaluation 791 returned -1.110909 +/- 0.032043
Energy evaluation 792 returned -0.972959 +/- 0.030339
Energy evaluation 793 returned -0.965471 +/- 0.034154
Energy evaluation 794 returned -0.983553 +/- 0.031628
Energy evaluation 795 returned -0.958872 +/- 0.035482
Energy evaluation 796 returned -0.980918 +/- 0.029551
Energy evaluation 797 returned -0.971562 +/- 0.032417
Energy evaluation 798 returned -0.985414 +/- 0.031848
Energy evaluation 799 returned -0.993806 +/- 0.031453
Energy evaluation 800 returned -1.057047 +/- 0.031037
Energy evaluation 801 returned -0.999504 +/- 0.030802
Energy evaluation 802 returned -0.971602 +/- 0.034525
Energy evaluation 803 returned -0.939703 +/- 0.033025
Energy evaluation 804 returned -0.991937 +/- 0.031924
Energy evaluation 805 returned -0.937699 +/- 0.031469
Energy evaluation 806 returned -1.019361 +/- 0.032607
Energy evaluation 807 returned -0.962611 +/- 0.031821
Energy evaluation 808 returned -0.969412 +/- 0.034241
Energy evaluation 809 returned -1.029352 +/- 0.033220
Energy evaluation 810 returned -0.973684 +/- 0.030717
Energy evaluation 811 returned -0.989216 +/- 0.035250
Energy evaluation 812 returned -0.997807 +/- 0.029865
Energy evaluation 813 returned -0.963783 +/- 0.031100
Energy evaluation 814 returned -0.946039 +/- 0.035765
Energy evaluation 815 returned -0.973332 +/- 0.033811
Energy evaluation 816 returned -0.984619 +/- 0.031367
Energy evaluation 817 returned -1.019452 +/- 0.031707
Energy evaluation 818 returned -0.965002 +/- 0.032568
Energy evaluation 819 returned -1.020313 +/- 0.030407
Energy evaluation 820 returned -1.011095 +/- 0.033902
Energy evaluation 821 returned -0.998524 +/- 0.033924
Energy evaluation 822 returned -0.971269 +/- 0.032055
Energy evaluation 823 returned -0.999140 +/- 0.032204
Energy evaluation 824 returned -1.023219 +/- 0.032946
Energy evaluation 825 returned -1.034648 +/- 0.029358
Energy evaluation 826 returned -1.000369 +/- 0.035229
Energy evaluation 827 returned -0.988710 +/- 0.029695
Energy evaluation 828 returned -1.077652 +/- 0.032634
Energy evaluation 829 returned -1.032578 +/- 0.032284
Energy evaluation 830 returned -1.011198 +/- 0.031987
Energy evaluation 831 returned -0.960760 +/- 0.034280
Energy evaluation 832 returned -1.024146 +/- 0.030337
Energy evaluation 833 returned -1.032693 +/- 0.030582
Energy evaluation 834 returned -0.991135 +/- 0.034010
Energy evaluation 835 returned -0.943894 +/- 0.035838
Energy evaluation 836 returned -1.002710 +/- 0.030519
Energy evaluation 837 returned -1.052773 +/- 0.030112
Energy evaluation 838 returned -1.014261 +/- 0.032930
Energy evaluation 839 returned -1.035608 +/- 0.034239
Energy evaluation 840 returned -1.011169 +/- 0.028710
Energy evaluation 841 returned -1.041459 +/- 0.032657
Energy evaluation 842 returned -0.995856 +/- 0.031301
Energy evaluation 843 returned -1.008846 +/- 0.029670
Energy evaluation 844 returned -1.006045 +/- 0.033802
Energy evaluation 845 returned -0.918895 +/- 0.034622
Energy evaluation 846 returned -0.977759 +/- 0.029454
Energy evaluation 847 returned -0.969228 +/- 0.032622
Energy evaluation 848 returned -1.009704 +/- 0.031187
Energy evaluation 849 returned -0.984614 +/- 0.033686
Energy evaluation 850 returned -0.980893 +/- 0.029801
Energy evaluation 851 returned -1.043636 +/- 0.029642
Energy evaluation 852 returned -0.920283 +/- 0.033614
Energy evaluation 853 returned -1.028215 +/- 0.029932
Energy evaluation 854 returned -0.997361 +/- 0.032675
Energy evaluation 855 returned -1.066655 +/- 0.028259
Energy evaluation 856 returned -1.034839 +/- 0.031737
Energy evaluation 857 returned -1.045831 +/- 0.028364
Energy evaluation 858 returned -1.021447 +/- 0.032307
Energy evaluation 859 returned -0.971358 +/- 0.029860
Energy evaluation 860 returned -1.041095 +/- 0.030735
Energy evaluation 861 returned -0.981135 +/- 0.031038
Energy evaluation 862 returned -0.991986 +/- 0.031503
Energy evaluation 863 returned -0.994583 +/- 0.031722
Energy evaluation 864 returned -0.961378 +/- 0.031083
Energy evaluation 865 returned -1.021680 +/- 0.030781
Energy evaluation 866 returned -1.001550 +/- 0.031792
Energy evaluation 867 returned -1.082979 +/- 0.031255
Energy evaluation 868 returned -1.028607 +/- 0.029809
Energy evaluation 869 returned -0.950352 +/- 0.029112
Energy evaluation 870 returned -1.001934 +/- 0.033564
Energy evaluation 871 returned -0.998879 +/- 0.029733
Energy evaluation 872 returned -0.971831 +/- 0.033513
Energy evaluation 873 returned -0.982483 +/- 0.032137
Energy evaluation 874 returned -1.015443 +/- 0.030364
Energy evaluation 875 returned -0.998631 +/- 0.032045
Energy evaluation 876 returned -0.976688 +/- 0.032485
Energy evaluation 877 returned -1.064392 +/- 0.031338
Energy evaluation 878 returned -0.950804 +/- 0.030879
Energy evaluation 879 returned -1.054708 +/- 0.028824
Energy evaluation 880 returned -0.919401 +/- 0.035599
Energy evaluation 881 returned -0.938161 +/- 0.031746
Energy evaluation 882 returned -0.926528 +/- 0.031959
Energy evaluation 883 returned -0.983400 +/- 0.032860
Energy evaluation 884 returned -0.997837 +/- 0.029965
Energy evaluation 885 returned -0.980783 +/- 0.032968
Energy evaluation 886 returned -0.999638 +/- 0.030176
Energy evaluation 887 returned -0.977962 +/- 0.030498
Energy evaluation 888 returned -0.986658 +/- 0.030896
Energy evaluation 889 returned -0.989520 +/- 0.030864
Energy evaluation 890 returned -0.949058 +/- 0.032621
Energy evaluation 891 returned -0.964865 +/- 0.029875
Energy evaluation 892 returned -1.031578 +/- 0.031103
Energy evaluation 893 returned -1.000529 +/- 0.028826
Energy evaluation 894 returned -1.012788 +/- 0.031123
Energy evaluation 895 returned -1.034517 +/- 0.029283
Energy evaluation 896 returned -1.017239 +/- 0.031185
Energy evaluation 897 returned -0.999251 +/- 0.030423
Energy evaluation 898 returned -1.062275 +/- 0.031705
Energy evaluation 899 returned -0.974157 +/- 0.031552
Energy evaluation 900 returned -0.997518 +/- 0.030198
Energy evaluation 901 returned -0.975608 +/- 0.029869
Energy evaluation 902 returned -1.014098 +/- 0.031442
Energy evaluation 903 returned -0.986103 +/- 0.031682
Energy evaluation 904 returned -0.996213 +/- 0.030508
Energy evaluation 905 returned -1.016772 +/- 0.029295
Energy evaluation 906 returned -0.994155 +/- 0.033181
Energy evaluation 907 returned -1.022150 +/- 0.029334
Energy evaluation 908 returned -1.023815 +/- 0.032588
Energy evaluation 909 returned -1.002598 +/- 0.032531
Energy evaluation 910 returned -1.007208 +/- 0.029137
Energy evaluation 911 returned -0.972256 +/- 0.030676
Energy evaluation 912 returned -0.926175 +/- 0.032557
Energy evaluation 913 returned -0.997694 +/- 0.032784
Energy evaluation 914 returned -1.013493 +/- 0.028782
Energy evaluation 915 returned -0.976425 +/- 0.030376
Energy evaluation 916 returned -1.018574 +/- 0.031818
Energy evaluation 917 returned -1.026767 +/- 0.032126
Energy evaluation 918 returned -1.021173 +/- 0.029315
Energy evaluation 919 returned -1.067505 +/- 0.029937
Energy evaluation 920 returned -1.012345 +/- 0.031443
Energy evaluation 921 returned -0.977361 +/- 0.034089
Energy evaluation 922 returned -0.986489 +/- 0.029154
Energy evaluation 923 returned -1.020429 +/- 0.029857
Energy evaluation 924 returned -1.037755 +/- 0.029674
Energy evaluation 925 returned -0.969929 +/- 0.032822
Energy evaluation 926 returned -0.950369 +/- 0.030652
Energy evaluation 927 returned -1.077733 +/- 0.030715
Energy evaluation 928 returned -0.996456 +/- 0.030839
Energy evaluation 929 returned -0.987424 +/- 0.031532
Energy evaluation 930 returned -1.014396 +/- 0.031060
Energy evaluation 931 returned -1.029922 +/- 0.033124
Energy evaluation 932 returned -1.015794 +/- 0.028127
Energy evaluation 933 returned -1.005317 +/- 0.028318
Energy evaluation 934 returned -0.998756 +/- 0.033667
Energy evaluation 935 returned -0.999579 +/- 0.031165
Energy evaluation 936 returned -1.021820 +/- 0.029453
Energy evaluation 937 returned -1.019211 +/- 0.029909
Energy evaluation 938 returned -0.985463 +/- 0.032547
Energy evaluation 939 returned -0.997831 +/- 0.030804
Energy evaluation 940 returned -1.022745 +/- 0.030701
Energy evaluation 941 returned -1.004677 +/- 0.031083
Energy evaluation 942 returned -0.975577 +/- 0.031519
Energy evaluation 943 returned -1.016243 +/- 0.032682
Energy evaluation 944 returned -0.997222 +/- 0.028332
Energy evaluation 945 returned -0.975944 +/- 0.029629
Energy evaluation 946 returned -1.026117 +/- 0.031854
Energy evaluation 947 returned -0.982106 +/- 0.028470
Energy evaluation 948 returned -0.970373 +/- 0.034399
Energy evaluation 949 returned -1.030061 +/- 0.032243
Energy evaluation 950 returned -0.979772 +/- 0.029733
Energy evaluation 951 returned -1.007426 +/- 0.032182
Energy evaluation 952 returned -0.981690 +/- 0.030516
Energy evaluation 953 returned -1.048511 +/- 0.028117
Energy evaluation 954 returned -0.986743 +/- 0.032962
Energy evaluation 955 returned -0.945073 +/- 0.029383
Energy evaluation 956 returned -0.963330 +/- 0.031855
Energy evaluation 957 returned -0.972405 +/- 0.028709
Energy evaluation 958 returned -0.992808 +/- 0.034245
Energy evaluation 959 returned -0.961358 +/- 0.030839
Energy evaluation 960 returned -0.995489 +/- 0.032402
Energy evaluation 961 returned -0.996751 +/- 0.031584
Energy evaluation 962 returned -1.014605 +/- 0.030775
Energy evaluation 963 returned -1.021467 +/- 0.030147
Energy evaluation 964 returned -0.989439 +/- 0.032361
Energy evaluation 965 returned -1.051029 +/- 0.031157
Energy evaluation 966 returned -1.002468 +/- 0.031887
Energy evaluation 967 returned -0.982325 +/- 0.028898
Energy evaluation 968 returned -1.019646 +/- 0.033579
Energy evaluation 969 returned -1.021551 +/- 0.030269
Energy evaluation 970 returned -1.017417 +/- 0.031815
Energy evaluation 971 returned -1.037527 +/- 0.031218
Energy evaluation 972 returned -1.005724 +/- 0.031348
Energy evaluation 973 returned -1.007502 +/- 0.031525
Energy evaluation 974 returned -1.029416 +/- 0.030400
Energy evaluation 975 returned -1.004617 +/- 0.030743
Energy evaluation 976 returned -0.991374 +/- 0.032936
Energy evaluation 977 returned -1.015038 +/- 0.030327
Energy evaluation 978 returned -0.957069 +/- 0.032742
Energy evaluation 979 returned -1.008622 +/- 0.030322
Energy evaluation 980 returned -0.991707 +/- 0.032422
Energy evaluation 981 returned -0.977856 +/- 0.029463
Energy evaluation 982 returned -0.987152 +/- 0.033559
Energy evaluation 983 returned -0.934635 +/- 0.032375
Energy evaluation 984 returned -1.026034 +/- 0.029977
Energy evaluation 985 returned -0.959344 +/- 0.028684
Energy evaluation 986 returned -1.030021 +/- 0.033757
Energy evaluation 987 returned -0.980538 +/- 0.031838
Energy evaluation 988 returned -1.057853 +/- 0.031025
Energy evaluation 989 returned -0.948215 +/- 0.035459
Energy evaluation 990 returned -0.972401 +/- 0.029887
Energy evaluation 991 returned -1.033349 +/- 0.032353
Energy evaluation 992 returned -0.972230 +/- 0.030471
Energy evaluation 993 returned -1.004425 +/- 0.033173
Energy evaluation 994 returned -1.003661 +/- 0.030472
Energy evaluation 995 returned -0.972430 +/- 0.034363
Energy evaluation 996 returned -0.964977 +/- 0.029878
Energy evaluation 997 returned -0.979914 +/- 0.031422
Energy evaluation 998 returned -0.945564 +/- 0.034027
Energy evaluation 999 returned -1.055920 +/- 0.030135
Energy evaluation 1000 returned -1.064126 +/- 0.031370
Energy evaluation 1001 returned -0.961398 +/- 0.033662
Energy evaluation 1002 returned -1.038466 +/- 0.030300
Energy evaluation 1003 returned -1.037960 +/- 0.029957
Energy evaluation 1004 returned -1.022867 +/- 0.032898
Energy evaluation 1005 returned -0.979184 +/- 0.030808
Energy evaluation 1006 returned -0.989504 +/- 0.033410
Energy evaluation 1007 returned -0.995529 +/- 0.032002
Energy evaluation 1008 returned -1.000105 +/- 0.029643
Energy evaluation 1009 returned -1.029865 +/- 0.029766
Energy evaluation 1010 returned -1.016752 +/- 0.032832
Energy evaluation 1011 returned -0.983467 +/- 0.030661
Energy evaluation 1012 returned -0.994240 +/- 0.032735
Energy evaluation 1013 returned -1.014989 +/- 0.030127
Energy evaluation 1014 returned -0.983941 +/- 0.032412
Energy evaluation 1015 returned -1.041868 +/- 0.031115
Energy evaluation 1016 returned -1.017627 +/- 0.031439
Energy evaluation 1017 returned -1.006392 +/- 0.028511
Energy evaluation 1018 returned -0.946356 +/- 0.034198
Energy evaluation 1019 returned -1.034708 +/- 0.029980
Energy evaluation 1020 returned -1.039788 +/- 0.030809
Energy evaluation 1021 returned -1.020616 +/- 0.030983
Energy evaluation 1022 returned -0.973869 +/- 0.031002
Energy evaluation 1023 returned -1.020920 +/- 0.032453
Energy evaluation 1024 returned -0.994614 +/- 0.029941
Energy evaluation 1025 returned -0.977376 +/- 0.032127
Energy evaluation 1026 returned -0.978485 +/- 0.030124
Energy evaluation 1027 returned -0.978233 +/- 0.033071
Energy evaluation 1028 returned -0.929290 +/- 0.031602
Energy evaluation 1029 returned -1.035471 +/- 0.031174
Energy evaluation 1030 returned -0.987792 +/- 0.031540
Energy evaluation 1031 returned -1.029508 +/- 0.033234
Energy evaluation 1032 returned -0.963405 +/- 0.029284
Energy evaluation 1033 returned -0.988925 +/- 0.032675
Energy evaluation 1034 returned -1.001834 +/- 0.031181
Energy evaluation 1035 returned -1.005719 +/- 0.031815
Energy evaluation 1036 returned -0.970747 +/- 0.029856
Energy evaluation 1037 returned -1.016290 +/- 0.031457
Energy evaluation 1038 returned -1.055224 +/- 0.031060
Energy evaluation 1039 returned -1.037417 +/- 0.030456
Energy evaluation 1040 returned -0.989888 +/- 0.033688
Energy evaluation 1041 returned -0.991445 +/- 0.033937
Energy evaluation 1042 returned -1.031271 +/- 0.028795
Energy evaluation 1043 returned -0.977898 +/- 0.033402
Energy evaluation 1044 returned -1.005856 +/- 0.029799
Energy evaluation 1045 returned -1.079747 +/- 0.029947
Energy evaluation 1046 returned -1.004045 +/- 0.031639
Energy evaluation 1047 returned -1.036121 +/- 0.032812
Energy evaluation 1048 returned -1.027332 +/- 0.029499
Energy evaluation 1049 returned -0.991534 +/- 0.033142
Energy evaluation 1050 returned -1.034950 +/- 0.028632
Energy evaluation 1051 returned -1.009399 +/- 0.030947
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### added y gate ###
qc.y(0)
qc.h(1)
return qc
|
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/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
from qiskit_cold_atom.providers import ColdAtomProvider
# save an account to disk
# ColdAtomProvider.save_account(url = ["url_of_backend_1", "url_of_backend_2"], username="JohnDoe",token="123456")
# load the stored account
provider = ColdAtomProvider.load_account()
print(provider.backends())
spin_device_backend = provider.get_backend("SYNQS_SoPa_backend")
spin_device_backend.status().to_dict()
spin_device_backend.configuration().supported_instructions
from qiskit.circuit import QuantumCircuit, Parameter
import numpy as np
t = Parameter("t")
circuit = QuantumCircuit(1, 1)
circuit.delay(duration = t, unit='s', qarg=0)
circuit.measure(0, 0)
circuit.draw(output='mpl')
# create a list of circuits with variable loading times:
load_times = np.arange(0.1, 15, 2)
circuit_list =[circuit.bind_parameters({t: load_time}) for load_time in load_times]
# send the list of circuits to the backend and execute with 5 shots each
# demo_job = spin_device_backend.run(circuit_list, shots = 5)
job_retrieved = spin_device_backend.retrieve_job(job_id = "20210520_171502_89aec")
print("job status: ", job_retrieved.status())
result = job_retrieved.result()
print(type(result))
outcomes = [result.get_memory(i) for i in range(len(circuit_list))]
atom_numbers = [np.mean(np.array(counts, dtype=float)) for counts in outcomes]
atom_stds = [np.std(np.array(counts, dtype=float)) for counts in outcomes]
import matplotlib.pyplot as plt
plt.errorbar(load_times, atom_numbers, yerr=atom_stds, fmt='x--')
plt.grid(alpha=0.5)
plt.title("loading of atoms in cold atomic device through Qiskit")
plt.xlabel("loading time [s]")
plt.ylabel("atom number in trap [a.u.]")
plt.show()
result.to_dict()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
# -*- 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/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### replaced cx gate ###
qc.cy(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### added x gate ###
qc.x(qubit)
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qrx = QuantumRegister(3, 'x')
qry = QuantumRegister(1, 'y')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
# qc.h(qry) 機率會不同
qc.h(qry)
qc.barrier()
qc.cx(qrx[0], qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/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.
"""Tests for circuit MPL drawer"""
import unittest
import os
import math
from test.visual import VisualTestUtilities
from pathlib import Path
import numpy as np
from numpy import pi
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer
from qiskit.circuit.library import (
XGate,
MCXGate,
HGate,
RZZGate,
SwapGate,
DCXGate,
ZGate,
SGate,
U1Gate,
CPhaseGate,
)
from qiskit.circuit.library import MCXVChain
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "circuit_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "circuit_failure_"
class TestCircuitMatplotlibDrawer(QiskitTestCase):
"""Circuit MPL visualization"""
def setUp(self):
super().setUp()
self.circuit_drawer = VisualTestUtilities.save_data_wrap(
_matplotlib_circuit_drawer, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_empty_circuit(self):
"""Test empty circuit"""
circuit = QuantumCircuit()
fname = "empty_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
from qiskit import pulse
with pulse.build(name="hadamard") as h_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0)
)
circuit.add_calibration("h", [0], h_q0)
fname = "calibrations.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_control_gates(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.cx(0, 1)
circuit.ch(0, 1)
from qiskit import pulse
with pulse.build(name="cnot") as cx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("cx", [0, 1], cx_q01)
with pulse.build(name="ch") as ch_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("ch", [0, 1], ch_q01)
fname = "calibrations_with_control_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_swap_and_reset(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.swap(0, 1)
circuit.reset(0)
from qiskit import pulse
with pulse.build(name="swap") as swap_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("swap", [0, 1], swap_q01)
with pulse.build(name="reset") as reset_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("reset", [0], reset_q0)
fname = "calibrations_with_swap_and_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_rzz_and_rxx(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.rzz(pi, 0, 1)
circuit.rxx(pi, 0, 1)
from qiskit import pulse
with pulse.build(name="rzz") as rzz_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rzz", [0, 1], rzz_q01)
with pulse.build(name="rxx") as rxx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rxx", [0, 1], rxx_q01)
fname = "calibrations_with_rzz_and_rxx.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
circuit = QuantumCircuit(2, 3)
fname = "no_op_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
fname = "long_name.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_multi_underscore_reg_names(self):
"""Test that multi-underscores in register names display properly"""
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
fname = "multi_underscore_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "multi_underscore_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
fname = "reg_conditional.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_with_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=True."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_bundle.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_no_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=False."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_no_bundle.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
fname = "plot_partial_barrier.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("1")
# check the barriers plot properly when plot_barriers= True
fname = "plot_barriers_true.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "plot_barriers_false.png"
self.circuit_drawer(circuit, filename=fname2, plot_barriers=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
fname = "no_barriers.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_minus1(self):
"""Test to see that fold=-1 is no folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_minus1.png"
self.circuit_drawer(circuit, fold=-1, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_4(self):
"""Test to see that fold=4 is folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_4.png"
self.circuit_drawer(circuit, fold=4, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_big_gates(self):
"""Test large gates with params"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
fname = "big_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]])
fname = "cnot.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cz(self):
"""Test Z and Controlled-Z Gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.z(0)
circuit.cz(0, 1)
circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3])
circuit.append(ZGate().control(2), [1, 2, 3])
circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3])
fname = "cz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
fname = "pauli_clifford.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
fname = "creg_initial_true.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "creg_initial_false.png"
self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_r_gates(self):
"""Test all R gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
fname = "r_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ctrl_labels(self):
"""Test control labels"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cy(1, 0, label="Bottom Y label")
circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label")
circuit.ch(0, 1, label="Top H label")
circuit.append(
HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"),
[qr[1], qr[2], qr[3], qr[0]],
)
fname = "ctrl_labels.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
fname = "cswap_rzz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
fname = "ghz_to_gate.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
fname = "scale_default.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "scale_half.png"
self.circuit_drawer(circuit, filename=fname2, scale=0.5)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname3 = "scale_double.png"
self.circuit_drawer(circuit, filename=fname3, scale=2)
ratio3 = VisualTestUtilities._save_diff(
self._image_path(fname3),
self._reference_path(fname3),
fname3,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
self.assertGreaterEqual(ratio3, 0.9999)
def test_pi_param_expr(self):
"""Test pi in circuit with parameter expression."""
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
fname = "pi_in_param_expr.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
basis_gates=["id", "cx", "rz", "sx", "x"],
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
fname = "partial_layout.png"
self.circuit_drawer(transpiled, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
fname = "init_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_with_global_phase(self):
"""Tests with global phase"""
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
fname = "global_phase.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_alternative_colors(self):
"""Tests alternative color schemes"""
ratios = []
for style in ["iqx", "iqx-dark", "textbook"]:
with self.subTest(style=style):
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = f"{style}_color.png"
self.circuit_drawer(circuit, style={"name": style}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
ratios.append(ratio)
for ratio in ratios:
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
fname = "reverse_bits.png"
self.circuit_drawer(circuit, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bw(self):
"""Tests black and white style parameter"""
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.x(1)
circuit.sdg(2)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit.swap(1, 2)
circuit.measure_all()
fname = "bw.png"
self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_style(self):
"""Tests loading a user style"""
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.append(HGate(label="H2"), [1])
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.append(SGate(label="S1"), [4])
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = "user_style.png"
self.circuit_drawer(
circuit,
style={
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_subfont_change(self):
"""Tests changing the subfont size"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(0)
circuit.u(pi / 2, pi / 2, pi / 2, 1)
circuit.p(pi / 2, 2)
style = {"name": "iqx", "subfontsize": 11}
fname = "subfont.png"
self.circuit_drawer(circuit, style=style, filename=fname)
self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_meas_condition(self):
"""Tests measure with a condition"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
fname = "meas_condition.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits_condition(self):
"""Tests reverse_bits with a condition and gate above"""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
fname = "reverse_bits_cond_true.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "reverse_bits_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_style_custom_gates(self):
"""Tests style for custom gates"""
def cnotnot(gate_label):
gate_circuit = QuantumCircuit(3, name=gate_label)
gate_circuit.cnot(0, 1)
gate_circuit.cnot(0, 2)
gate = gate_circuit.to_gate()
return gate
q = QuantumRegister(3, name="q")
circuit = QuantumCircuit(q)
circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]])
circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]])
circuit.h(q[0])
fname = "style_custom_gates.png"
self.circuit_drawer(
circuit,
style={
"displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")},
"displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_6095(self):
"""Tests controlled-phase gate style
See https://github.com/Qiskit/qiskit-terra/issues/6095"""
circuit = QuantumCircuit(2)
circuit.cp(1.0, 0, 1)
circuit.h(1)
fname = "6095.png"
self.circuit_drawer(
circuit,
style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_1q_1c(self):
"""Tests q0-cr0 instruction on a circuit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Inst").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
fname = "instruction_1q_1c.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ1(self):
"""Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]])
fname = "instruction_3q_3c_circ1.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ2(self):
"""Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]])
fname = "instruction_3q_3c_circ2.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ3(self):
"""Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
cr3 = ClassicalRegister(2, "cr3")
circuit = QuantumCircuit(qr, cr, cr2, cr3)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]])
fname = "instruction_3q_3c_circ3.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_overwide_gates(self):
"""Test gates don't exceed width of default fold"""
circuit = QuantumCircuit(5)
initial_state = np.zeros(2**5)
initial_state[5] = 1
circuit.initialize(initial_state)
fname = "wide_params.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_one_bit_regs(self):
"""Test registers with only one bit display without number"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.h(0)
circuit.measure(0, 0)
fname = "one_bit_regs.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_ax_subplot(self):
"""Test for when user supplies ax for a subplot"""
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(6, 4))
fig.patch.set_facecolor("white")
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.plot([1, 2, 3])
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.cx(0, 1)
circuit.h(1)
circuit.cx(1, 2)
plt.close(fig)
fname = "user_ax.png"
self.circuit_drawer(circuit, ax=ax2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_figwidth(self):
"""Test style dict 'figwidth'"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.x(1)
circuit.cx(1, 2)
circuit.x(2)
fname = "figwidth.png"
self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_registerless_one_bit(self):
"""Test circuit with one-bit registers and registerless bits."""
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
fname = "registerless_one_bit.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
fname = "measure_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditions_measures_with_bits(self):
"""Test that gates with conditions and measures work with bits"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
fname = "measure_cond_bits_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_bits_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional_gates_right_of_measures_with_bits(self):
"""Test that gates with conditions draw to right of measures when same bit"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[1])
circuit.h(qr[1]).c_if(cr[1], 0)
circuit.h(qr[2]).c_if(cr[0], 0)
fname = "measure_cond_bits_right.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions work with bits reversed"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(2, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
fname = "cond_bits_reverse.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with conditions"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
fname = "sidetext_condition.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_with_conditions(self):
"""Test that gates with conditions draw correctly when folding"""
qr = QuantumRegister(3)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
fname = "fold_with_conditions.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
fname = "idle_wires_barrier.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_wire_order(self):
"""Test the wire_order option"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "cx")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
fname = "wire_order.png"
self.circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_barrier_label(self):
"""Test the barrier label"""
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
fname = "barrier_label.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_op(self):
"""Test the IfElseOp with if only"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "if_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op(self):
"""Test the IfElseOp with else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_textbook_style(self):
"""Test the IfElseOp with else in textbook style"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_textbook.png"
self.circuit_drawer(circuit, style="textbook", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_with_body(self):
"""Test the IfElseOp with adding a body manually"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.h(1)
circuit.measure(0, 1)
circuit.measure(1, 2)
circuit.x(2)
circuit.x(2, label="XLabel").c_if(cr, 2)
qr2 = QuantumRegister(3, "qr2")
qc2 = QuantumCircuit(qr2, cr)
qc2.x(1)
qc2.y(1)
qc2.z(0)
qc2.x(0, label="X1i").c_if(cr, 4)
circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2])
circuit.x(0, label="X1i")
fname = "if_else_body.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_nested(self):
"""Test the IfElseOp with complex nested if/else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_nested.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_wire_order(self):
"""Test the IfElseOp with complex nested if/else and wire_order"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_wire_order.png"
self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_fold(self):
"""Test the IfElseOp with complex nested if/else and fold"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_fold.png"
self.circuit_drawer(circuit, fold=7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_while_loop_op(self):
"""Test the WhileLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.measure(0, 2)
with circuit.while_loop((cr[0], 0)):
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
fname = "while_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_for_loop_op(self):
"""Test the ForLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_switch_case_op(self):
"""Test the SwitchCaseOp"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(3, 4, 5):
circuit.y(1)
circuit.y(0)
circuit.y(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
circuit.h(0)
fname = "switch_case.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
def speak(text):
from IPython.display import Javascript as js, clear_output
# Escape single quotes
text = text.replace("'", r"\'")
display(js(f'''
if(window.speechSynthesis) {{
var synth = window.speechSynthesis;
synth.speak(new window.SpeechSynthesisUtterance('{text}'));
}}
'''))
# Clear the JS so that the notebook doesn't speak again when reopened/refreshed
clear_output(False)
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main')
import sys
np.set_printoptions(threshold=sys.maxsize)
from qiskit import *
from matplotlib import pyplot as plt
backend = provider.get_backend('ibmq_armonk')
from qiskit import *
from qiskit.pulse import *
from qiskit.tools.monitor import job_monitor
qubit = 0
back_config = backend.configuration()
inst_sched_map = backend.defaults().instruction_schedule_map
meas_map_idx = None
for i, measure_group in enumerate(back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit])
pulse_sigma = 80
pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16)
drive_chan = DriveChannel(0)
def create_cal_circuits(amp):
sched = Schedule()
sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan)
measure = inst_sched_map.get('measure', qubits=[qubit])
sched+=measure << sched.duration
return sched
default_qubit_freq = backend.defaults().qubit_freq_est[0]
freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75)
sched_list = [create_cal_circuits(0.4)]*75
# sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list])
# sweep_job = backend.run(sweep_exp)
sweep_job = execute(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list])
job_monitor(sweep_job)
sweep_result = sweep_job.result()
sweep_values = []
for i in range(len(sweep_result.results)):
res = sweep_result.get_memory(i)*1e-14
sweep_values.append(res[qubit])
scale_factor = 1e+9
freq_list_scaled = freq_list/scale_factor
from scipy.optimize import curve_fit
def find_init_params(res_values):
est_baseline = np.mean(res_values)
est_slope = -5 if est_baseline-np.min(res_values) > 2 else 5
return [est_slope, 4.975, 1, est_baseline]
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
init_params = find_init_params(np.real(sweep_values)) # initial parameters for curve_fit
fit_params, y_fit = fit_function(freq_list_scaled,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
init_params
)
plt.scatter(freq_list_scaled, np.real(sweep_values), color='black')
plt.plot(freq_list_scaled, y_fit, color='red')
plt.xlim([min(freq_list_scaled), max(freq_list_scaled)])
# plt.ylim([-7,0])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
_, qubit_freq_new, _, _ = fit_params
qubit_freq_ground = qubit_freq_new*scale_factor
speak("The test program is done.")
print(f"The new qubit frequency is : {qubit_freq_ground} Hz")
#### Moving on to the Rabi experiments for 0->1 transition.
amp_list = np.linspace(0, 1.0, 75)
rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list]
# rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list))
# rabi_job = backend.run(rabi_exp)
rabi_job = execute(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list))
job_monitor(rabi_job)
rabi_results = rabi_job.result()
scale_factor = 1e-14
rabi_values = []
for i in range(75):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = np.real(baseline_remove(rabi_values))
fit_params, y_fit = fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
[5, 1, 1, -3])
drive_period = fit_params[2]
pi_amp_ground = drive_period/2
plt.scatter(amp_list, rabi_values, color='black')
plt.plot(amp_list, y_fit, color='red')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print(f"The calibrated pi amp is : {pi_amp_ground}")
speak("The test program is over. Have a look at it.")
from qiskit.pulse import library as pulse_lib
def get_pi_pulse_ground():
pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground)
return pulse
def get_zero_sched():
zero_sched = Schedule()
zero_sched += measure
return zero_sched
def get_one_sched():
one_sched = Schedule()
one_sched += Play(get_pi_pulse_ground(), drive_chan)
one_sched += measure << one_sched.duration
return one_sched
def IQ_plot(zero_data, one_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5
x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5
y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5
y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.xlim(x_min, x_max)
plt.ylim(y_min,y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
def get_job_data(job, average):
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
return result_data
discrim_01_sched_list = [get_zero_sched(), get_one_sched()]
discrim_job = execute(discrim_01_sched_list, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2)
job_monitor(discrim_job)
discrim_data = get_job_data(discrim_job, average=False)
zero_data = discrim_data[0]
one_data = discrim_data[1]
x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data)
discrim_job_0 = execute(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
job_monitor(discrim_job_0)
discrim_job_1 = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
job_monitor(discrim_job_1)
zero_data_sep = get_job_data(discrim_job_0, average=False)
one_data_sep = get_job_data(discrim_job_1, average=False)
x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep, one_data_sep)
discrim_01_sched_list_assemble = [get_zero_sched(), get_one_sched()]
discrim_exp = assemble(discrim_01_sched_list_assemble, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2)
discrim_job_assemble = backend.run(discrim_exp)
job_monitor(discrim_job_assemble)
discrim_data_assemble = get_job_data(discrim_job_assemble, average=False)
zero_data_asmbl = discrim_data_assemble[0]
one_data_asmbl = discrim_data_assemble[1]
x_min, x_max, y_min, y_max = IQ_plot(zero_data_asmbl, one_data_asmbl)
def zero_pulse_with_gap(gap):
gapped_sched = Schedule()
gapped_sched += measure << gap
return gapped_sched
discrim_exp_0 = assemble(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
# discrim_exp_0 = assemble(zero_pulse_with_gap(350), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
discrim_job_0_asmbl = backend.run(discrim_exp_0)
job_monitor(discrim_job_0_asmbl)
discrim_exp_1 = assemble(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
discrim_job_1_asmbl = backend.run(discrim_exp_1)
job_monitor(discrim_job_1_asmbl)
zero_data_sep_asmbl = get_job_data(discrim_job_0_asmbl, average=False)
one_data_sep_asmbl = get_job_data(discrim_job_1_asmbl, average=False)
x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep_asmbl, one_data_sep_asmbl)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
import sys
sys.path[1:1] = ["_common", "_common/qiskit"]
sys.path[1:1] = ["../../_common", "../../_common/qiskit"]
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import time
import math
import os
import numpy as np
np.random.seed(0)
import execute as ex
import metrics as metrics
from collections import defaultdict
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.circuit.library import HartreeFock as HF
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers import ActiveSpaceTransformer
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit.opflow import PauliTrotterEvolution, CircuitStateFn, Suzuki
from qiskit.opflow.primitive_ops import PauliSumOp
# Function that converts a list of single and double excitation operators to Pauli operators
def readPauliExcitation(norb, circuit_id=0):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/ansatzes/{norb}_qubit_{circuit_id}.txt')
with open(filename) as f:
data = f.read()
ansatz_dict = json.loads(data)
# initialize Pauli list
pauli_list = []
# current coefficients
cur_coeff = 1e5
# current Pauli list
cur_list = []
# loop over excitations
for ext in ansatz_dict:
if cur_coeff > 1e4:
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
elif abs(abs(ansatz_dict[ext]) - abs(cur_coeff)) > 1e-4:
pauli_list.append(PauliSumOp.from_list(cur_list))
cur_coeff = ansatz_dict[ext]
cur_list = [(ext, ansatz_dict[ext])]
else:
cur_list.append((ext, ansatz_dict[ext]))
# add the last term
pauli_list.append(PauliSumOp.from_list(cur_list))
# return Pauli list
return pauli_list
# Get the Hamiltonian by reading in pre-computed file
def ReadHamiltonian(nqubit):
# load pre-computed data
filename = os.path.join(os.getcwd(), f'../qiskit/Hamiltonians/{nqubit}_qubit.txt')
with open(filename) as f:
data = f.read()
ham_dict = json.loads(data)
# pauli list
pauli_list = []
for p in ham_dict:
pauli_list.append( (p, ham_dict[p]) )
# build Hamiltonian
ham = PauliSumOp.from_list(pauli_list)
# return Hamiltonian
return ham
def VQEEnergy(n_spin_orbs, na, nb, circuit_id=0, method=1):
'''
Construct a Qiskit circuit for VQE Energy evaluation with UCCSD ansatz
:param n_spin_orbs:The number of spin orbitals
:return: return a Qiskit circuit for this VQE ansatz
'''
# allocate qubits
num_qubits = n_spin_orbs
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name="main")
# number of alpha spin orbitals
norb_a = int(n_spin_orbs / 2)
# number of beta spin orbitals
norb_b = norb_a
# construct the Hamiltonian
qubit_op = ReadHamiltonian(n_spin_orbs)
# initialize the HF state
qc = HartreeFock(n_spin_orbs, na, nb)
# form the list of single and double excitations
singles = []
doubles = []
for occ_a in range(na):
for vir_a in range(na, norb_a):
singles.append((occ_a, vir_a))
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
singles.append((occ_b, vir_b))
for occ_a in range(na):
for vir_a in range(na, norb_a):
for occ_b in range(norb_a, norb_a+nb):
for vir_b in range(norb_a+nb, n_spin_orbs):
doubles.append((occ_a, vir_a, occ_b, vir_b))
# get cluster operators in Paulis
pauli_list = readPauliExcitation(n_spin_orbs, circuit_id)
# loop over the Pauli operators
for index, PauliOp in enumerate(pauli_list):
# get circuit for exp(-iP)
cluster_qc = ClusterOperatorCircuit(PauliOp)
# add to ansatz
qc.compose(cluster_qc, inplace=True)
# method 2, only compute the last term in the Hamiltonian
if method == 2:
# last term in Hamiltonian
qc_with_mea, is_diag = ExpectationCircuit(qc, qubit_op[1], num_qubits)
# return the circuit
return qc_with_mea
# now we need to add the measurement parts to the circuit
# circuit list
qc_list = []
diag = []
off_diag = []
for p in qubit_op:
# get the circuit with expectation measurements
qc_with_mea, is_diag = ExpectationCircuit(qc, p, num_qubits)
# add to circuit list
qc_list.append(qc_with_mea)
# diagonal term
if is_diag:
diag.append(p)
# off-diagonal term
else:
off_diag.append(p)
return qc_list
def ClusterOperatorCircuit(pauli_op):
# compute exp(-iP)
exp_ip = pauli_op.exp_i()
# Trotter approximation
qc_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=1, reps=1)).convert(exp_ip)
# convert to circuit
qc = qc_op.to_circuit()
# return this circuit
return qc
# Function that adds expectation measurements to the raw circuits
def ExpectationCircuit(qc, pauli, nqubit, method=1):
# a flag that tells whether we need to perform rotation
need_rotate = False
# copy the unrotated circuit
raw_qc = qc.copy()
# whether this term is diagonal
is_diag = True
# primitive Pauli string
PauliString = pauli.primitive.to_list()[0][0]
# coefficient
coeff = pauli.coeffs[0]
# basis rotation
for i, p in enumerate(PauliString):
target_qubit = nqubit - i - 1
if (p == "X"):
need_rotate = True
is_diag = False
raw_qc.h(target_qubit)
elif (p == "Y"):
raw_qc.sdg(target_qubit)
raw_qc.h(target_qubit)
need_rotate = True
is_diag = False
# perform measurements
raw_qc.measure_all()
# name of this circuit
raw_qc.name = PauliString + " " + str(np.real(coeff))
return raw_qc, is_diag
# Function that implements the Hartree-Fock state
def HartreeFock(norb, na, nb):
# initialize the quantum circuit
qc = QuantumCircuit(norb)
# alpha electrons
for ia in range(na):
qc.x(ia)
# beta electrons
for ib in range(nb):
qc.x(ib+int(norb/2))
# return the circuit
return qc
import json
from qiskit import execute, Aer
backend = Aer.get_backend("qasm_simulator")
precalculated_data = {}
def run(min_qubits=4, max_qubits=4, max_circuits=3, num_shots=4092 * 2**8, method=2):
print(f"... using circuit method {method}")
# validate parameters (smallest circuit is 4 qubits)
max_qubits = max(4, max_qubits)
min_qubits = min(max(4, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
if method == 1: max_circuits = 1
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for input_size in range(min_qubits, max_qubits + 1, 2):
# determine the number of circuits to execute fo this group
num_circuits = max_circuits
num_qubits = input_size
# decides number of electrons
na = int(num_qubits/4)
nb = int(num_qubits/4)
# decides number of unoccupied orbitals
nvira = int(num_qubits/2) - na
nvirb = int(num_qubits/2) - nb
# determine the size of t1 and t2 amplitudes
t1_size = na * nvira + nb * nvirb
t2_size = na * nb * nvira * nvirb
# random seed
np.random.seed(0)
# create the circuit for given qubit size and simulation parameters, store time metric
ts = time.time()
# circuit list
qc_list = []
# method 1 (default)
if method == 1:
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct all circuits
qc_list = VQEEnergy(num_qubits, na, nb, 0, method)
else:
# loop over circuits
for circuit_id in range(num_circuits):
# sample t1 and t2 amplitude
t1 = np.random.normal(size=t1_size)
t2 = np.random.normal(size=t2_size)
# construct circuit
qc_single = VQEEnergy(num_qubits, na, nb, circuit_id, method)
qc_single.name = qc_single.name + " " + str(circuit_id)
# add to list
qc_list.append(qc_single)
print(f"************\nExecuting VQE with num_qubits {num_qubits}")
for qc in qc_list:
# get circuit id
if method == 1:
circuit_id = qc.name.split()[0]
else:
circuit_id = qc.name.split()[2]
# collapse the sub-circuits used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
job = execute(qc, backend, shots=num_shots)
# executation result
result = job.result()
# get measurement counts
counts = result.get_counts(qc)
# initialize empty dictionary
dist = {}
for key in counts.keys():
prob = counts[key] / num_shots
dist[key] = prob
# add dist values to precalculated data for use in fidelity calculation
precalculated_data[f"{circuit_id}"] = dist
with open(f'precalculated_data_qubit_{num_qubits}_method1.json', 'w') as f:
f.write(json.dumps(
precalculated_data,
sort_keys=True,
indent=4,
separators=(',', ': ')
))
run()
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 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.
"""Test Classical Imaginary Evolver."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import data, ddt, unpack
import numpy as np
from qiskit_algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
from qiskit_algorithms import SciPyImaginaryEvolver
from qiskit.opflow import PauliSumOp
@ddt
class TestSciPyImaginaryEvolver(QiskitAlgorithmsTestCase):
"""Test SciPy Imaginary Evolver."""
def create_hamiltonian_lattice(self, num_sites: int) -> SparsePauliOp:
"""Creates an Ising Hamiltonian on a lattice."""
j_const = 0.1
g_const = -1.0
zz_op = ["I" * i + "ZZ" + "I" * (num_sites - i - 2) for i in range(num_sites - 1)]
x_op = ["I" * i + "X" + "I" * (num_sites - i - 1) for i in range(num_sites)]
return SparsePauliOp(zz_op) * j_const + SparsePauliOp(x_op) * g_const
@data(
(Statevector.from_label("0"), 100, SparsePauliOp("X"), Statevector.from_label("-")),
(Statevector.from_label("0"), 100, SparsePauliOp("-X"), Statevector.from_label("+")),
)
@unpack
def test_evolve(
self,
initial_state: Statevector,
tau: float,
hamiltonian: SparsePauliOp,
expected_state: Statevector,
):
"""Initializes a classical imaginary evolver and evolves a state to find the ground state.
It compares the solution with the first eigenstate of the hamiltonian.
"""
expected_state_matrix = expected_state.data
evolution_problem = TimeEvolutionProblem(hamiltonian, tau, initial_state)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=300)
result = classic_evolver.evolve(evolution_problem)
with self.subTest("Amplitudes"):
np.testing.assert_allclose(
np.absolute(result.evolved_state.data),
np.absolute(expected_state_matrix),
atol=1e-10,
rtol=0,
)
with self.subTest("Phases"):
np.testing.assert_allclose(
np.angle(result.evolved_state.data),
np.angle(expected_state_matrix),
atol=1e-10,
rtol=0,
)
@data(
(
Statevector.from_label("0" * 5),
SparsePauliOp.from_sparse_list([("X", [i], 1) for i in range(5)], num_qubits=5),
5,
),
(Statevector.from_label("0"), SparsePauliOp("X"), 1),
)
@unpack
def test_observables(
self, initial_state: Statevector, hamiltonian: SparsePauliOp, nqubits: int
):
"""Tests if the observables are properly evaluated at each timestep."""
time_ev = 5.0
observables = {"Energy": hamiltonian, "Z": SparsePauliOp("Z" * nqubits)}
evolution_problem = TimeEvolutionProblem(
hamiltonian, time_ev, initial_state, aux_operators=observables
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=300)
result = classic_evolver.evolve(evolution_problem)
z_mean, z_std = result.observables["Z"]
time_vector = result.times
expected_z = 1 / (np.cosh(time_vector) ** 2 + np.sinh(time_vector) ** 2)
expected_z_std = np.zeros_like(expected_z)
np.testing.assert_allclose(z_mean, expected_z**nqubits, atol=1e-10, rtol=0)
np.testing.assert_allclose(z_std, expected_z_std, atol=1e-10, rtol=0)
def test_quantum_circuit_initial_state(self):
"""Tests if the system can be evolved with a quantum circuit as an initial state."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, range(1, 3))
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3), time=1.0, initial_state=qc
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
result = classic_evolver.evolve(evolution_problem)
self.assertEqual(result.evolved_state, Statevector(qc))
def test_paulisumop_hamiltonian(self):
"""Tests if the hamiltonian can be a PauliSumOp"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp.from_list(
[
("XI", 1),
("IX", 1),
]
)
observable = PauliSumOp.from_list([("ZZ", 1)])
evolution_problem = TimeEvolutionProblem(
hamiltonian=hamiltonian,
time=1.0,
initial_state=Statevector.from_label("00"),
aux_operators={"ZZ": observable},
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
result = classic_evolver.evolve(evolution_problem)
expected = 1 / (np.cosh(1.0) ** 2 + np.sinh(1.0) ** 2)
np.testing.assert_almost_equal(result.aux_ops_evaluated["ZZ"][0], expected**2)
def test_error_time_dependency(self):
"""Tests if an error is raised for a time dependent Hamiltonian."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X" * 3),
time=1.0,
initial_state=Statevector.from_label("0" * 3),
t_param=0,
)
classic_evolver = SciPyImaginaryEvolver(num_timesteps=5)
with self.assertRaises(ValueError):
classic_evolver.evolve(evolution_problem)
def test_no_time_steps(self):
"""Tests if the evolver handles some edge cases related to the number of timesteps."""
evolution_problem = TimeEvolutionProblem(
hamiltonian=SparsePauliOp("X"),
time=1.0,
initial_state=Statevector.from_label("0"),
aux_operators={"Energy": SparsePauliOp("X")},
)
with self.subTest("0 timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=0)
classic_evolver.evolve(evolution_problem)
with self.subTest("1 timestep"):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=1)
result = classic_evolver.evolve(evolution_problem)
np.testing.assert_equal(result.times, np.array([0.0, 1.0]))
with self.subTest("Negative timesteps"):
with self.assertRaises(ValueError):
classic_evolver = SciPyImaginaryEvolver(num_timesteps=-5)
classic_evolver.evolve(evolution_problem)
if __name__ == "__main__":
unittest.main()
|
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, Updated March 2022
@author: hassi
"""
# https://www.qiskit.org/documentation/_modules/qiskit/algorithms/factorizers/shor.html
from qiskit import Aer, IBMQ
from qiskit.algorithms import Shor
from qiskit.utils import QuantumInstance
import time
global backend, shots
def display_shor(N, backend, shots):
print("Building Shor circuit...")
instance = QuantumInstance(backend=backend, shots=shots)
shors = Shor(quantum_instance = instance)
shor_circuit = shors.construct_circuit(N)
print("Shor circuit for: ",str(N) )
print(shor_circuit)
print("Decomposed Shor circuit for: ",str(N) )
print(shor_circuit.decompose())
print("Circuit data\n\nDepth: ",shor_circuit.depth(),"\nWidth: ",shor_circuit.width(),"\nSize: ",shor_circuit.size())
def run_shor(N, backend, shots):
print("Running Shor's algorithm for",str(N),"on", backend,"...")
instance = QuantumInstance(backend=backend, shots=shots)
shors = Shor(quantum_instance = instance)
results=shors.factor(N)
if results.factors==[]:
print("No prime factors: ",str(N),"=",str(N))
elif isinstance(results.factors[0],int):
print("Prime factors: ",str(N),"=",results.factors[0],"^ 2")
else:
print("Prime factors: ",str(N),"=",results.factors[0][0],"*",results.factors[0][1])
def main():
number=1
print("\nCh 11: Shor's algorithm with Aqua")
print("---------------------------------")
while number!=0:
number=int(input("\nEnter an odd number N >1 (0 to exit):\n"))
if number<=64: #Arbitrarily set upper limit for local simulator
print("Getting local simulator backend...")
backend = Aer.get_backend('qasm_simulator')
shots = 1024
else:
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
print("Getting IBM Q simulator backend...")
backend = provider.get_backend('ibmq_qasm_simulator')
if number>1 and number % 2>0:
type=input("Enter R to run the Shor algorithm, D to display the circuit.\n")
start_time=time.time()
if type.upper()=="D":
display_shor(number, backend, shots)
elif type.upper()=="R":
run_shor(number, backend, shots)
elif type.upper() in ["RD","DR"]:
display_shor(number, backend, shots)
run_shor(number, backend, shots)
end_time=time.time()
print("Elapsed time: ","%.2f" % (end_time-start_time), "s")
else:
print("The number must be odd and larger than 1.")
if __name__ == '__main__':
main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/qwqmlf/qwgc
|
qwqmlf
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
from qiskit import QuantumCircuit
# ## Create Circuit
# In[2]:
def createInputCircuit(data):
qubits_num = len(data)
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
return qcircuit
# In[3]:
def createModelCircuit(params):
qubits_num = len(params[0])
qcircuit = QuantumCircuit(qubits_num, qubits_num)
qubits = qcircuit.qubits
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
for i in range(qubits_num - 1):
qcircuit.cz(qubits[i], qubits[i + 1])
qcircuit.cz(qubits[0], qubits[qubits_num - 1])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
# In[4]:
def createCircuit(params, data):
input_circuit = createInputCircuit(data)
model_circuit = createModelCircuit(params)
full_circuit = input_circuit.compose(model_circuit)
return full_circuit
# ## Create Noisy Circuit
# In[8]:
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.utils import insert_noise
from qiskit.providers.aer.noise import pauli_error, depolarizing_error
# In[9]:
def createNoiseModel(p, errorType):
# QuantumError objects
if errorType == 'bit_flip':
error = pauli_error([('X', p), ('I', 1 - p)])
elif errorType == 'phase_flip':
error = pauli_error([('Z', p), ('I', 1 - p)])
elif errorType == 'depolarizing':
error = depolarizing_error(p, num_qubits=1)
## two-qubits quantumError objects
if errorType == 'depolarizing':
error_2qubits = depolarizing_error(p, num_qubits=2)
else:
error_2qubits = error.tensor(error)
# Add errors to noise model
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ['u3'])
noise_model.add_all_qubit_quantum_error(error_2qubits, ['cz'])
return noise_model
# In[10]:
def createNoisyModelCircuit(params, p, errorType):
noise_model = createNoiseModel(p, errorType)
model_circuit = createModelCircuit(params)
return insert_noise(model_circuit, noise_model)
# In[12]:
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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 Qiskit's QuantumCircuit class for multiple registers."""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.circuit.exceptions import CircuitError
class TestCircuitMultiRegs(QiskitTestCase):
"""QuantumCircuit Qasm tests."""
def test_circuit_multi(self):
"""Test circuit multi regs declared at start."""
qreg0 = QuantumRegister(2, "q0")
creg0 = ClassicalRegister(2, "c0")
qreg1 = QuantumRegister(2, "q1")
creg1 = ClassicalRegister(2, "c1")
circ = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ.compose(meas)
circ2 = QuantumCircuit()
circ2.add_register(qreg0)
circ2.add_register(qreg1)
circ2.add_register(creg0)
circ2.add_register(creg1)
circ2.x(qreg0[1])
circ2.x(qreg1[0])
meas2 = QuantumCircuit()
meas2.add_register(qreg0)
meas2.add_register(qreg1)
meas2.add_register(creg0)
meas2.add_register(creg1)
meas2.measure(qreg0, creg0)
meas2.measure(qreg1, creg1)
qc2 = circ2.compose(meas2)
dag_qc = circuit_to_dag(qc)
dag_qc2 = circuit_to_dag(qc2)
dag_circ2 = circuit_to_dag(circ2)
dag_circ = circuit_to_dag(circ)
self.assertEqual(dag_qc, dag_qc2)
self.assertEqual(dag_circ, dag_circ2)
def test_circuit_multi_name_collision(self):
"""Test circuit multi regs, with name collision."""
qreg0 = QuantumRegister(2, "q")
qreg1 = QuantumRegister(3, "q")
self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
import matplotlib.pyplot as plt
import numpy as np
from VehicleRouting.standard.factories.VehicleRoutingProblemFactories import Experiment1VehicleRoutingProblemFactory
from VehicleRouting.standard.problems.VehicleRoutingProblem import VehicleRoutingProblem
from VehicleRouting.functions.functionsVehicleRouting import get_execute_circuit
from VehicleRouting.functions.functionsVehicleRouting import create_qaoa_circuit
from qiskit import Aer
from qiskit.visualization import plot_histogram
from scipy.optimize import minimize
# Setting Up Graph
from VehicleRouting.standard.plotter.GraphPlotter import GraphPlotter
from VehicleRouting.standard.concretization.GraphStrategy import SimpleExperimentProblemStrategy
problem_factory = Experiment1VehicleRoutingProblemFactory()
problem = VehicleRoutingProblem(problem_factory)
plotter = GraphPlotter(problem)
plotter.plot_problem()
graph = problem.get_graph()
# Returns a function to be optimized
p = 2
expectation = get_execute_circuit(graph)
# Optimize
initial_parameter = np.ones(2*p)
optimization_method = 'COBYLA'
optimization_object = minimize(expectation, initial_parameter, method=optimization_method)
print(optimization_object)
# Get a simulator
backend = Aer.get_backend('aer_simulator')
backend.shots = 2 ^ 12
# Create Circuit with Optimized Parameters
optimized_parameters = optimization_object.x
qc_res = create_qaoa_circuit(graph, optimized_parameters)
qc_res.draw(output="mpl")
# Run simulation with optimised parameters
counts = backend.run(qc_res, seed_simulator=10).result().get_counts()
print(counts)
# Plot Histogram
plot_histogram(counts)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.