repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import numpy as np
import qiskit
from dc_qiskit_algorithms import UniformRotationGate
from qiskit.circuit import Parameter
from qiskit.circuit.library import U1Gate
from scipy import sparse
LOG = logging.getLogger(__name__)
def apply_initial(value: float, scaling_factor: Parameter) -> qiskit.QuantumCircuit:
"""
This function initializes the circuit using Proposition 1 of the paper:
First we need a Hadamard and then we rotate by the value * scaling factor * 2
with the R_z rotation.
:param value: The initial value
:param scaling_factor: The scaling factor to be used when computing the characteristic function
:return: The initial quantum circuit with the data system only
"""
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_data)
# BY Proposition 1 we need to start in a superposition state
qc.h(qreg_data)
# Then the initial rotation
# qc.append(RZGate(2*scaling_factor * value), qreg_data)
qc.u1(scaling_factor * value, qreg_data)
return qc
def apply_level(level: int, realizations: np.array, scaling_factor: Parameter, with_debug_circuit: bool = False, **kwargs) -> qiskit.QuantumCircuit:
k, = realizations.shape
qubits_k = int(np.ceil(np.log2(k)))
qc = qiskit.QuantumCircuit(name=f'level_{level}')
qreg_index = qiskit.QuantumRegister(qubits_k, f'level_{level}')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_index)
qc.add_register(qreg_data)
alpha = sparse.dok_matrix([realizations]).transpose()
if with_debug_circuit:
LOG.debug(f"Will add a controlled rotations with u1({scaling_factor} * {realizations})")
for (i, j), angle in alpha.items():
qc.append(
U1Gate(1.0 * scaling_factor * angle).control(num_ctrl_qubits=qubits_k, ctrl_state=int(i)),
list(qreg_index) + list(qreg_data)
)
else:
LOG.debug(f"Will add a uniform rotation gate with u1({scaling_factor} * {realizations})")
qc.append(UniformRotationGate(lambda theta: U1Gate(scaling_factor * theta), alpha), list(qreg_index) + list(qreg_data))
return qc
def apply_level_two_realizations(level: int, realizations: np.array, scaling_factor: Parameter, **kwargs) -> qiskit.QuantumCircuit:
k, = realizations.shape
assert k == 2
qubits_k = int(np.ceil(np.log2(k)))
qc = qiskit.QuantumCircuit(name=f'level_{level}')
qreg_index = qiskit.QuantumRegister(qubits_k, f'level_{level}')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_index)
qc.add_register(qreg_data)
x_l1 = realizations[0]
x_l2 = realizations[1]
qc.cu1(theta=scaling_factor * x_l2, control_qubit=qreg_index, target_qubit=qreg_data)
qc.x(qreg_index)
qc.cu1(theta=scaling_factor * x_l1, control_qubit=qreg_index, target_qubit=qreg_data)
qc.x(qreg_index)
return qc
def x_measurement() -> qiskit.QuantumCircuit:
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
creg_data = qiskit.ClassicalRegister(1, 'output')
qc.add_register(qreg_data)
qc.add_register(creg_data)
qc.h(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
def y_measurement() -> qiskit.QuantumCircuit:
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
creg_data = qiskit.ClassicalRegister(1, 'output')
qc.add_register(qreg_data)
qc.add_register(creg_data)
qc.z(qreg_data)
qc.s(qreg_data)
qc.h(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import random
import matplotlib.pyplot as plt
def generate_n_bit_inputs(n):
"""Generate all possible n-bit inputs."""
return [bin(i)[2:].zfill(n) for i in range(2**n)]
def constant_function(value):
"""Returns a constant function that always returns the given value."""
return lambda x: value
def balanced_function(n):
"""Returns a balanced function for n-bit inputs."""
inputs = generate_n_bit_inputs(n)
half = len(inputs) // 2
random.shuffle(inputs)
lookup = {x: 0 if i < half else 1 for i, x in enumerate(inputs)}
return lambda x: lookup[x]
def determine_function_type(f, n):
"""Determine if the function f is constant or balanced."""
inputs = generate_n_bit_inputs(n)
outputs = [f(x) for x in inputs]
unique_outputs = set(outputs)
if len(unique_outputs) == 1:
return "Constant"
elif outputs.count(0) == outputs.count(1):
return "Balanced"
else:
return "Unknown"
def plot_function(f, n, title):
"""Plot the function outputs for all n-bit inputs."""
inputs = generate_n_bit_inputs(n)
outputs = [f(x) for x in inputs]
# Convert binary inputs to integers for plotting
x = [int(i, 2) for i in inputs]
y = outputs
plt.figure(figsize=(10, 5))
plt.scatter(x, y, c='blue')
plt.title(title)
plt.xlabel('Input (as integer)')
plt.ylabel('Output')
plt.xticks(range(2**n))
plt.yticks([0, 1])
plt.grid(True)
plt.show()
# Define n
n = 3
# Create a constant function that always returns 1
const_func = constant_function(1)
print("Constant Function Test:")
print(f"The function is: {determine_function_type(const_func, n)}")
plot_function(const_func, n, "Constant Function (Always 1)")
# Create a balanced function for n-bit inputs
bal_func = balanced_function(n)
print("\nBalanced Function Test:")
print(f"The function is: {determine_function_type(bal_func, n)}")
plot_function(bal_func, n, "Balanced Function")
# useful additional packages
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
n = 13 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.id(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
djCircuit.draw(output='mpl',scale=0.5)
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
"""Performance Analysis of 3 Qubit Code under Bit Flip Error"""
import noise
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister
from qiskit import Aer, execute
from qiskit.quantum_info import partial_trace, state_fidelity
from qiskit.quantum_info import DensityMatrix, Kraus
from qiskit.visualization import plot_histogram, plot_bloch_vector
from three_qubit_code import ThreeQubitCode
# Parameters
error_prob = 0.05
theta = np.pi/3
phi = np.pi/4
# Initialize error correcting circuit, backend and noise model
qasm = Aer.get_backend('qasm_simulator')
svsm = Aer.get_backend('statevector_simulator')
unit = Aer.get_backend('unitary_simulator')
noise_model = noise.bit_flip_noise(error_prob)
qecc = ThreeQubitCode()
# Visualize parameters
print(noise_model)
qecc.visualize()
# Define test circuit and input state
output = ClassicalRegister(3)
circ = QuantumCircuit(qecc.code, qecc.syndrm, output)
circ.ry(theta, qecc.code[0])
circ.rz(phi, qecc.code[0])
plot_bloch_vector([np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi), np.cos(theta)], title="Input State")
plt.show()
# Define final measurement circuit
meas = QuantumCircuit(qecc.code, qecc.syndrm, output)
meas.measure(qecc.code, output)
# QASM simulation w/o error correction
job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + meas, backend=qasm, noise_model=noise_model,
basis_gates=noise_model.basis_gates)
counts_noisy = job.result().get_counts()
# QASM simulation with error correction
job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_model,
basis_gates=noise_model.basis_gates)
counts_corrected = job.result().get_counts()
# Plot QASM simulation data
plot_histogram([counts_noisy, counts_corrected],
title='3-Qubit Error Correction $(P_{error} = ' + str(error_prob) + ')$',
legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False)
plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15)
plt.show()
# Initialize fidelity simulation objects
job = execute(circ + qecc.encoder_ckt, backend=svsm)
init_state = DensityMatrix(job.result().get_statevector())
job = execute(qecc.syndrome_ckt, backend=unit)
syndrome_op = Kraus(job.result().get_unitary())
# Initialize fidelity simulation parameters
p_error = [0.05 * i for i in range(11)]
f1 = []
f2 = []
# Evolve initial state
for p in p_error:
# Build noise channel
bit_flip_channel = Kraus([[[0, np.sqrt(p)],
[np.sqrt(p), 0]],
[[np.sqrt(1-p), 0],
[0, np.sqrt(1-p)]]])
bit_flip_channel = bit_flip_channel.tensor(bit_flip_channel).tensor(bit_flip_channel)
bit_flip_channel = bit_flip_channel.expand(Kraus(np.eye(2))).expand(Kraus(np.eye(2)))
# Apply channels
corrupted_state = DensityMatrix(init_state.evolve(bit_flip_channel))
corrected_state = DensityMatrix(corrupted_state.evolve(syndrome_op))
corrected_state = DensityMatrix(corrected_state.evolve(qecc.correction_ckt))
# Trace out syndrome
ini = DensityMatrix(partial_trace(init_state, [3, 4]))
corrupted_state = DensityMatrix(partial_trace(corrupted_state, [3, 4]))
corrected_state = DensityMatrix(partial_trace(corrected_state, [3, 4]))
# Record results
f1.append(state_fidelity(ini, corrupted_state))
f2.append(state_fidelity(ini, corrected_state))
# Plot fidelity
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.plot(p_error, f1, label='w/o code')
ax.plot(p_error, f2, label='with code')
ax.set_title("$Fidelity$ vs $P_{error}$")
ax.set_xlabel('$P_{error}$')
ax.set_ylabel('$Fidelity$')
ax.set_ylabel('$Fidelity$')
ax.legend()
plt.xlim(0, 0.5)
plt.ylim(0, 1)
plt.grid()
plt.show()
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend("aer_simulator")
qc = QuantumCircuit(2)
qc.cx(0, 1)
display(qc.draw("mpl"))
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as Target) = }"))
|
https://github.com/rochisha0/quantum-ugly-duckling
|
rochisha0
|
#importing libraries
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, IBMQ
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
provider = IBMQ.load_account()
backend = provider.backends.ibmqx2
real_circ = QuantumCircuit(3, 3)
for i in range(200):
real_circ.u3(0,0,0,0)
real_circ.u3(0,0,0,1)
real_circ.u3(0,0,0,2)
real_circ.cx(0,1)
real_circ.cx(1,2)
real_circ.cx(2,0)
real_circ.barrier()
real_circ.measure([0, 1, 2], [0, 1, 2])
job_exp = execute(real_circ, backend=backend, shots=8192)
print(job_exp.job_id())
job_monitor(job_exp)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(real_circ)
print(exp_measurement_result)
plot_histogram(exp_measurement_result, color='midnightblue', title="NQRNG result on IBM Yorktown backend")
backend = provider.backends.ibmqx2
hada= QuantumCircuit(3, 3)
hada.h(0)
hada.h(1)
hada.h(2)
hada.measure([0, 1, 2], [0, 1, 2])
job_exp = execute(hada, backend=backend, shots=8192)
print(job_exp.job_id())
from qiskit.tools.monitor import job_monitor
job_monitor(job_exp)
exp_result = job_exp.result()
exp_measurement_result_hada = exp_result.get_counts(hada)
print(exp_measurement_result_hada)
plot_histogram(exp_measurement_result_hada, color='midnightblue', title="QRNS result on IBM Yorktown backend")
plot_histogram(exp_measurement_result_hada, color='midnightblue', title="QRNG result on IBM Yorktown backend")
plot_histogram(exp_measurement_result, color='midnightblue', title="NQRNG result on IBM Yorktown backend")
hada.draw('mpl')
backend = provider.backends.ibmqx2
real_circ = QuantumCircuit(3, 3)
real_circ.u3(0,0,0,0)
real_circ.u3(0,0,0,1)
real_circ.u3(0,0,0,2)
real_circ.cx(0,1)
real_circ.cx(1,2)
real_circ.cx(2,0)
real_circ.measure([0, 1, 2], [0, 1, 2])
job_exp = execute(real_circ, backend=backend, shots=8192)
print(job_exp.job_id())
job_monitor(job_exp)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(real_circ)
print(exp_measurement_result)
plot_histogram(exp_measurement_result, color='midnightblue', title="Basic circuit on IBM Yorktown backend")
real_circ.draw('mpl')
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
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-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/QuCO-CSAM/Solving-Combinatorial-Optimisation-Problems-Using-Quantum-Algorithms
|
QuCO-CSAM
|
# Important libraries and modules
import numpy as np
from itertools import permutations
import gzip
from qiskit import*
import time
from qiskit.aqua.algorithms import VQE
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import IBMQ
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.optimization.applications.ising.tsp import TspData
import qiskit.optimization.applications.ising.tsp as tsp
from qiskit.circuit.library import TwoLocal
from qiskit.circuit.library import RealAmplitudes
# # Load account from disk
IBMQ.load_account()
IBMQ.providers()
def readInData():
"""
Output G : N by N distance matrix from Matrices1a.txt file.
"""
G = []
p = [3, 4,5,6,7,8,9,10,11]
q = [i**(2) for i in p ]
m = 0
v = open("Matrices.txt" , "r")
w = v.read().split()
for i in range (len(w)):
w[i] = int(float(w[i]))
for i in range (len(q)):
G.append(np.reshape(w[m:m+q[i]] , (p[i] , p[i])))
m = m + q[i]
return G
distanceMatrix = readInData() #Array of different sized matrices
def determineIfFeasible(result):
"""
Determines if eigenstate is feasible or infeasible.
Output: arr = Infeasible if eiegenstate is infeasible or arr = binary array of feasible solution
"""
data = sorted(result['eigenstate'].items(), key=lambda item: item[1])[::-1]
for i in range(len(data)):
a = tsp.tsp_feasible(data[i][0])
arr = 'Infeasible'
if a == True:
b = str(data[i][0])
arr = [b , data[i][1]]
break
return arr
def optimal(a,b,c,f,u):
"""
Read in data of initial optimal point that will be used in the quantum algorithm
"""
openfile = open("optimal.txt" , "r")
readFile = openfile.read().split()
t = []
for i in readFile:
if i != ',':
q = len(i)
t.append(float(i[0:q-1]))
v, r, o, d, z = np.array(t[0:a]), np.array(t[a:a+b]), np.array(t[a+b : a+b+c]), np.array(t[a+b+c:a+b+c+f]), np.array(t[a+b+c+f:a+b+c+f+u])
return [v,r,o,d,z]
R = optimal(54,96,100,216,294) #Array of corresponding initial points
def variationalQuantumEigensolver(numIter,numShots,distanceMatrix, varForm, initialPoint, deviceName):
"""
Implementation of the VQE
Output: classial TSP solution (total length of tour) and time taken to execute algorithm
"""
# Mappining of problem to ising hamiltonian
x = TspData('tmp',len(matrix),np.zeros((3,3)),distanceMatrix)
qubitOp ,offset = tsp.get_operator(x)
seed = 10598
# Generate a circuit
spsa = SPSA(maxiter = numIter)
if varForm == 'vf1':
ry = RealAmplitudes(qubitOp.num_qubits, entanglement='linear')
elif varForm == 'vf2':
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
runVqe = VQE(qubitOp, ry, spsa,include_custom=True, initial_point = initialPoint)
my_provider = IBMQ.get_provider(ibm_hub) #Replace ibm_hub with appropriate qiskit hub name
device = my_provider.get_backend(deviceName) # deviceName is the Device of IBM quantum device in a string
quantum_instance = QuantumInstance(device, seed_simulator=seed, seed_transpiler=seed,shots = numShots,
skip_qobj_validation = False)
result = runVqe.run(quantum_instance)
#Convert quantum result into its classical form and determine if feasible or infeasible
answer = determineIfFeasible(result)
if answer == 'Infeasible':
solution = -1
else:
binarry = [int(p) for p in answer[0]]
route = tsp.get_tsp_solution(binarry)
solution = tsp.tsp_value(route, distanceMatrix)
return solution, result['optimizer_time']
## Example for 3 by 3 instance implemented using VQE:
numIter = 1
numShots = 1024
distanceMatrix = distanceMatrix[0]
varForm = 'vf1' #vf1 indicates the RealAmplitude form
deviceName = 'ibmq_cambridge'
initialPoint = R[0]
finalResult = variationalQuantumEigensolver(numIter,numShots, distanceMatrix, varForm, initialPoint, deviceName)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
result = backend.run(qc, shots = 8192).result()
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
from qiskit import IBMQ
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
#provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
# Include matplot lib inline plotting for graphical output and plotting
%matplotlib inline
from byskit import byskit,gen_random_weights
n_parent = 2
n_child = 3
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
# Trying to get results out
results = b.execute_circ().result()
# Import histogram visualisation tool and plot results
from qiskit.tools.visualization import plot_histogram
plot_histogram(results.get_counts(b.circ))
n_parent = 2
n_child = 4
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ().result()
plot_histogram(results.get_counts(b.circ))
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
# Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv
module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages"))
if module_path not in sys.path:
sys.path.append(module_path)
import c2qa
from IPython.display import HTML
import qiskit
import qiskit.visualization
from matplotlib import pyplot as plt
import numpy as np
n = 4
qreg = c2qa.QumodeRegister(1, num_qubits_per_qumode=n)
creg = qiskit.ClassicalRegister(n)
circuit = c2qa.CVCircuit(qreg, creg, probe_measure=True)
#creating a coherent state with λ = (1+1i) using the displacement operator.
#coherent states are sometimes referred to as "displaced ground states"
Lambda = 1+1j
circuit.cv_d(Lambda, qreg[0])
state, _, _ = c2qa.util.simulate(circuit)
c2qa.wigner.plot_wigner(circuit, state)
#The coherent state is displaced along the x axis by sqrt(2)*Re(λ),
#and on the y axis by sqrt(2)*Im(λ)
def measure_overlap(alpha1, alpha2):
qreg = c2qa.QumodeRegister(1, num_qubits_per_qumode=5)
circuit = c2qa.CVCircuit(qreg)
circuit.cv_d(alpha1, qreg[0])
state1, _, _ = c2qa.util.simulate(circuit)
circuit.clear()
circuit.cv_d(alpha2, qreg[0])
state2, _, _ = c2qa.util.simulate(circuit)
return state1.inner(state2)
ds = np.linspace(0,4,10)
overlaps = []
for d in ds:
overlaps.append(measure_overlap(d/2, -d/2))
plt.plot(ds, overlaps, linestyle = "None", marker = "o")
xlist = np.linspace(0,4,100)
plt.plot(xlist, np.exp(-(xlist)**2/2))
qr = qiskit.QuantumRegister(1)
qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4)
circuit = c2qa.CVCircuit(qmr, qr)
animate_steps = 10
t0 = 0
tf = 1
osc_frequency = 6 #6 GHz oscillator
#prepare initial state
circuit.cv_d(1, qmr[0])
stepsize = (tf-t0)/animate_steps
for t in range(animate_steps):
circuit.cv_r(-osc_frequency*(stepsize), qmr[0])
anim = c2qa.animate.animate_wigner(circuit, qubit=qr[0], animation_segments=1);
HTML(anim.to_html5_video())
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 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.
"""Job Manager used to manage jobs for IBM Quantum Experience."""
import logging
import warnings
from typing import List, Optional, Union, Any
from concurrent import futures
from qiskit.circuit import QuantumCircuit
from qiskit.pulse import Schedule
from qiskit.providers.ibmq.utils import validate_job_tags
from qiskit.providers.ibmq.accountprovider import AccountProvider
from .exceptions import IBMQJobManagerInvalidStateError
from .utils import format_job_details, format_status_counts
from .managedjobset import ManagedJobSet
from ..ibmqbackend import IBMQBackend
logger = logging.getLogger(__name__)
class IBMQJobManager:
"""Job Manager for IBM Quantum Experience.
The Job Manager is a higher level mechanism for handling
:class:`jobs<qiskit.providers.ibmq.job.IBMQJob>` composed of
multiple circuits or pulse schedules. It splits the experiments into
multiple jobs based on backend restrictions. When the jobs are finished,
it collects and presents the results in a unified view.
You can use the :meth:`run()` method to submit multiple experiments
with the Job Manager::
from qiskit import IBMQ, transpile
from qiskit.providers.ibmq.managed import IBMQJobManager
from qiskit.circuit.random import random_circuit
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator')
# Build a thousand circuits.
circs = []
for _ in range(1000):
circs.append(random_circuit(num_qubits=5, depth=4, measure=True))
# Need to transpile the circuits first.
circs = transpile(circs, backend=backend)
# Use Job Manager to break the circuits into multiple jobs.
job_manager = IBMQJobManager()
job_set_foo = job_manager.run(circs, backend=backend, name='foo')
The :meth:`run()` method returns a :class:`ManagedJobSet` instance, which
represents the set of jobs for the experiments. You can use the
:class:`ManagedJobSet` methods, such as :meth:`statuses()<ManagedJobSet.statuses>`,
:meth:`results()<ManagedJobSet.results>`, and
:meth:`error_messages()<ManagedJobSet.error_messages>` to get a combined
view of the jobs in the set.
For example::
results = job_set_foo.results()
results.get_counts(5) # Counts for experiment 5.
The :meth:`job_set_id()<ManagedJobSet.job_set_id>` method of :class:`ManagedJobSet`
returns the job set ID, which can be used to retrieve the job set later::
job_set_id = job_set_foo.job_set_id()
retrieved_foo = job_manager.retrieve_job_set(job_set_id=job_set_id, provider=provider)
"""
def __init__(self) -> None:
"""IBMQJobManager constructor."""
self._job_sets = [] # type: List[ManagedJobSet]
self._executor = futures.ThreadPoolExecutor()
def run(
self,
experiments: Union[QuantumCircuit, Schedule, List[QuantumCircuit], List[Schedule]],
backend: IBMQBackend,
name: Optional[str] = None,
max_experiments_per_job: Optional[int] = None,
job_share_level: Optional[str] = None,
job_tags: Optional[List[str]] = None,
**run_config: Any
) -> ManagedJobSet:
"""Execute a set of circuits or pulse schedules on a backend.
The circuits or schedules will be split into multiple jobs. Circuits
or schedules in a job will be executed together in each shot.
Args:
experiments: Circuit(s) or pulse schedule(s) to execute.
backend: Backend to execute the experiments on.
name: Name for this set of jobs.
Each job within the set will have
a job name that consists of the set name followed by a suffix.
If not specified, the current date and time is used.
max_experiments_per_job: Maximum number of experiments to run in each job.
If not specified, the default is to use the maximum allowed by
the backend.
If the specified value is greater the maximum allowed by the
backend, the default is used.
job_share_level: Allow sharing the jobs at the hub, group, project, or
global level. The level can be one of: ``global``, ``hub``,
``group``, ``project``, and ``none``.
job_tags: Tags to be assigned to the jobs. The tags can
subsequently be used as a filter in the
:meth:`IBMQBackend.jobs()<qiskit.providers.ibmq.ibmqbackend.IBMQBackend.jobs()>`
function call.
run_config: Configuration of the runtime environment. Some
examples of these configuration parameters include:
``qobj_id``, ``qobj_header``, ``shots``, ``memory``,
``seed_simulator``, ``qubit_lo_freq``, ``meas_lo_freq``,
``qubit_lo_range``, ``meas_lo_range``, ``schedule_los``,
``meas_level``, ``meas_return``, ``meas_map``,
``memory_slot_size``, ``rep_time``, and ``parameter_binds``.
Refer to the documentation on :func:`qiskit.compiler.assemble`
for details on these arguments.
Returns:
A :class:`ManagedJobSet` instance representing the set of jobs for
the experiments.
Raises:
IBMQJobManagerInvalidStateError: If an input parameter value is not valid.
"""
if not isinstance(experiments, list):
experiments = list(experiments)
if (any(isinstance(exp, Schedule) for exp in experiments) and
not backend.configuration().open_pulse):
raise IBMQJobManagerInvalidStateError(
'Pulse schedules found, but the backend does not support pulse schedules.')
if job_share_level:
warnings.warn("The `job_share_level` keyword is no longer supported "
"and will be removed in a future release.",
Warning, stacklevel=2)
validate_job_tags(job_tags, IBMQJobManagerInvalidStateError)
if not isinstance(backend, IBMQBackend):
raise IBMQJobManagerInvalidStateError(
"IBMQJobManager only supports IBMQBackend. "
"{} is not an IBMQBackend.".format(backend))
experiment_list = self._split_experiments(
experiments, backend=backend, max_experiments_per_job=max_experiments_per_job)
job_set = ManagedJobSet(name=name)
job_set.run(experiment_list, backend=backend, executor=self._executor,
job_tags=job_tags, **run_config)
self._job_sets.append(job_set)
return job_set
def _split_experiments(
self,
experiments: Union[List[QuantumCircuit], List[Schedule]],
backend: IBMQBackend,
max_experiments_per_job: Optional[int] = None
) -> List[Union[List[QuantumCircuit], List[Schedule]]]:
"""Split a list of experiments into sub-lists.
Args:
experiments: Experiments to be split.
backend: Backend to execute the experiments on.
max_experiments_per_job: Maximum number of experiments to run in each job.
Returns:
A list of sub-lists of experiments.
"""
if hasattr(backend.configuration(), 'max_experiments'):
backend_max = backend.configuration().max_experiments
chunk_size = backend_max if max_experiments_per_job is None \
else min(backend_max, max_experiments_per_job)
elif max_experiments_per_job:
chunk_size = max_experiments_per_job
else:
return [experiments]
return [experiments[x:x + chunk_size] for x in range(0, len(experiments), chunk_size)]
def report(self, detailed: bool = True) -> str:
"""Return a report on the statuses of all jobs managed by this Job Manager.
Args:
detailed: ``True`` if a detailed report is to be returned. ``False``
if a summary report is to be returned.
Returns:
A report on job statuses.
"""
job_set_statuses = [job_set.statuses() for job_set in self._job_sets]
flat_status_list = [stat for stat_list in job_set_statuses for stat in stat_list]
report = ["Summary report:"]
report.extend(format_status_counts(flat_status_list))
if detailed:
report.append("\nDetail report:")
for i, job_set in enumerate(self._job_sets):
report.append((" Job set name: {}, ID: {}".format(
job_set.name(), job_set.job_set_id())))
report.extend(format_job_details(
job_set_statuses[i], job_set.managed_jobs()))
return '\n'.join(report)
def job_sets(self, name: Optional[str] = None) -> List[ManagedJobSet]:
"""Return job sets being managed in this session, subject to optional filtering.
Args:
name: Name of the managed job sets.
Returns:
A list of managed job sets that match the filter.
"""
if name:
return [job_set for job_set in self._job_sets if job_set.name() == name]
return self._job_sets
def retrieve_job_set(
self,
job_set_id: str,
provider: AccountProvider,
refresh: bool = False
) -> ManagedJobSet:
"""Retrieve a previously submitted job set.
Args:
job_set_id: Job set ID.
provider: Provider used for this job set.
refresh: If ``True``, re-query the server for the job set information.
Otherwise return the cached value.
Returns:
Retrieved job set.
Raises:
IBMQJobManagerUnknownJobSet: If the job set cannot be found.
IBMQJobManagerInvalidStateError: If jobs for this job set are
found but have unexpected attributes.
"""
for index, mjs in enumerate(self._job_sets):
if mjs.job_set_id() == job_set_id:
if not refresh:
return mjs
del self._job_sets[index]
break
new_job_set = ManagedJobSet(short_id=job_set_id)
new_job_set.retrieve_jobs(provider=provider)
self._job_sets.append(new_job_set)
return new_job_set
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.visualization.timeline import draw as timeline_draw
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
timeline_draw(circ)
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
def python_commands(commands):
try:
result = subprocess.run(
['python', '-c', commands], check=True, capture_output=True, encoding='utf8'
)
except subprocess.CalledProcessError as err:
return err
return result
def basic_inits():
all_coms = []
for _compile in ("False", "True"):
for calljulia in ("pyjulia", "juliacall"):
for depot in ("False", "True"):
args = f"compile={_compile}, calljulia='{calljulia}', depot={depot}"
coms = f"import qiskit_alt; qiskit_alt.project.ensure_init({args})"
all_coms.append(coms)
if calljulia == "pyjulia":
other_calljulia = "juliacall"
else:
other_calljulia = "pyjulia"
args = f"compile={_compile}, calljulia='{other_calljulia}', depot={depot}"
coms = f"import qiskit_alt; qiskit_alt.project.ensure_init({args}); qiskit_alt.project.clean_all()"
all_coms.append(coms)
return all_coms
# def basic_inits():
# all_coms = ["import sys", "import os", "import sdsdff", "import sdsdff", "import shutil"]
# return all_coms
def run_tests(all_commands=None, verbose=False):
num_passed = 0
if all_commands is None:
all_commands = basic_inits()
for commands in all_commands:
print(f"running '{commands}'")
result = python_commands(commands)
if isinstance(result, subprocess.CalledProcessError):
print(f"**** Commands '{commands}' failed with error code {result}")
print(result.stderr)
else:
num_passed += 1
if verbose:
print(result)
msg = f"{num_passed} of {len(all_commands)} installation tests passed"
if num_passed < len(all_commands):
print("**** " + msg)
else:
print(msg)
if __name__ == '__main__':
run_tests()
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
#pip install pennyane
#improt pennylane dependnecies
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
from sklearn.preprocessing import StandardScaler
# load the csv files
import pandas as pd
# plot the historical acc and cost
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
scale = StandardScaler()
scale.fit(X_train)
X_train = scale.transform(X_train)
X_test = scale.transform(X_test)
n_wires = 4
dev = qml.device("default.qubit", wires=n_wires)
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(1))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 1
weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
if sum(x) == 0:
x[0]=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_test
y_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
y_test_pred = []
for i in y_pred:
if i < 0:
y_test_pred.append(-1)
else:
y_test_pred.append(1)
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'mera_1_standard_layers.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
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/nahumsa/volta
|
nahumsa
|
import numpy as np
from qiskit.aqua.operators import I, X, Y, Z
import matplotlib.pyplot as plt
%load_ext autoreload
%autoreload 2
def BCS_hamiltonian(epsilons, V):
return ((1/2*epsilons[0]*I^Z) + (1/2*epsilons[1]*Z^I) + V*(1/2*(X^X) + 1/2*(Y^Y)))
EPSILONS = [1,1]
V = 2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
from qiskit.aqua.operators import PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki
from qiskit.aqua.operators import StateFn, Plus, Zero, One, Minus, PauliExpectation, CX
from qiskit.circuit import Parameter
from qiskit import BasicAer
# Initial State
init_state = (Plus^Zero)
# Time evolution operator
evolution_param = Parameter("t")
evolution_op = (evolution_param * hamiltonian).exp_i()
# Measurement of the Hamiltonian with the time evolved state
evo_and_meas = StateFn(hamiltonian).adjoint() @ evolution_op @ init_state
# Trotterization
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
# Diagonalize the measurement
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
# Create an array to represent time and apply to the circuit
n_points = 10
time_array = list(np.linspace(0, 1/V, n_points))
expectations = diagonalized_meas_op.bind_parameters({evolution_param: time_array})
# Define Backend
backend = BasicAer.get_backend("statevector_simulator")
# Use CircuitSampler for getting energy values
sampler = CircuitSampler(backend=backend)
sampled_expectations = sampler.convert(expectations)
sampled_energies = sampled_expectations.eval()
print(f"Time:\n {time_array}")
print(f"Sampled energies after Trotterization:\n {np.real(sampled_energies)}")
plt.plot(time_array, np.real(sampled_energies))
plt.show()
|
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
|
wyqian1027
|
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_bloch_multivector, array_to_latex
from grader import *
language(True)
phi_plus = QuantumCircuit(2)
phi_plus.h(0)
phi_plus.cnot(0, 1)
phi_plus.draw('mpl')
# Simulamos para ver su resultado
backend = Aer.get_backend('statevector_simulator')
result = execute(phi_plus, backend).result().get_statevector()
array_to_latex(result)
phi_minus = QuantumCircuit(2)
##### ==================================
# Escribe tu solución aquí.
phi_minus.h(0)
phi_minus.z(0)
phi_minus.cnot(0, 1)
##### ==================================
phi_minus.draw('mpl')
# Esta celda te dirá si lo que has hecho da el resultado correcto.
# Tómalo como un indicador, los tests que hace no consideran todas las opciones posibles.
# Si crees que tu respuesta es (in)correcta y el grader dice algo diferente, simplemente pregúntame.
# No intentes hacer trampas modificando el código del corrector :)
ex1_grader(phi_minus)
psi_plus = QuantumCircuit(2)
##### ==================================
# Escribe tu solución aquí.
psi_plus.h(0)
psi_plus.x(1)
psi_plus.cnot(0, 1)
##### ==================================
psi_plus.draw('mpl')
ex2_grader(psi_plus)
psi_minus = QuantumCircuit(2)
##### ==================================
# Escribe tu solución aquí.
psi_minus.h(0)
psi_minus.x(1)
psi_minus.z(0)
psi_minus.cnot(0, 1)
##### ==================================
psi_minus.draw('mpl')
ex3_grader(psi_minus)
GHZ = QuantumCircuit(3)
##### ==================================
# Escribe tu solución aquí.
GHZ.h(0)
GHZ.cnot(0, 1)
GHZ.cnot(0, 2)
##### ==================================
GHZ.draw('mpl')
ex4_grader(GHZ)
Even = QuantumCircuit(3)
##### ==================================
# Escribe tu solución aquí.
Even.h(0)
Even.h(1)
Even.cnot(0, 2)
Even.cnot(1, 2)
##### ==================================
Even.draw('mpl')
ex5_grader(Even)
Odd = QuantumCircuit(3)
##### ==================================
# Escribe tu solución aquí.
Odd.h(0)
Odd.h(1)
Odd.x(2)
Odd.cnot(0, 2)
Odd.cnot(1, 2)
##### ==================================
Odd.draw('mpl')
ex6_grader(Odd)
def measure_z_axis(qc, qubit, cbit): #Las medidas deben guardarse en bits clásicos.
qc.measure(qubit, cbit)
def measure_x_axis(qc, qubit, cbit):
##### ==================================
# Escribe tu solución aquí.
qc.h(qubit)
qc.measure(qubit, cbit)
##### ==================================
ex7_grader(measure_x_axis)
def expectation_value_single_qubit(qc, nshots=8092):
# Ejecuta el circuito que ya está rotado a la base correspondiente
backend_shots = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend_shots, shots=nshots).result().get_counts() #Counts is a dictionary that contains the number of zeros and the number of ones measured
# Esto es simplemente para evitar problemas. En caso de que falte una key en el diccionario la añade
if '1' not in counts.keys():
counts['1'] = 0
if '0' not in counts.keys():
counts['0'] = 0
# Obten el numero de veces que se ha medido 0 y 1
n_zeros = counts['0']
n_ones = counts['1']
# Calcula las probabilidades
p_0 = n_zeros/nshots
p_1 = n_ones/nshots # O 1-p_0
expectation_value = 1*p_0+(-1)*p_1
return expectation_value
# Mide <Z> sobre un estado que te guste
qc_z = QuantumCircuit(1,1)
measure_z_axis(qc_z, 0, 0)
print('<Z>=', expectation_value_single_qubit(qc_z))
qc_z.draw('mpl')
# Mide <X> sobre un estado que te guste
qc_x = QuantumCircuit(1,1)
measure_x_axis(qc_x, 0, 0)
print('<X>=', expectation_value_single_qubit(qc_x))
qc_x.draw('mpl')
##### ==================================
# Escribe tu solución aquí.
measure_strings = ['ZZ', 'ZX', 'XZ', 'XX']
# Primero crea un estado de Bell
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cnot(0, 1)
# Para cada uno de los operadores que queremos medir, (ZZ, ZX, XZ and XX) crea un nuevo circuito (quizás usando qc.copy())
# que mida en ese eje.
chsh_circuits = []
for string in measure_strings:
qc1 = qc.copy()
if string[0] == 'Z':
measure_z_axis(qc1, 0, 0)
if string[0] == 'X':
measure_x_axis(qc1, 0, 0)
if string[1] == 'Z':
measure_z_axis(qc1, 1, 1)
if string[1] == 'X':
measure_x_axis(qc1, 1, 1)
chsh_circuits.append(qc1)
##### ==================================
chsh_circuits[0].draw('mpl')
chsh_circuits[1].draw('mpl')
chsh_circuits[2].draw('mpl')
chsh_circuits[3].draw('mpl')
# Hacer tests aquí que no revelasen la respuesta era complicado, así que no hay ayuda :(
# Podemos correr todos los circuitos a la vez y luego postprocesar los datos
nshots = 8092 # Cuantos más shots, menos error
backend_shots = Aer.get_backend('qasm_simulator')
counts_list = execute(chsh_circuits, backend_shots, shots=nshots).result().get_counts()
counts_list
##### ==================================
# Escribe tu solución aquí.
exp_dict = {}
# Para cada uno de los circuitos, coge las counts que tengas para ese circuito, calcula la probabilidad
#de cada estado y combinalas teniendo mucho cuidado con qué signo lleva cada término
for i in range(len(chsh_circuits)):
string = measure_strings[i] #ZZ, ZX, XZ and XX
counts = counts_list[i]
exp = 0.
for element in counts:
parity = (-1)**(int(element[0])+int(element[1]))
#print(element, parity)
exp += counts[element]*parity
exp_dict[string] = exp/nshots
# Puede que quieras inspirarte en la función expectation_value_single_qubit
# Si estás muy perdido y no sabes cómo resolver esto, puedes preguntar.
##### ==================================
# Si no sabes si tu respuesta es correcta, puedes calcular los resultados a mano
# (de hecho seguramente sea más fácil que calcularlo así) y comprobar si tu código está funcionando
##### ==================================
# Escribe tu solución aquí.
exp_AB = np.sqrt(1/2)*(exp_dict['ZZ']-exp_dict['XZ'])
exp_Ab = np.sqrt(1/2)*(exp_dict['ZX']-exp_dict['XX'])
exp_aB = np.sqrt(1/2)*(exp_dict['ZZ']+exp_dict['XZ'])
exp_ab = np.sqrt(1/2)*(exp_dict['ZX']+exp_dict['XX'])
CHSH = exp_AB - exp_Ab + exp_aB + exp_ab
##### ==================================
print('Tu resultado es <CHSH>=', CHSH)
print('El resultado correcto es <CHSH>=', 2*np.sqrt(2))
##### ==================================
# Escribe tu solución aquí.
Can_entanglement_be_teleported = True#Escribe True or False :D
##### ==================================
##### ==================================
# Escribe tu solución aquí.
Where_did_the_bell_pair_go = 'En los dos últimos cúbits'
##### ==================================
##### ==================================
# Escribe tu solución aquí.
##### ==================================
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
def qc_dqc1(ph):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr, name='DQC1')
qc.h(0)
qc.h(1) # cria o estado de Bell dos qubits 1 e 2, que equivale ao estado de 1 sendo maximamente misto
qc.cx(1,2)
#qc.barrier()
qc.cp(ph, 0, 1)
return qc
ph = math.pi/2
qc_dqc1_ = qc_dqc1(ph)
qc_dqc1_.draw('mpl')
qc_dqc1_.decompose().draw('mpl')
def pTraceL_num(dl, dr, rhoLR): # Retorna traco parcial sobre L de rhoLR
rhoR = np.zeros((dr, dr), dtype=complex)
for j in range(0, dr):
for k in range(j, dr):
for l in range(0, dl):
rhoR[j,k] += rhoLR[l*dr+j,l*dr+k]
if j != k:
rhoR[k,j] = np.conj(rhoR[j,k])
return rhoR
def pTraceR_num(dl, dr, rhoLR): # Retorna traco parcial sobre R de rhoLR
rhoL = np.zeros((dl, dl), dtype=complex)
for j in range(0, dl):
for k in range(j, dl):
for l in range(0, dr):
rhoL[j,k] += rhoLR[j*dr+l,k*dr+l]
if j != k:
rhoL[k,j] = np.conj(rhoL[j,k])
return rhoL
# simulation
phmax = 2*math.pi
dph = phmax/20
ph = np.arange(0,phmax+dph,dph)
d = len(ph);
xm = np.zeros(d)
ym = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm[j] = 2*rho_0[1,0].real
ym[j] = 2*rho_0[1,0].imag
qc.draw('mpl')
# experiment
phmax = 2*math.pi
dph = phmax/10
ph_exp = np.arange(0,phmax+dph,dph)
d = len(ph_exp);
xm_exp = np.zeros(d)
ym_exp = np.zeros(d)
for j in range(0,d):
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
qc_dqc1_ = qc_dqc1(ph_exp[j])
qc.append(qc_dqc1_, [0,1,2])
qstc = state_tomography_circuits(qc, [1,0])
job = execute(qstc, backend=device, shots=nshots)
print(job.job_id())
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_01 = qstf.fit(method='lstsq')
rho_0 = pTraceR_num(2, 2, rho_01)
xm_exp[j] = 2*rho_0[1,0].real
ym_exp[j] = 2*rho_0[1,0].imag
plt.plot(ph, xm, label = r'$\langle X\rangle_{sim}$')#, marker='*')
plt.plot(ph, ym, label = r'$\langle Y\rangle_{sim}$')#, marker='o')
plt.scatter(ph_exp, xm_exp, label = r'$\langle X\rangle_{exp}$', marker='*', color='r')
plt.scatter(ph_exp, ym_exp, label = r'$\langle Y\rangle_{exp}$', marker='o', color='g')
plt.legend(bbox_to_anchor=(1, 1))#,loc='center right')
#plt.xlim(0,2*math.pi)
#plt.ylim(-1,1)
plt.xlabel(r'$\phi$')
plt.show()
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
import qiskit
import qiskit_aer
def test_qiskit():
"""Verify we can do a simple QisKit circuit without our custom gates."""
qr = qiskit.QuantumRegister(6)
cr = qiskit.ClassicalRegister(6)
circuit = qiskit.circuit.QuantumCircuit(qr, cr)
circuit.cx(qr[0:1], qr[2])
circuit.save_statevector()
backend = qiskit_aer.AerSimulator()
job = backend.run(circuit)
result = job.result()
state = result.get_statevector(circuit)
assert result.success
print(state)
def test_initialize(capsys):
with capsys.disabled():
# Successful with Qiskit v0.34.2, raises error with v0.35+
qr = qiskit.QuantumRegister(1)
circuit = qiskit.circuit.QuantumCircuit(qr)
circuit.initialize([0, 1], qr[0])
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def apply_z_to_plus():
"""Write a circuit that applies PauliZ to the |+> state and returns
the state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE |+> STATE
qml.Hadamard(wires=0)
# APPLY PAULI Z
qml.PauliZ(wires=0)
# RETURN THE STATE
return qml.state()
print(apply_z_to_plus())
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def fake_z():
"""Use RZ to produce the same action as Pauli Z on the |+> state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE |+> STATE
qml.Hadamard(wires=0)
# APPLY RZ
qml.RZ(np.pi, wires=0)
# RETURN THE STATE
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def many_rotations():
"""Implement the circuit depicted above and return the quantum state.
Returns:
array[complex]: The state of the qubit after the operations.
"""
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE CIRCUIT
qml.Hadamard(wires=0)
qml.S(wires=0)
qml.adjoint(qml.T)(wires=0)
qml.RZ(0.3, wires=0)
qml.adjoint(qml.S)(wires=0)
# RETURN THE STATE
return qml.state()
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def too_many_ts():
"""You can implement the original circuit here as well, it may help you with
testing to ensure that the circuits have the same effect.
Returns:
array[float]: The measurement outcome probabilities.
"""
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.T(wires=[0,1])
qml.adjoint(qml.T)(wires=2)
qml.T(wires=0)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.adjoint(qml.T)(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.adjoint(qml.T)(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
qml.T(wires=1)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
return qml.probs(wires=[0, 1, 2])
@qml.qnode(dev)
def just_enough_ts():
"""Implement an equivalent circuit as the above with the minimum number of
T and T^\dagger gates required.
Returns:
array[float]: The measurement outcome probabilities.
"""
##################
# YOUR CODE HERE #
##################
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.S(wires=0)
qml.T(wires=1)
qml.adjoint(qml.T)(wires=2)
# qml.T(wires=0)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
qml.adjoint(qml.S)(wires=0)
qml.S(wires=1)
qml.adjoint(qml.S)(wires=2)
# qml.adjoint(qml.T)(wires=0)
# qml.T(wires=1)
# qml.adjoint(qml.T)(wires=2)
qml.S(wires=1)
qml.adjoint(qml.T)(wires=2)
# qml.T(wires=1)
# qml.Hadamard(wires=[0,1,2])
qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.Hadamard(wires=2)
# IMPLEMENT THE CIRCUIT, BUT COMBINE AND OPTIMIZE THE GATES
# TO MINIMIZE THE NUMBER OF TS
return qml.probs(wires=[0, 1, 2])
##################
# YOUR CODE HERE #
##################
# FILL IN THE CORRECT VALUES FOR THE ORIGINAL CIRCUIT
original_depth = 8
original_t_count = 13
original_t_depth = 6
# FILL IN THE CORRECT VALUES FOR THE NEW, OPTIMIZED CIRCUIT
optimal_depth = 6
optimal_t_count = 3
optimal_t_depth = 2
dev = qml.device("default.qubit", wires=1)
##################
# YOUR CODE HERE #
##################
# ADJUST THE VALUES OF PHI, THETA, AND OMEGA
phi, theta, omega = np.pi/2, np.pi/2, np.pi/2
@qml.qnode(dev)
def hadamard_with_rz_rx():
qml.RZ(phi, wires=0)
qml.RX(theta, wires=0)
qml.RZ(omega, wires=0)
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def convert_to_rz_rx():
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE CIRCUIT IN THE PICTURE USING ONLY RZ AND RX
qml.RZ(np.pi/2, wires=0)
qml.RX(np.pi/2, wires=0)
qml.RZ(np.pi/2, wires=0)
qml.RZ(np.pi/2,wires=0)
qml.RZ(np.pi, wires=0)
qml.RZ(np.pi/2, wires=0)
qml.RZ(np.pi/4, wires=0)
qml.RZ(np.pi/2,wires=0)
qml.RX(np.pi, wires=0)
qml.RZ(np.pi, wires=0)
qml.RZ(np.pi/2, wires=0)
return qml.state()
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def unitary_with_h_and_t():
##################
# YOUR CODE HERE #
##################
# APPLY ONLY H AND T TO PRODUCE A CIRCUIT THAT EFFECTS THE GIVEN MATRIX
# qml.T(wires=0)
qml.Hadamard(wires=0)
qml.T(wires=0)
qml.Hadamard(wires=0)
qml.T(wires=0)
qml.T(wires=0)
qml.Hadamard(wires=0)
# qml.T(wires=0)
return qml.state()
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, IBMQ
IBMQ.enable_account('Insert account token here') # Get this from your IBM Q account
provider = IBMQ.get_provider(hub='ibm-q')
q = QuantumRegister(1,'q') # Initialise quantum register
c = ClassicalRegister(1,'c') # Initialise classical register
circuit = QuantumCircuit(q,c) # Initialise circuit
circuit.h(q[0]) # Put Qubit 0 in to superposition using hadamard gate
circuit.measure(q,c) # Measure qubit
backend = provider.get_backend('ibmq_qasm_simulator') # Set device to IBMs quantum simulator
job = execute(circuit, backend, shots=1024) # Execute job and run program 1024 times
result = job.result() # Get result
counts = result.get_counts(circuit) # Count the number of measurements for each state
print('RESULT: ',counts) # Print result
print('Press any key to close')
input()
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# genera las distancias
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
header = ['instance', 'iteration', 'distance']
length_instances = 2
with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
for i in range(length_instances):
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import ZFeatureMap, RealAmplitudes
from qiskit.utils import algorithm_globals
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EffectiveDimension, LocalEffectiveDimension
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
# set random seed
algorithm_globals.random_seed = 42
num_qubits = 3
# create a feature map
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
# create a variational circuit
ansatz = RealAmplitudes(num_qubits, reps=1)
# combine feature map and ansatz into a single circuit
qc = QuantumCircuit(num_qubits)
qc.append(feature_map, range(num_qubits))
qc.append(ansatz, range(num_qubits))
qc.decompose().draw("mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
sparse=False,
)
# we can set the total number of input samples and weight samples for random selection
num_input_samples = 10
num_weight_samples = 10
global_ed = EffectiveDimension(
qnn=qnn, weight_samples=num_weight_samples, input_samples=num_input_samples
)
# we can also provide user-defined samples and parameters
input_samples = algorithm_globals.random.normal(0, 1, size=(10, qnn.num_inputs))
weight_samples = algorithm_globals.random.uniform(0, 1, size=(10, qnn.num_weights))
global_ed = EffectiveDimension(qnn=qnn, weight_samples=weight_samples, input_samples=input_samples)
# finally, we will define ranges to test different numbers of data, n
n = [5000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000]
global_eff_dim_0 = global_ed.get_effective_dimension(dataset_size=n[0])
d = qnn.num_weights
print("Data size: {}, global effective dimension: {:.4f}".format(n[0], global_eff_dim_0))
print(
"Number of weights: {}, normalized effective dimension: {:.4f}".format(d, global_eff_dim_0 / d)
)
global_eff_dim_1 = global_ed.get_effective_dimension(dataset_size=n)
print("Effective dimension: {}".format(global_eff_dim_1))
print("Number of weights: {}".format(d))
# plot the normalized effective dimension for the model
plt.plot(n, np.array(global_eff_dim_1) / d)
plt.xlabel("Number of data")
plt.ylabel("Normalized GLOBAL effective dimension")
plt.show()
num_inputs = 3
num_samples = 50
X, y = make_classification(
n_samples=num_samples,
n_features=num_inputs,
n_informative=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
)
X = MinMaxScaler().fit_transform(X)
y = 2 * y - 1 # labels in {-1, 1}
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct classifier
initial_point = algorithm_globals.random.random(estimator_qnn.num_weights)
estimator_classifier = NeuralNetworkClassifier(
neural_network=estimator_qnn,
optimizer=COBYLA(maxiter=80),
initial_point=initial_point,
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function (callback)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
trained_weights = estimator_classifier.weights
# get Local Effective Dimension for set of trained weights
local_ed_trained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=trained_weights, input_samples=X
)
local_eff_dim_trained = local_ed_trained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for trained QNN: ",
local_eff_dim_trained / estimator_qnn.num_weights,
)
# get Local Effective Dimension for set of untrained weights
local_ed_untrained = LocalEffectiveDimension(
qnn=estimator_qnn, weight_samples=initial_point, input_samples=X
)
local_eff_dim_untrained = local_ed_untrained.get_effective_dimension(dataset_size=n)
print(
"normalized local effective dimensions for untrained QNN: ",
local_eff_dim_untrained / estimator_qnn.num_weights,
)
# plot the normalized effective dimension for the model
plt.plot(n, np.array(local_eff_dim_trained) / estimator_qnn.num_weights, label="trained weights")
plt.plot(
n, np.array(local_eff_dim_untrained) / estimator_qnn.num_weights, label="untrained weights"
)
plt.xlabel("Number of data")
plt.ylabel("Normalized LOCAL effective dimension")
plt.legend()
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
#initialization
import sys
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing the QISKit
from qiskit import QuantumProgram
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
#set api
from IBMQuantumExperience import IBMQuantumExperience
api = IBMQuantumExperience(token=qx_config['APItoken'], config={'url': qx_config['url']})
#prepare backends
from qiskit.backends import discover_local_backends, discover_remote_backends, get_backend_instance
remote_backends = discover_remote_backends(api) #we have to call this to connect to remote backends
local_backends = discover_local_backends()
# Quantum program setup
Q_program = QuantumProgram()
#for plot with 16qubit
import numpy as np
from functools import reduce
from scipy import linalg as la
from collections import Counter
import matplotlib.pyplot as plt
def plot_histogram5(data, number_to_keep=False):
"""Plot a histogram of data.
data is a dictionary of {'000': 5, '010': 113, ...}
number_to_keep is the number of terms to plot and rest is made into a
single bar called other values
"""
if number_to_keep is not False:
data_temp = dict(Counter(data).most_common(number_to_keep))
data_temp["rest"] = sum(data.values()) - sum(data_temp.values())
data = data_temp
labels = sorted(data)
values = np.array([data[key] for key in labels], dtype=float)
pvalues = values / sum(values)
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects = ax.bar(ind, pvalues, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Probabilities', fontsize=12)
ax.set_xticks(ind)
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])])
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
'%f' % float(height),
ha='center', va='bottom', fontsize=8)
plt.show()
q1_2 = Q_program.create_quantum_register("q1_2", 3)
c1_2 = Q_program.create_classical_register("c1_2", 3)
qw1_2 = Q_program.create_circuit("qw1_2", [q1_2], [c1_2])
t=8 #time
qw1_2.x(q1_2[2])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.u3(t, 0, 0, q1_2[1])
qw1_2.cx(q1_2[2], q1_2[1])
qw1_2.measure(q1_2[0], c1_2[0])
qw1_2.measure(q1_2[1], c1_2[2])
qw1_2.measure(q1_2[2], c1_2[1])
print(qw1_2.qasm())
result = Q_program.execute(["qw1_2"], backend='local_qiskit_simulator', shots=1000)
plot_histogram5(result.get_counts("qw1_2"))
result = Q_program.execute(["qw1_2"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=1024)
plot_histogram5(result.get_counts("qw1_2"))
q1 = Q_program.create_quantum_register("q1", 3)
c1 = Q_program.create_classical_register("c1", 3)
qw1 = Q_program.create_circuit("qw1", [q1], [c1])
t=8 #time
qw1.x(q1[1])
qw1.cx(q1[2], q1[1])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.u3(t, 0, 0, q1[2])
qw1.cx(q1[2], q1[0])
qw1.cx(q1[2], q1[1])
qw1.u3(2*t, 0, 0, q1[2])
qw1.measure(q1[0], c1[0])
qw1.measure(q1[1], c1[1])
qw1.measure(q1[2], c1[2])
print(qw1.qasm())
result = Q_program.execute(["qw1"], backend='local_qiskit_simulator')
plot_histogram5(result.get_counts("qw1"))
result = Q_program.execute(["qw1"], backend='ibmqx4', shots=1000, max_credits=3, wait=10, timeout=600)
plot_histogram5(result.get_counts("qw1"))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
#Set up the quantum and classical registers, and combine them into a circuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]) #Create a superposition on the single quantum bit
qc.measure(qr[0], cr[0]) #Measure the single bit, and store its value in the clasical bit
from qiskit import register, available_backends, get_backend
#Import the config file (Qconfig.py) to retrieve the API token and API url
try:
import sys
sys.path.append('../') #Parent directory
import Qconfig
qx_config = {
'APItoken': Qconfig.APItoken,
'url': Qconfig.config['url']}
except Exception as e:
print(e)
qx_config = {
'APItoken':'YOUR_TOKEN_HERE',
'url':'https://quantumexperience.ng.bluemix.net/api'}
#Setup API
register(qx_config['APItoken'], qx_config['url'])
backend = 'ibmq_qasm_simulator' #Replace 'ibmq_qasm_simulator' with 'ibmqx5' to run on the quantum computer
shots_sim = 100 #Adjust this number as desired, with effects as described above
job_sim = execute(qc, backend, shots=shots_sim) #Run job on chosen backend for chosen number of shots
stats_sim = job_sim.result().get_counts() #Retrieve results
#Select '0' to represent 'laurel'
if '0' not in stats_sim.keys():
stats_sim['laurel'] = 0
else:
stats_sim['laurel'] = stats_sim.pop('0')
#Which leaves '1' to represent 'yanny'
if '1' not in stats_sim.keys():
stats_sim['yanny'] = 0
else:
stats_sim['yanny'] = stats_sim.pop('1')
plot_histogram(stats_sim)
from pydub import AudioSegment
from pydub.playback import play
#Import two tracks
laurel = AudioSegment.from_wav('laurel_or_yanny_audio_files/laurel.wav')
yanny = AudioSegment.from_wav('laurel_or_yanny_audio_files/yanny.wav')
play(laurel) #Listen to the laurel-specific track
play(yanny) #Listen to the yanny-specific track
#Modify the volumes based on the results of the experiment
laurel = laurel + ((100*stats_sim['laurel']/shots_sim)-50) #Laurel
yanny = yanny + ((100*stats_sim['yanny']/shots_sim)-50) #Yanny
#Mix the two together and play the result
mixed = laurel.overlay(yanny)
play(mixed)
mixed.export('laurel_or_yanny_audio_files/quantumLaurelYanny.wav', format='wav')
print("Installed packages are as the following")
!python --version
print()
!conda list 'qiskit|IBMQuantumExperience|numpy|scipy'
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""The Iterative Quantum Amplitude Estimation Algorithm."""
from __future__ import annotations
from typing import cast
import warnings
import numpy as np
from scipy.stats import beta
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.providers import Backend
from qiskit.primitives import BaseSampler
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult
from .estimation_problem import EstimationProblem
from ..exceptions import AlgorithmError
class IterativeAmplitudeEstimation(AmplitudeEstimator):
r"""The Iterative Amplitude Estimation algorithm.
This class implements the Iterative Quantum Amplitude Estimation (IQAE) algorithm, proposed
in [1]. The output of the algorithm is an estimate that,
with at least probability :math:`1 - \alpha`, differs by epsilon to the target value, where
both alpha and epsilon can be specified.
It differs from the original QAE algorithm proposed by Brassard [2] in that it does not rely on
Quantum Phase Estimation, but is only based on Grover's algorithm. IQAE iteratively
applies carefully selected Grover iterations to find an estimate for the target amplitude.
References:
[1]: Grinko, D., Gacon, J., Zoufal, C., & Woerner, S. (2019).
Iterative Quantum Amplitude Estimation.
`arXiv:1912.05559 <https://arxiv.org/abs/1912.05559>`_.
[2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).
Quantum Amplitude Amplification and Estimation.
`arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
epsilon_target: float,
alpha: float,
confint_method: str = "beta",
min_ratio: float = 2,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
The output of the algorithm is an estimate for the amplitude `a`, that with at least
probability 1 - alpha has an error of epsilon. The number of A operator calls scales
linearly in 1/epsilon (up to a logarithmic factor).
Args:
epsilon_target: Target precision for estimation target `a`, has values between 0 and 0.5
alpha: Confidence level, the target probability is 1 - alpha, has values between 0 and 1
confint_method: Statistical method used to estimate the confidence intervals in
each iteration, can be 'chernoff' for the Chernoff intervals or 'beta' for the
Clopper-Pearson intervals (default)
min_ratio: Minimal q-ratio (:math:`K_{i+1} / K_i`) for FindNextK
quantum_instance: Deprecated: Quantum Instance or Backend
sampler: A sampler primitive to evaluate the circuits.
Raises:
AlgorithmError: if the method to compute the confidence intervals is not supported
ValueError: If the target epsilon is not in (0, 0.5]
ValueError: If alpha is not in (0, 1)
ValueError: If confint_method is not supported
"""
# validate ranges of input arguments
if not 0 < epsilon_target <= 0.5:
raise ValueError(f"The target epsilon must be in (0, 0.5], but is {epsilon_target}.")
if not 0 < alpha < 1:
raise ValueError(f"The confidence level alpha must be in (0, 1), but is {alpha}")
if confint_method not in {"chernoff", "beta"}:
raise ValueError(
f"The confidence interval method must be chernoff or beta, but is {confint_method}."
)
super().__init__()
# set quantum instance
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.quantum_instance = quantum_instance
# store parameters
self._epsilon = epsilon_target
self._alpha = alpha
self._min_ratio = min_ratio
self._confint_method = confint_method
self._sampler = sampler
@property
def sampler(self) -> BaseSampler | None:
"""Get the sampler primitive.
Returns:
The sampler primitive to evaluate the circuits.
"""
return self._sampler
@sampler.setter
def sampler(self, sampler: BaseSampler) -> None:
"""Set sampler primitive.
Args:
sampler: A sampler primitive to evaluate the circuits.
"""
self._sampler = sampler
@property
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self) -> QuantumInstance | None:
"""Deprecated. Get the quantum instance.
Returns:
The quantum instance used to run this algorithm.
"""
return self._quantum_instance
@quantum_instance.setter
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None:
"""Deprecated. Set quantum instance.
Args:
quantum_instance: The quantum instance used to run this algorithm.
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
@property
def epsilon_target(self) -> float:
"""Returns the target precision ``epsilon_target`` of the algorithm.
Returns:
The target precision (which is half the width of the confidence interval).
"""
return self._epsilon
@epsilon_target.setter
def epsilon_target(self, epsilon: float) -> None:
"""Set the target precision of the algorithm.
Args:
epsilon: Target precision for estimation target `a`.
"""
self._epsilon = epsilon
def _find_next_k(
self,
k: int,
upper_half_circle: bool,
theta_interval: tuple[float, float],
min_ratio: float = 2.0,
) -> tuple[int, bool]:
"""Find the largest integer k_next, such that the interval (4 * k_next + 2)*theta_interval
lies completely in [0, pi] or [pi, 2pi], for theta_interval = (theta_lower, theta_upper).
Args:
k: The current power of the Q operator.
upper_half_circle: Boolean flag of whether theta_interval lies in the
upper half-circle [0, pi] or in the lower one [pi, 2pi].
theta_interval: The current confidence interval for the angle theta,
i.e. (theta_lower, theta_upper).
min_ratio: Minimal ratio K/K_next allowed in the algorithm.
Returns:
The next power k, and boolean flag for the extrapolated interval.
Raises:
AlgorithmError: if min_ratio is smaller or equal to 1
"""
if min_ratio <= 1:
raise AlgorithmError("min_ratio must be larger than 1 to ensure convergence")
# initialize variables
theta_l, theta_u = theta_interval
old_scaling = 4 * k + 2 # current scaling factor, called K := (4k + 2)
# the largest feasible scaling factor K cannot be larger than K_max,
# which is bounded by the length of the current confidence interval
max_scaling = int(1 / (2 * (theta_u - theta_l)))
scaling = max_scaling - (max_scaling - 2) % 4 # bring into the form 4 * k_max + 2
# find the largest feasible scaling factor K_next, and thus k_next
while scaling >= min_ratio * old_scaling:
theta_min = scaling * theta_l - int(scaling * theta_l)
theta_max = scaling * theta_u - int(scaling * theta_u)
if theta_min <= theta_max <= 0.5 and theta_min <= 0.5:
# the extrapolated theta interval is in the upper half-circle
upper_half_circle = True
return int((scaling - 2) / 4), upper_half_circle
elif theta_max >= 0.5 and theta_max >= theta_min >= 0.5:
# the extrapolated theta interval is in the upper half-circle
upper_half_circle = False
return int((scaling - 2) / 4), upper_half_circle
scaling -= 4
# if we do not find a feasible k, return the old one
return int(k), upper_half_circle
def construct_circuit(
self, estimation_problem: EstimationProblem, k: int = 0, measurement: bool = False
) -> QuantumCircuit:
r"""Construct the circuit :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`.
The A operator is the unitary specifying the QAE problem and Q the associated Grover
operator.
Args:
estimation_problem: The estimation problem for which to construct the QAE circuit.
k: The power of the Q operator.
measurement: Boolean flag to indicate if measurements should be included in the
circuits.
Returns:
The circuit implementing :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`.
"""
num_qubits = max(
estimation_problem.state_preparation.num_qubits,
estimation_problem.grover_operator.num_qubits,
)
circuit = QuantumCircuit(num_qubits, name="circuit")
# add classical register if needed
if measurement:
c = ClassicalRegister(len(estimation_problem.objective_qubits))
circuit.add_register(c)
# add A operator
circuit.compose(estimation_problem.state_preparation, inplace=True)
# add Q^k
if k != 0:
circuit.compose(estimation_problem.grover_operator.power(k), inplace=True)
# add optional measurement
if measurement:
# real hardware can currently not handle operations after measurements, which might
# happen if the circuit gets transpiled, hence we're adding a safeguard-barrier
circuit.barrier()
circuit.measure(estimation_problem.objective_qubits, c[:])
return circuit
def _good_state_probability(
self,
problem: EstimationProblem,
counts_or_statevector: dict[str, int] | np.ndarray,
num_state_qubits: int,
) -> tuple[int, float] | float:
"""Get the probability to measure '1' in the last qubit.
Args:
problem: The estimation problem, used to obtain the number of objective qubits and
the ``is_good_state`` function.
counts_or_statevector: Either a counts-dictionary (with one measured qubit only!) or
the statevector returned from the statevector_simulator.
num_state_qubits: The number of state qubits.
Returns:
If a dict is given, return (#one-counts, #one-counts/#all-counts),
otherwise Pr(measure '1' in the last qubit).
"""
if isinstance(counts_or_statevector, dict):
one_counts = 0
for state, counts in counts_or_statevector.items():
if problem.is_good_state(state):
one_counts += counts
return int(one_counts), one_counts / sum(counts_or_statevector.values())
else:
statevector = counts_or_statevector
num_qubits = int(np.log2(len(statevector))) # the total number of qubits
# sum over all amplitudes where the objective qubit is 1
prob = 0
for i, amplitude in enumerate(statevector):
# consider only state qubits and revert bit order
bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1]
objectives = [bitstr[index] for index in problem.objective_qubits]
if problem.is_good_state(objectives):
prob = prob + np.abs(amplitude) ** 2
return prob
def estimate(
self, estimation_problem: EstimationProblem
) -> "IterativeAmplitudeEstimationResult":
"""Run the amplitude estimation algorithm on provided estimation problem.
Args:
estimation_problem: The estimation problem.
Returns:
An amplitude estimation results object.
Raises:
ValueError: A quantum instance or Sampler must be provided.
AlgorithmError: Sampler job run error.
"""
if self._quantum_instance is None and self._sampler is None:
raise ValueError("A quantum instance or sampler must be provided.")
# initialize memory variables
powers = [0] # list of powers k: Q^k, (called 'k' in paper)
ratios = [] # list of multiplication factors (called 'q' in paper)
theta_intervals = [[0, 1 / 4]] # a priori knowledge of theta / 2 / pi
a_intervals = [[0.0, 1.0]] # a priori knowledge of the confidence interval of the estimate
num_oracle_queries = 0
num_one_shots = []
# maximum number of rounds
max_rounds = (
int(np.log(self._min_ratio * np.pi / 8 / self._epsilon) / np.log(self._min_ratio)) + 1
)
upper_half_circle = True # initially theta is in the upper half-circle
if self._quantum_instance is not None and self._quantum_instance.is_statevector:
# for statevector we can directly return the probability to measure 1
# note, that no iterations here are necessary
# simulate circuit
circuit = self.construct_circuit(estimation_problem, k=0, measurement=False)
ret = self._quantum_instance.execute(circuit)
# get statevector
statevector = ret.get_statevector(circuit)
# calculate the probability of measuring '1'
num_qubits = circuit.num_qubits - circuit.num_ancillas
prob = self._good_state_probability(estimation_problem, statevector, num_qubits)
prob = cast(float, prob) # tell MyPy it's a float and not Tuple[int, float ]
a_confidence_interval = [prob, prob] # type: list[float]
a_intervals.append(a_confidence_interval)
theta_i_interval = [
np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval # type: ignore
]
theta_intervals.append(theta_i_interval)
num_oracle_queries = 0 # no Q-oracle call, only a single one to A
else:
num_iterations = 0 # keep track of the number of iterations
# number of shots per iteration
shots = 0
# do while loop, keep in mind that we scaled theta mod 2pi such that it lies in [0,1]
while theta_intervals[-1][1] - theta_intervals[-1][0] > self._epsilon / np.pi:
num_iterations += 1
# get the next k
k, upper_half_circle = self._find_next_k(
powers[-1],
upper_half_circle,
theta_intervals[-1], # type: ignore
min_ratio=self._min_ratio,
)
# store the variables
powers.append(k)
ratios.append((2 * powers[-1] + 1) / (2 * powers[-2] + 1))
# run measurements for Q^k A|0> circuit
circuit = self.construct_circuit(estimation_problem, k, measurement=True)
counts = {}
if self._quantum_instance is not None:
ret = self._quantum_instance.execute(circuit)
# get the counts and store them
counts = ret.get_counts(circuit)
shots = self._quantum_instance._run_config.shots
else:
try:
job = self._sampler.run([circuit])
ret = job.result()
except Exception as exc:
raise AlgorithmError("The job was not completed successfully. ") from exc
shots = ret.metadata[0].get("shots")
if shots is None:
circuit = self.construct_circuit(estimation_problem, k=0, measurement=True)
try:
job = self._sampler.run([circuit])
ret = job.result()
except Exception as exc:
raise AlgorithmError(
"The job was not completed successfully. "
) from exc
# calculate the probability of measuring '1'
prob = 0.0
for bit, probabilities in ret.quasi_dists[0].binary_probabilities().items():
# check if it is a good state
if estimation_problem.is_good_state(bit):
prob += probabilities
a_confidence_interval = [prob, prob]
a_intervals.append(a_confidence_interval)
theta_i_interval = [
np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval
]
theta_intervals.append(theta_i_interval)
num_oracle_queries = 0 # no Q-oracle call, only a single one to A
break
counts = {
k: round(v * shots)
for k, v in ret.quasi_dists[0].binary_probabilities().items()
}
# calculate the probability of measuring '1', 'prob' is a_i in the paper
num_qubits = circuit.num_qubits - circuit.num_ancillas
# type: ignore
one_counts, prob = self._good_state_probability(
estimation_problem, counts, num_qubits
)
num_one_shots.append(one_counts)
# track number of Q-oracle calls
num_oracle_queries += shots * k
# if on the previous iterations we have K_{i-1} == K_i, we sum these samples up
j = 1 # number of times we stayed fixed at the same K
round_shots = shots
round_one_counts = one_counts
if num_iterations > 1:
while (
powers[num_iterations - j] == powers[num_iterations]
and num_iterations >= j + 1
):
j = j + 1
round_shots += shots
round_one_counts += num_one_shots[-j]
# compute a_min_i, a_max_i
if self._confint_method == "chernoff":
a_i_min, a_i_max = _chernoff_confint(prob, round_shots, max_rounds, self._alpha)
else: # 'beta'
a_i_min, a_i_max = _clopper_pearson_confint(
round_one_counts, round_shots, self._alpha / max_rounds
)
# compute theta_min_i, theta_max_i
if upper_half_circle:
theta_min_i = np.arccos(1 - 2 * a_i_min) / 2 / np.pi
theta_max_i = np.arccos(1 - 2 * a_i_max) / 2 / np.pi
else:
theta_min_i = 1 - np.arccos(1 - 2 * a_i_max) / 2 / np.pi
theta_max_i = 1 - np.arccos(1 - 2 * a_i_min) / 2 / np.pi
# compute theta_u, theta_l of this iteration
scaling = 4 * k + 2 # current K_i factor
theta_u = (int(scaling * theta_intervals[-1][1]) + theta_max_i) / scaling
theta_l = (int(scaling * theta_intervals[-1][0]) + theta_min_i) / scaling
theta_intervals.append([theta_l, theta_u])
# compute a_u_i, a_l_i
a_u = np.sin(2 * np.pi * theta_u) ** 2
a_l = np.sin(2 * np.pi * theta_l) ** 2
a_u = cast(float, a_u)
a_l = cast(float, a_l)
a_intervals.append([a_l, a_u])
# get the latest confidence interval for the estimate of a
confidence_interval = tuple(a_intervals[-1])
# the final estimate is the mean of the confidence interval
estimation = np.mean(confidence_interval)
result = IterativeAmplitudeEstimationResult()
result.alpha = self._alpha
result.post_processing = estimation_problem.post_processing
result.num_oracle_queries = num_oracle_queries
result.estimation = estimation
result.epsilon_estimated = (confidence_interval[1] - confidence_interval[0]) / 2
result.confidence_interval = confidence_interval
result.estimation_processed = estimation_problem.post_processing(estimation)
confidence_interval = tuple(
estimation_problem.post_processing(x) for x in confidence_interval
)
result.confidence_interval_processed = confidence_interval
result.epsilon_estimated_processed = (confidence_interval[1] - confidence_interval[0]) / 2
result.estimate_intervals = a_intervals
result.theta_intervals = theta_intervals
result.powers = powers
result.ratios = ratios
return result
class IterativeAmplitudeEstimationResult(AmplitudeEstimatorResult):
"""The ``IterativeAmplitudeEstimation`` result object."""
def __init__(self) -> None:
super().__init__()
self._alpha: float | None = None
self._epsilon_target: float | None = None
self._epsilon_estimated: float | None = None
self._epsilon_estimated_processed: float | None = None
self._estimate_intervals: list[list[float]] | None = None
self._theta_intervals: list[list[float]] | None = None
self._powers: list[int] | None = None
self._ratios: list[float] | None = None
self._confidence_interval_processed: tuple[float, float] | None = None
@property
def alpha(self) -> float:
r"""Return the confidence level :math:`\alpha`."""
return self._alpha
@alpha.setter
def alpha(self, value: float) -> None:
r"""Set the confidence level :math:`\alpha`."""
self._alpha = value
@property
def epsilon_target(self) -> float:
"""Return the target half-width of the confidence interval."""
return self._epsilon_target
@epsilon_target.setter
def epsilon_target(self, value: float) -> None:
"""Set the target half-width of the confidence interval."""
self._epsilon_target = value
@property
def epsilon_estimated(self) -> float:
"""Return the estimated half-width of the confidence interval."""
return self._epsilon_estimated
@epsilon_estimated.setter
def epsilon_estimated(self, value: float) -> None:
"""Set the estimated half-width of the confidence interval."""
self._epsilon_estimated = value
@property
def epsilon_estimated_processed(self) -> float:
"""Return the post-processed estimated half-width of the confidence interval."""
return self._epsilon_estimated_processed
@epsilon_estimated_processed.setter
def epsilon_estimated_processed(self, value: float) -> None:
"""Set the post-processed estimated half-width of the confidence interval."""
self._epsilon_estimated_processed = value
@property
def estimate_intervals(self) -> list[list[float]]:
"""Return the confidence intervals for the estimate in each iteration."""
return self._estimate_intervals
@estimate_intervals.setter
def estimate_intervals(self, value: list[list[float]]) -> None:
"""Set the confidence intervals for the estimate in each iteration."""
self._estimate_intervals = value
@property
def theta_intervals(self) -> list[list[float]]:
"""Return the confidence intervals for the angles in each iteration."""
return self._theta_intervals
@theta_intervals.setter
def theta_intervals(self, value: list[list[float]]) -> None:
"""Set the confidence intervals for the angles in each iteration."""
self._theta_intervals = value
@property
def powers(self) -> list[int]:
"""Return the powers of the Grover operator in each iteration."""
return self._powers
@powers.setter
def powers(self, value: list[int]) -> None:
"""Set the powers of the Grover operator in each iteration."""
self._powers = value
@property
def ratios(self) -> list[float]:
r"""Return the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`."""
return self._ratios
@ratios.setter
def ratios(self, value: list[float]) -> None:
r"""Set the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`."""
self._ratios = value
@property
def confidence_interval_processed(self) -> tuple[float, float]:
"""Return the post-processed confidence interval."""
return self._confidence_interval_processed
@confidence_interval_processed.setter
def confidence_interval_processed(self, value: tuple[float, float]) -> None:
"""Set the post-processed confidence interval."""
self._confidence_interval_processed = value
def _chernoff_confint(
value: float, shots: int, max_rounds: int, alpha: float
) -> tuple[float, float]:
"""Compute the Chernoff confidence interval for `shots` i.i.d. Bernoulli trials.
The confidence interval is
[value - eps, value + eps], where eps = sqrt(3 * log(2 * max_rounds/ alpha) / shots)
but at most [0, 1].
Args:
value: The current estimate.
shots: The number of shots.
max_rounds: The maximum number of rounds, used to compute epsilon_a.
alpha: The confidence level, used to compute epsilon_a.
Returns:
The Chernoff confidence interval.
"""
eps = np.sqrt(3 * np.log(2 * max_rounds / alpha) / shots)
lower = np.maximum(0, value - eps)
upper = np.minimum(1, value + eps)
return lower, upper
def _clopper_pearson_confint(counts: int, shots: int, alpha: float) -> tuple[float, float]:
"""Compute the Clopper-Pearson confidence interval for `shots` i.i.d. Bernoulli trials.
Args:
counts: The number of positive counts.
shots: The number of shots.
alpha: The confidence level for the confidence interval.
Returns:
The Clopper-Pearson confidence interval.
"""
lower, upper = 0, 1
# if counts == 0, the beta quantile returns nan
if counts != 0:
lower = beta.ppf(alpha / 2, counts, shots - counts + 1)
# if counts == shots, the beta quantile returns nan
if counts != shots:
upper = beta.ppf(1 - alpha / 2, counts + 1, shots - counts)
return lower, upper
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 4 17:53:16 2022
@author: pejmanjouzdani
"""
import logging
from time import time
class TestCirc:
def __init__(self, func, FLAG=False):
self.func = func
self.func.name = func.__name__
self.FLAG=FLAG
def __call__(self, *args, **kwargs):
#### If the flag is ON
if self.FLAG==True:
try:
results = self.test1(self.func , *args, **kwargs)
except:
raise
# if successful do other tests...
print(results)
return results
#### If the flag is OFF: just run the function
else:
return self.func(*args, **kwargs)
@staticmethod
def test1( func, *args, **kwargs):
pass
# time
start = time()
results = func(*args, **kwargs)
### cmpare with hat is expected using *args etc.
end_time = time()
logging.info('\n %s function takes %s second to run'%(func.name, end_time - start) )
print('\n %s function takes %s second to run'%(func.name, end_time - start))
return results
def test2(self, *args, **kwargs):
NotImplemented
if __name__=='__main__':
from qiskit import QuantumCircuit
from BasicFunctions.functions import getQCirc, getUQUCirc
tested_func= TestCirc(getQCirc, FLAG=True)
number_qubits= 3
Q = [1,2,3]
circ = QuantumCircuit(number_qubits)
circ_Q = tested_func(circ, Q)
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
with open('in-exemplo.txt', 'r') as f:
print(f.read())
with open('out-exemplo.txt', 'r') as f:
print(f.read())
import time
import matplotlib.pyplot as plt
import pandas as pd
import os
import subprocess
%matplotlib inline
#Roda entradas
def roda_com_entrada(executavel, arquivo_in, envs = '1', deb = '0'):
with open(arquivo_in) as f:
start = time.perf_counter()
a = f.read()
proc = subprocess.run([executavel], input=a, text=True, capture_output=True, env=dict(OMP_NUM_THREADS=envs, DEBUG=deb, **os.environ))
end = time.perf_counter()
f.close()
ret = ''
for i in a:
if i == "\n":
break
ret += i
return (proc.stdout, end - start, int(ret))
v
#retorna tamanho do tour apartir do stdout
buf = ''
for i in out:
if i == " ":
return float(buf)
buf += i
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
tempos_2 = []
resultados1 = []
resultados2 = []
resultados3 = []
#Usando as mesmas entradas
for i in range(8):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca_local_antigo','busca-exaustiva/in-'+str(i)+'.txt')
b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt')
c = roda_com_entrada('./heuristico/heuristico','busca-exaustiva/in-'+str(i)+'.txt')
tempos.append(a[1])
tempos_1.append(b[1])
tempos_2.append(c[1])
tamanho_entradas.append(a[2])
resultados1.append(tamanho_tour(a[0]))
resultados2.append(tamanho_tour(b[0]))
resultados3.append(tamanho_tour(c[0]))
#Teste com entrada um pouco maior
print("Rodando entrada: 8")
tempos.append(roda_com_entrada('./busca_local_antigo','maior.txt')[1])
tempos_1.append(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[1])
tempos_2.append(roda_com_entrada('./heuristico/heuristico','maior.txt')[1])
tamanho_entradas.append(roda_com_entrada('./busca-local/busca-local','maior.txt')[2])
resultados1.append(tamanho_tour(roda_com_entrada('./busca_local_antigo','maior.txt')[0]))
resultados2.append(tamanho_tour(roda_com_entrada('./busca-exaustiva/busca-exaustiva','maior.txt')[0]))
resultados3.append(tamanho_tour(roda_com_entrada('./heuristico/heuristico','maior.txt')[0]))
plt.title("Comparacao Desempenho")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos_1)
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_2)
plt.legend(["busca-exaustiva", "busca-local","heuristico"])
plt.show()
plt.title("Comparacao Desempenho")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_2)
plt.legend(["busca-local","heuristico"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-local-tempo"] = pd.Series(tempos)
df["busca-exaustiva-tempo"] = pd.Series(tempos_1)
df["heuristica-tempo"] = pd.Series(tempos_2)
df["busca-local-resultado"] = pd.Series(resultados1)
df["busca-exaustiva-resultado"] = pd.Series(resultados2)
df["heuristica-resultado"] = pd.Series(resultados3)
df
df.describe()
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
tempos_2 = []
tempos_3 = []
tempos_4 = []
tempos_5 = []
#Usando as mesmas entradas
for i in range(7):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt')
b = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','2')
c = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','3')
d = roda_com_entrada('./busca-local/busca-local-paralela','busca-local/in-'+str(i)+'.txt','4')
e = roda_com_entrada('./busca_local_antigo','busca-local/in-'+str(i)+'.txt')
f = roda_com_entrada('./busca-local/busca-local-gpu','busca-local/in-'+str(i)+'.txt')
tempos.append(a[1])
tempos_1.append(b[1])
tempos_2.append(c[1])
tempos_3.append(d[1])
tempos_4.append(e[1])
tempos_5.append(f[1])
tamanho_entradas.append(a[2])
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_1)
plt.plot(tamanho_entradas, tempos_2)
plt.plot(tamanho_entradas, tempos_3)
plt.legend(["1 thread otimizado", "2 threads otimizado","3 threads otimizado", "4 threads otimizado", "Sem otimizações"])
plt.show()
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos_3)
plt.plot(tamanho_entradas, tempos_5)
plt.legend(["4 thread otimizado", "GPU"])
plt.show()
plt.title("Comparacao Desempenho Busca Local")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_4)
plt.legend(["1 thread otimizado", "Sem otimizações"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-local-1-thread"] = pd.Series(tempos)
df["busca-local-2-threads"] = pd.Series(tempos_1)
df["busca-local-3-threads"] = pd.Series(tempos_2)
df["busca-local-4-threads"] = pd.Series(tempos_3)
df["busca-local-gpu"] = pd.Series(tempos_5)
df["busca-local-semopt"] = pd.Series(tempos_4)
df
#Cria resultados
tamanho_entradas = []
tempos = []
tempos_1 = []
tempos_2 = []
#Usando as mesmas entradas
for i in range(8):
print("Rodando entrada: "+str(i))
if i != 7:
a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1')
tempos.append(a[1])
b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '8', '0')
c = roda_com_entrada('./busca-exaustiva-apenasbb','busca-exaustiva/in-'+str(i)+'.txt', '1', '0')
tempos_1.append(b[1])
tempos_2.append(c[1])
tamanho_entradas.append(a[2])
plt.title("Comparacao Desempenho Busca Exaustiva")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas[:-1], tempos)
plt.plot(tamanho_entradas[:-1], tempos_2[:-1])
plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"])
plt.show()
plt.title("Comparacao Desempenho Busca Exaustiva")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos_1)
plt.plot(tamanho_entradas, tempos_2)
plt.legend(["Branch and Bound Paralelo", "Branch and Bound Simples"])
plt.show()
df = pd.DataFrame()
df["Tamanho Entrada"] = pd.Series(tamanho_entradas)
df["busca-exaustiva-simples"] = pd.Series(tempos)
df["busca-exaustiva-branchnbound"] = pd.Series(tempos_2)
df["busca-exaustiva-branchnbound-par"] = pd.Series(tempos_1)
df
|
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 layouts of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import layouts
class TestBitArrange(QiskitTestCase):
"""Tests for layout.bit_arrange."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
qregs = qiskit.QuantumRegister(3)
cregs = qiskit.ClassicalRegister(3)
self.regs = list(qregs) + list(cregs)
def test_qreg_creg_ascending(self):
"""Test qreg_creg_ascending layout function."""
sorted_regs = layouts.qreg_creg_ascending(self.regs)
ref_regs = [
self.regs[0],
self.regs[1],
self.regs[2],
self.regs[3],
self.regs[4],
self.regs[5],
]
self.assertListEqual(sorted_regs, ref_regs)
def test_qreg_creg_descending(self):
"""Test qreg_creg_descending layout function."""
sorted_regs = layouts.qreg_creg_descending(self.regs)
ref_regs = [
self.regs[2],
self.regs[1],
self.regs[0],
self.regs[5],
self.regs[4],
self.regs[3],
]
self.assertListEqual(sorted_regs, ref_regs)
class TestAxisMap(QiskitTestCase):
"""Tests for layout.time_axis_map."""
def test_time_map_in_dt(self):
"""Test time_map_in_dt layout function."""
axis_config = layouts.time_map_in_dt(time_window=(-100, 500))
self.assertEqual(axis_config.window, (-100, 500))
self.assertEqual(axis_config.label, "System cycle time (dt)")
ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"}
self.assertDictEqual(axis_config.axis_map, ref_map)
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
from calibration import *
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main')
"""
Object to calibrate pulse of backend and qubit of interest.
"""
# Importing required python packages
from warnings import warn
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.signal import find_peaks
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# Importing standard Qiskit libraries
from qiskit import IBMQ, execute, pulse
from qiskit.providers.ibmq import IBMQBackend
from qiskit.pulse import DriveChannel, Schedule, Play
from qiskit.pulse import library as pulse_lib
from qiskit.pulse.library import Waveform, Gaussian
from qiskit.tools.monitor import job_monitor
from qiskit.providers.exceptions import QiskitBackendNotFoundError, BackendConfigurationError
# Loading your IBM Q account(s)
#IBMQ.load_account()
#provider = IBMQ.get_provider()
class PulseCalibration():
"""Creates an object that is used for pulse calibration.
Args:
backend (IBMQBackend) : The IBMQBackend for which pulse calibration needs to be done.
qubit (int) : The qubit for which the pulse calibration is done.
qubit_freq_ground (float) : Custom frequency for 0->1 transition.
qubit_freq_excited (float) : Custom frequency for 1->2 transition.
pi_amp_ground (float) : Custom pi amplitude for 0->1 transition.
The value should be between 0 and 1.
pi_amp_excited (float) : Custom pi amplitude for 1->2 transition.
The value should be between 0 and 1.
pulse_dur (int) : The duration of the pi pulse to be used for calibration.
pulse_sigma (int) : The standard deviation of the pi pulse to be used for calibration.
"""
def __init__(self, backend, qubit, qubit_freq_ground=None, qubit_freq_excited=None,
pi_amp_ground=None, pi_amp_excited=None, pulse_dur=None, pulse_sigma=None):
# pylint: disable=too-many-locals
# pylint: disable=too-many-arguments
if not isinstance(backend, IBMQBackend):
raise QiskitBackendNotFoundError("Provided backend not available." +
"Please provide backend after obtaining from IBMQ.")
self._backend = backend
self._back_config = backend.configuration()
if qubit >= self._back_config.n_qubits:
raise BackendConfigurationError(f"Qubit {qubit} not present in the provided backend.")
self._qubit = qubit
self._back_defaults = backend.defaults()
self._qubit_anharmonicity = backend.properties().qubit_property(self._qubit)['anharmonicity'][0]
self._dt = self._back_config.dt
self._qubit_freq = self._back_defaults.qubit_freq_est[self._qubit]
self._inst_sched_map = self._back_defaults.instruction_schedule_map
self._drive_chan = DriveChannel(qubit)
if pulse_sigma:
self._pulse_sigma = pulse_sigma
else:
if self._backend.name() == 'ibmq_armonk':
self._pulse_sigma = 80
else:
self._pulse_sigma = 40
if pulse_dur:
self._pulse_duration = pulse_dur
else:
self._pulse_duration = (4*self._pulse_sigma)-((4*self._pulse_sigma) % 16)
self._qubit_freq_ground = qubit_freq_ground
self._qubit_freq_excited = qubit_freq_excited
self._pi_amp_ground = pi_amp_ground
self._pi_amp_excited = pi_amp_excited
self._state_discriminator_012 = None
# Find out which measurement map index is needed for this qubit
meas_map_idx = None
for i, measure_group in enumerate(self._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!"
# The measurement pulse for measuring the qubit of interest.
self._measure = self._inst_sched_map.get('measure',
qubits=self._back_config.meas_map[meas_map_idx])
def create_cal_circuit(self, amp):
"""Constructs and returns a schedule containing Gaussian pulse with amplitude as 'amp',
sigma as 'pulse_sigma' and duration as 'pulse_duration'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=amp), self._drive_chan)
sched += self._measure << sched.duration
return sched
def create_cal_circuit_excited(self, base_pulse, freq):
""" Constructs and returns a schedule containing a pi pulse for 0->1 transition followed by
a sidebanded pulse which corresponds to applying 'base_pulse' at frequency 'freq'."""
sched = Schedule()
sched += Play(Gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_ground), self._drive_chan)
sched += Play(self.apply_sideband(base_pulse, freq), self._drive_chan)
sched += self._measure << sched.duration
return sched
@staticmethod
def _fit_function(x_values, y_values, function, init_params):
""" A function fitter. Returns the fit parameters of 'function'."""
fitparams, _ = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
@staticmethod
def _baseline_remove(values):
"""Centering data around zero."""
return np.array(values) - np.mean(values)
def apply_sideband(self, pulse, frequency):
"""Apply a sine sideband to 'pulse' at frequency 'freq'.
Args:
pulse (Waveform): The pulse to which sidebanding is to be applied.
frequency (float): LO frequency at which the pulse is to be applied.
Returns:
Waveform: The sidebanded pulse.
"""
t_samples = np.linspace(0, self._dt*self._pulse_duration, self._pulse_duration)
sine_pulse = np.sin(2*np.pi*(frequency-self._qubit_freq_ground)*t_samples)
sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse),
name='sideband_pulse')
return sideband_pulse
def get_job_data(self, job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
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)[self._qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, self._qubit]*scale_factor)
return result_data
# Prints out relative maxima frequencies in output_data; height gives lower bound (abs val)
@staticmethod
def _rel_maxima(freqs, output_data, height, distance):
"""Prints out relative maxima frequencies in output_data (can see peaks);
height gives upper bound (abs val). Be sure to set the height properly or
the peak will be ignored!
Args:
freqs (list): frequency list
output_data (list): list of resulting signals
height (float): upper bound (abs val) on a peak
width (float):
Returns:
list: List containing relative maxima frequencies
"""
peaks, _ = find_peaks(x=output_data, height=height, distance=distance)
return freqs[peaks]
def find_freq_ground(self, verbose=False, visual=False):
"""Sets and returns the calibrated frequency corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
sched_list = [self.create_cal_circuit(0.5)]*75
freq_list = np.linspace(self._qubit_freq-(45*1e+6), self._qubit_freq+(45*1e+6), 75)
sweep_job = execute(sched_list, backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los = [{self._drive_chan: freq} for freq in freq_list])
jid = sweep_job.job_id()
if verbose:
print("Executing the Frequency sweep job for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(sweep_job)
sweep_job = self._backend.retrieve_job(jid)
sweep_result = sweep_job.result()
sweep_values = []
for i in range(len(sweep_result.results)):
# Get the results from the ith experiment
res = sweep_result.get_memory(i)*1e-14
# Get the results for `qubit` from this experiment
sweep_values.append(res[self._qubit])
freq_list_GHz = freq_list/1e+9
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# def find_init_params(freq_list, res_values):
# hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
# hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
# if hmin_index < hmax_index:
# est_baseline = min(res_values)
# est_slope = (res_values[hmax_index] - res_values[hmin_index])/(freq_list[hmax_index] - freq_list[hmin_index])
# else:
# est_baseline = max(res_values)
# est_slope = (res_values[hmin_index] - res_values[hmax_index])/(freq_list[hmin_index] - freq_list[hmax_index])
# return [est_slope, self._qubit_freq/1e9, 1, est_baseline]
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
init_params = find_init_params_gauss(freq_list_GHz, np.real(sweep_values))
# init_params = find_init_params(freq_list_GHz, np.real(sweep_values))
print('ground freq init params : ', init_params)
# Obtain the optimal paramters that fit the result data.
# fit_params, y_fit = self._fit_function(freq_list_GHz,
# np.real(sweep_values),
# lorentzian,
# init_params # init parameters for curve_fit
# )
fit_params, y_fit = self._fit_function(freq_list_GHz,
np.real(sweep_values),
gauss,
init_params # init parameters for curve_fit
)
if visual:
print("The frequency-signal plot for frequency sweep: ")
plt.scatter(freq_list_GHz, np.real(sweep_values), color='black')
plt.plot(freq_list_GHz, y_fit, color='red')
plt.xlim([min(freq_list_GHz), max(freq_list_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
qubit_freq_new, _, _, _ = fit_params
self._qubit_freq_ground = qubit_freq_new*1e9
if verbose:
print(f"The calibrate frequency for the 0->1 transition is {self._qubit_freq_ground}")
return [self._qubit_freq_ground, freq_list_GHz, sweep_values]
def find_pi_amp_ground(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 0->1 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_ground(verbose, visual)
amp_list = np.linspace(0, 1, 75)
rabi_sched_list = [self.create_cal_circuit(amp) for amp in amp_list]
rabi_list_len = len(rabi_sched_list)
rabi_job = execute(rabi_sched_list,backend=self._backend, meas_level=1, meas_return='avg',
shots=1024, schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(rabi_sched_list))
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job to get Pi pulse for 0->1 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
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)[self._qubit]*scale_factor)
rabi_values = np.real(self._baseline_remove(rabi_values))
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
# Obtain the optimal paramters that fit the result data.
init_params = find_init_params_amp(amp_list,rabi_values)
fit_params, y_fit = self._fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period = fit_params[2]
self._pi_amp_ground = drive_period/2
if verbose:
print(f"The Pi amplitude of 0->1 transition is {self._pi_amp_ground}.")
if visual:
print("The amplitude-signal plot for rabi oscillation for 0->1 transition.")
plt.figure()
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()
return [self._pi_amp_ground, amp_list, rabi_values]
def find_freq_excited(self, verbose=False, visual=False):
"""Sets and returns the frequency corresponding to 1->2 transition."""
# pylint: disable=too-many-locals
if not self._qubit_freq_ground:
raise ValueError("The qubit_freq_ground is not determined. Please determine" +
"qubit_freq_ground first.")
if not self._pi_amp_ground:
raise ValueError("The pi_amp_ground is not determined.\
Please determine pi_amp_ground first.")
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=0.3)
sched_list = []
# Here we assume that the anharmocity is about 8% for all qubits.
excited_freq_list = self._qubit_freq_ground + self._qubit_anharmonicity + np.linspace(-30*1e+6, 30*1e+6, 75)
for freq in excited_freq_list:
sched_list.append(self.create_cal_circuit_excited(base_pulse, freq))
excited_sweep_job = execute(sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*len(excited_freq_list)
)
jid = excited_sweep_job.job_id()
excited_freq_list_GHz = excited_freq_list/1e+9
if verbose:
print("Executing the Frequency sweep job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(excited_sweep_job)
excited_sweep_job = self._backend.retrieve_job(jid)
excited_sweep_data = self.get_job_data(excited_sweep_job, average=True)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list_GHz, excited_sweep_data, color='black')
plt.xlim([min(excited_freq_list_GHz), max(excited_freq_list_GHz)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
def find_init_params_gauss(freq_list, res_values):
hmin_index = np.where(res_values==min(res_values[:len(freq_list)//2]))[0][0]
hmax_index = np.where(res_values==max(res_values[:len(freq_list)//2]))[0][0]
mean_est = freq_list[hmax_index]
var_est = np.abs(freq_list[hmax_index]-freq_list[hmin_index])/2
scale_est = max(res_values)-min(res_values)
shift_est = min(res_values)
return [mean_est, var_est, scale_est, shift_est]
def gauss(x, mean, var, scale, shift):
return (scale*(1/var*np.sqrt(2*np.pi))*np.exp(-(1/2)*(((x-mean)/var)**2)))+shift
def lorentzian(xval, scale, q_freq, hwhm, shift):
return (scale / np.pi) * (hwhm / ((xval - q_freq)**2 + hwhm**2)) + shift
# do fit in Hz
# init_params = find_init_params(excited_freq_list_GHz, np.real(excited_sweep_data))
init_params = find_init_params_gauss(excited_freq_list_GHz, np.real(excited_sweep_data))
print("Init params : ", init_params)
excited_sweep_fit_params, excited_sweep_y_fit = self._fit_function(excited_freq_list_GHz,
excited_sweep_data,
gauss,
init_params
)
if visual:
print("The frequency-signal plot of frequency sweep for 1->2 transition.")
# Note: we are only plotting the real part of the signal
plt.scatter(excited_freq_list/1e+9, excited_sweep_data, color='black')
plt.plot(excited_freq_list/1e+9, excited_sweep_y_fit, color='red')
plt.xlim([min(excited_freq_list/1e+9), max(excited_freq_list/1e+9)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep", fontsize=15)
plt.show()
qubit_freq_12, _, _, _ = excited_sweep_fit_params
self._qubit_freq_excited = qubit_freq_12*1e+9
if verbose:
print(f"The calibrated frequency for the 1->2 transition\
is {self._qubit_freq_excited}.")
return [self._qubit_freq_excited, excited_freq_list, excited_sweep_data]
def find_pi_amp_excited(self, verbose=False, visual=False):
"""Sets and returns the amplitude of the pi pulse corresponding to 1->2 transition."""
if not self._qubit_freq_excited:
warn("ground_qubit_freq not computed yet and custom qubit freq not provided." +
"Computing ground_qubit_freq now.")
self._qubit_freq_ground = self.find_freq_excited(verbose, visual)
amp_list = np.linspace(0, 1.0, 75)
rabi_sched_list = []
for amp in amp_list:
base_pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=amp)
rabi_sched_list.append(self.create_cal_circuit_excited(base_pulse,
self._qubit_freq_excited))
rabi_job = execute(rabi_sched_list, backend=self._backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*75
)
jid = rabi_job.job_id()
if verbose:
print("Executing the rabi oscillation job for 1->2 transition.")
print('Job Id : ', jid)
# job_monitor(rabi_job)
rabi_job = self._backend.retrieve_job(jid)
rabi_data = self.get_job_data(rabi_job, average=True)
rabi_data = np.real(self._baseline_remove(rabi_data))
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
def find_init_params_amp(amp_list, rabi_values):
min_index = np.where(rabi_values==min(rabi_values))[0][0]
max_index = np.where(rabi_values==max(rabi_values))[0][0]
scale_est = (max(rabi_values) - min(rabi_values))/2
shift_est = (max(rabi_values) + min(rabi_values))/2
shift_est = np.mean(rabi_values)
period_est = 0.5
if ((max(rabi_values)-rabi_values[0])/(2*scale_est)) < 0.5:
phi_est = np.pi/2
else:
phi_est = -np.pi/2
return [scale_est, shift_est, period_est, phi_est]
init_params = find_init_params_amp(amp_list, rabi_data)
print('Init params for 01 amp : ', init_params)
(rabi_fit_params,
rabi_y_fit) = self._fit_function(amp_list,
rabi_data,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
init_params)
drive_period_excited = rabi_fit_params[2]
pi_amp_excited = (drive_period_excited/2/np.pi) * (np.pi+rabi_fit_params[3])
self._pi_amp_excited = pi_amp_excited
if visual:
print("The amplitude-signal plot of rabi oscillation for 1->2 transition.")
plt.figure()
plt.scatter(amp_list, rabi_data, color='black')
plt.plot(amp_list, rabi_y_fit, color='red')
# account for phi in computing pi amp
plt.axvline(self._pi_amp_excited, color='red', linestyle='--')
plt.axvline(self._pi_amp_excited+drive_period_excited/2, color='red', linestyle='--')
plt.annotate("", xy=(self._pi_amp_excited+drive_period_excited/2, 0),
xytext=(self._pi_amp_excited, 0),
arrowprops=dict(arrowstyle="<->", color='red'))
#plt.annotate("$\\pi$", xy=(self._pi_amp_excited-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.title('Rabi Experiment (1->2)', fontsize=20)
plt.show()
return [self._pi_amp_excited, amp_list, rabi_data]
def get_pi_pulse_ground(self):
"""Returns a pi pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground)
return pulse
def get_pi_pulse_excited(self):
"""Returns a pi pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_x90_pulse_ground(self):
"""Returns a pi/2 pulse of the 0->1 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration,
sigma=self._pulse_sigma, amp=self._pi_amp_ground/2)
return pulse
def get_x90_pulse_excited(self):
"""Returns a pi/2 pulse of the 1->2 transition."""
pulse = pulse_lib.gaussian(duration=self._pulse_duration, sigma=self._pulse_sigma,
amp=self._pi_amp_excited/2)
excited_pulse = self.apply_sideband(pulse, self._qubit_freq_excited)
return excited_pulse
def get_zero_sched(self):
"""Returns a schedule that performs only a measurement."""
zero_sched = Schedule()
zero_sched += self._measure
return zero_sched
def get_one_sched(self):
"""Returns a schedule that creates a |1> state from |0> by applying
a pi pulse of 0->1 transition and performs a measurement."""
one_sched = Schedule()
one_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
one_sched += self._measure << one_sched.duration
return one_sched
def get_two_sched(self):
"""Returns a schedule that creates a |2> state from |0> by applying
a pi pulse of 0->1 transition followed by applying a pi pulse
of 1->2 transition and performs a measurement."""
two_sched = Schedule()
two_sched += Play(self.get_pi_pulse_ground(), self._drive_chan)
two_sched += Play(self.get_pi_pulse_excited(), self._drive_chan)
two_sched += self._measure << two_sched.duration
return two_sched
@staticmethod
def _create_iq_plot(zero_data, one_data, two_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$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_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)
mean_two = np.mean(two_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.scatter(np.real(mean_two), np.imag(mean_two),
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-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
@staticmethod
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def find_three_level_discriminator(self, verbose=False, visual=False):
"""Returns a discriminator for discriminating 0-1-2 states."""
# pylint: disable=too-many-locals
zero_sched = self.get_zero_sched()
one_sched = self.get_one_sched()
two_sched = self.get_two_sched()
iq_job = execute([zero_sched, one_sched, two_sched], backend=self._backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{self._drive_chan: self._qubit_freq_ground}]*3
)
jid = iq_job.job_id()
if verbose:
print('Job Id : ', jid)
# job_monitor(iq_job)
iq_job = self._backend.retrieve_job(jid)
iq_data = self.get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = self._create_iq_plot(zero_data, one_data, two_data)
# Create IQ vector (split real, imag parts)
zero_data_reshaped = self.reshape_complex_vec(zero_data)
one_data_reshaped = self.reshape_complex_vec(one_data)
two_data_reshaped = self.reshape_complex_vec(two_data)
iq_data = np.concatenate((zero_data_reshaped, one_data_reshaped, two_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
iq_012_train, iq_012_test, state_012_train, state_012_test = train_test_split(iq_data,
state_012,
test_size=0.5)
classifier_lda_012 = LinearDiscriminantAnalysis()
classifier_lda_012.fit(iq_012_train, state_012_train)
score_012 = classifier_lda_012.score(iq_012_test, state_012_test)
if verbose:
print('The accuracy score of the discriminator is: ', score_012)
self._state_discriminator_012 = classifier_lda_012
if visual:
self._separatrix_plot(classifier_lda_012, x_min, x_max, y_min, y_max, 1024)
return self._state_discriminator_012
@staticmethod
def _separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min, x_max, num_x),
np.linspace(y_min, y_max, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_qubit_freq_ground(self):
"""Returns the set 0->1 transition frequency."""
return self._qubit_freq_ground
def get_qubit_freq_excited(self):
"""Returns the set 1->2 transition frequency."""
return self._qubit_freq_excited
def get_pi_amp_ground(self):
"""Returns the set 0->1 transition pi pulse amplitude."""
return self._pi_amp_ground
def get_pi_amp_excited(self):
"""Returns the set 1->2 transition pi pulse amplitude."""
return self._pi_amp_excited
def get_three_level_discriminator(self):
"""Returns the set 0-1-2 state discriminator."""
return self._state_discriminator_012
def calibrate_all(self, verbose=False, visual=False):
"""Calibrates and sets both the ground and excited transition frequencies and
corresponding pi pulse amplitudes. Also constructs a 0-1-2 state discriminator."""
ground_freq = self.find_freq_ground(verbose, visual)
ground_amp = self.find_pi_amp_ground(verbose, visual)
excited_freq = self.find_freq_excited(verbose, visual)
excited_amp = self.find_pi_amp_excited(verbose, visual)
state_discriminator = self.find_three_level_discriminator(verbose, visual)
return ground_freq, ground_amp, excited_freq, excited_amp, state_discriminator
anharmon = backend.properties().qubit_property(qubit)['anharmonicity'][0]
qu_freq = backend.properties().qubit_property(qubit)['frequency'][0]
print(qu_freq)
print(anharmon)
print(qu_freq+anharmon)
# backend = provider.get_backend('ibmq_casablanca')
# backend = provider.get_backend('ibmq_jakarta')
backend = provider.get_backend('ibmq_bogota')
# backend = provider.get_backend('ibmq_rome')
qubit = 0
cal_object = PulseCalibration(backend, qubit)
visual = True
verbose = True
ground_freq_list = cal_object.find_freq_ground(verbose, visual)
[ground_freq, freq_list, sweep_vals] = ground_freq_list
print(ground_freq)
ground_amp_list = cal_object.find_pi_amp_ground(verbose, visual)
pi_amp_ground = ground_amp_list[0]
amp_list = ground_amp_list[1]
rabi_values = ground_amp_list[2]
print(ground_freq)
print(pi_amp_ground)
excited_list = cal_object.find_freq_excited(verbose, visual)
excited_freq = excited_list[0]
excited_freq_list = excited_list[1]
excited_sweep_data = excited_list[2]
excited_freq_list_GHz = excited_freq_list/1e+9
excited_freq
pi_amp_excited_list = cal_object.find_pi_amp_excited(verbose, visual)
[excited_amp, amp_list, rabi_data] = pi_amp_excited_list
pi_amp_excited = excited_amp
pi_amp_excited
print(ground_freq)
print(pi_amp_ground)
print(excited_freq)
print(pi_amp_excited)
discrim = cal_object.find_three_level_discriminator(verbose, visual)
def create_iq_plot(zero_data, one_data, two_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$')
# two data plotted in green
plt.scatter(np.real(two_data), np.imag(two_data),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'$|2\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))-5
x_max = np.max(np.append(np.real(zero_data), np.append(np.real(one_data),
np.real(two_data))))+5
y_min = np.min(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_data))))-5
y_max = np.max(np.append(np.imag(zero_data), np.append(np.imag(one_data),
np.imag(two_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)
mean_two = np.mean(two_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.scatter(np.real(mean_two), np.imag(mean_two),
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-2 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
def reshape_complex_vec(vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries.
This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i, item in enumerate(vec):
vec_reshaped[i] = [np.real(item), np.imag(item)]
return vec_reshaped
def separatrix_plot(lda, x_min, x_max, y_min, y_max, shots):
"""Returns a sepratrix plot for the classifier."""
# pylint: disable=too-many-arguments
num_x, num_y = shots, shots
xvals, vals = np.meshgrid(np.linspace(x_min-4, x_max+4, num_x),
np.linspace(y_min-4, y_max+4, num_y))
predict_prob = lda.predict_proba(np.c_[xvals.ravel(), vals.ravel()])
predict_prob = predict_prob[:, 1].reshape(xvals.shape)
plt.contour(xvals, vals, predict_prob, [0.5], linewidths=2., colors='black')
def get_job_data(job, average):
"""Retrieve data from a job that has already run.
Args:
job (Job): The job whose data you want.
average (bool): If True, gets the data assuming data is an average.
If False, gets the data assuming it is for single shots.
Return:
list: List containing job result data.
"""
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
iq_job = backend.retrieve_job('60b500cf5255f0280438b583')
iq_data = get_job_data(iq_job, average=False)
zero_data = iq_data[0]
one_data = iq_data[1]
two_data = iq_data[2]
if visual:
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = create_iq_plot(zero_data, one_data, two_data)
newcalobject = PulseCalibration(backend, qubit)
output_list = newcalobject.calibrate_all(verbose, visual)
[new_ground_freq, new_pi_amp_ground, new_excited_freq, new_pi_amp_excited, new_discrim] = output_list
print(new_ground_freq[0])
print(new_pi_amp_ground[0])
print(new_excited_freq[0])
print(new_pi_amp_excited[0])
back_config = backend.configuration()
back_defaults = backend.defaults()
inst_sched_map = back_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!"
# The measurement pulse for measuring the qubit of interest.
measure = inst_sched_map.get('measure', qubits=back_config.meas_map[meas_map_idx])
# Should be getting |2> ideally.
sigma = 40
duration = 4*40
chan = DriveChannel(0)
with pulse.build(backend) as test_0:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited), chan)
test_0 += measure << test_0.duration
test_0.draw()
test0_job = execute(test_0, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test0 = test0_job.job_id()
print(jid_test0)
test0_job = backend.retrieve_job(jid_test0)
res = get_job_data(test0_job, average=False)
res[0]
reshaped_res = reshape_complex_vec(res[0])
plt.scatter(np.real(res[0]), np.imag(res[0]))
plt.show()
output = discrim.predict(reshaped_res)
arr = [0,0,0]
for i in output:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a 0-1 pi pulse.
# Should be ideally getting |1>
with pulse.build(backend) as test_00:
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground), chan)
test_00 += measure << test_00.duration
test_00.draw()
test00_job = execute(test_00, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test00 = test00_job.job_id()
print(jid_test00)
test00_job = backend.retrieve_job(jid_test00)
res00 = get_job_data(test00_job, average=False)
res00[0]
reshaped_res00 = reshape_complex_vec(res00[0])
plt.scatter(np.real(res00[0]), np.imag(res00[0]))
plt.show()
output00 = discrim.predict(reshaped_res00)
arr = [0,0,0]
for i in output00:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_1:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 0-1
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_1 += measure << test_pulse_1.duration
test_pulse_1.draw()
test1_job = execute(test_pulse_1, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test1 = test1_job.job_id()
print(jid_test1)
test1_job = backend.retrieve_job(jid_test1)
res1 = get_job_data(test1_job, average=False)
reshaped_res1 = reshape_complex_vec(res1[0])
plt.scatter(np.real(res1[0]), np.imag(res1[0]))
plt.show()
output1 = discrim.predict(reshaped_res1)
arr = [0,0,0]
for i in output1:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H then Z then H gate on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_2:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_2 += measure << test_pulse_2.duration
test_pulse_2.draw()
test2_job = execute(test_pulse_2, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test2 = test2_job.job_id()
print(jid_test2)
test2_job = backend.retrieve_job(jid_test2)
res2 = get_job_data(test2_job, average=False)
reshaped_res2 = reshape_complex_vec(res2[0])
plt.scatter(np.real(res2[0]), np.imag(res2[0]))
plt.show()
output2 = discrim.predict(reshaped_res2)
arr = [0,0,0]
for i in output2:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1, then H on 1-2
# then Z on 1-2 followed by H on 1-2
# Should get |0>/sqrt(2) + |2>/sqrt(2)
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_3:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Undoing phase appied during 0-1 transitions
pulse.shift_phase(np.pi, chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
# Applying a Z pulse
pulse.shift_phase(np.pi, chan)
# Applying H gate on 1-2
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_3 += measure << test_pulse_3.duration
test_pulse_3.draw()
test3_job = execute(test_pulse_3, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test3 = test3_job.job_id()
print(jid_test3)
test3_job = backend.retrieve_job(jid_test3)
res3 = get_job_data(test3_job, average=False)
reshaped_res3 = reshape_complex_vec(res3[0])
plt.scatter(np.real(res3[0]), np.imag(res3[0]))
plt.show()
output3 = discrim.predict(reshaped_res3)
arr = [0,0,0]
for i in output3:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 1-2
# Should get |1>/sqrt(2) + |2>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_4:
# Exciting the qubit to |1> state
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying H gate
pulse.set_frequency(excited_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_4 += measure << test_pulse_4.duration
test_pulse_4.draw()
test4_job = execute(test_pulse_4, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test4 = test4_job.job_id()
print(jid_test4)
test4_job = backend.retrieve_job(jid_test4)
res4 = get_job_data(test4_job, average=False)
reshaped_res4 = reshape_complex_vec(res4[0])
plt.scatter(np.real(res4[0]), np.imag(res4[0]))
plt.show()
output4 = discrim.predict(reshaped_res4)
arr = [0,0,0]
for i in output4:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a H on 0-1
# Should get |0>/sqrt(2) + |1>/sqrt(2) ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_5:
# Setting 0-1 frequency for channel and applying H gate
pulse.set_frequency(ground_freq, chan)
pulse.shift_phase(-np.pi/2, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground/2, name='X(pi/2)'), chan)
pulse.shift_phase(-np.pi/2, chan)
test_pulse_5 += measure << test_pulse_5.duration
test_pulse_5.draw()
test5_job = execute(test_pulse_5, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test5 = test5_job.job_id()
print(jid_test5)
test5_job = backend.retrieve_job(jid_test5)
res5 = get_job_data(test5_job, average=False)
reshaped_res5 = reshape_complex_vec(res5[0])
plt.scatter(np.real(res5[0]), np.imag(res5[0]))
plt.show()
output5 = discrim.predict(reshaped_res5)
arr = [0,0,0]
for i in output5:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 0-1
# Should get |1> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_6:
# Setting 0-1 frequency for channel and applying X gate
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
test_pulse_6 += measure << test_pulse_6.duration
test_pulse_6.draw()
test6_job = execute(test_pulse_6, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test6 = test6_job.job_id()
print(jid_test6)
test6_job = backend.retrieve_job(jid_test6)
res6 = get_job_data(test6_job, average=False)
reshaped_res6 = reshape_complex_vec(res6[0])
plt.scatter(np.real(res6[0]), np.imag(res6[0]))
plt.show()
output6 = discrim.predict(reshaped_res6)
arr = [0,0,0]
for i in output6:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
# Performing a X on 1-2
# Should get |2> ideally.
chan = DriveChannel(0)
with pulse.build(backend) as test_pulse_7:
# Setting 0-1 frequency for channel and applying 0-1 pi pulse
pulse.set_frequency(ground_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_ground, name='X(pi)'), chan)
# Setting 1-2 frequency for channel and applying 1-2 pi pulse
pulse.set_frequency(excited_freq, chan)
pulse.play(Gaussian(duration=duration, sigma=sigma, amp=pi_amp_excited, name='X(pi)'), chan)
test_pulse_7 += measure << test_pulse_7.duration
test_pulse_7.draw()
test7_job = execute(test_pulse_7, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_test7 = test7_job.job_id()
print(jid_test7)
test7_job = backend.retrieve_job(jid_test7)
res7 = get_job_data(test7_job, average=False)
reshaped_res7 = reshape_complex_vec(res7[0])
plt.scatter(np.real(res7[0]), np.imag(res7[0]))
plt.show()
output7 = discrim.predict(reshaped_res7)
arr = [0,0,0]
for i in output7:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
back_config = backend.configuration()
print("Supported kernels: ", back_config.meas_kernels)
print("Supported discriminators: ", back_config.discriminators)
qc = QuantumCircuit(2)
qc.cx(0,1)
with pulse.build(backend) as cnot_pulse:
pulse.call(qc)
cnot_pulse += measure << cnot_pulse.duration
cnot_pulse.draw()
cnot_job = execute(cnot_pulse, backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{chan: ground_freq}]
)
jid_cnot = cnot_job.job_id()
print(jid_cnot)
cnot_job = backend.retrieve_job(jid_cnot)
cnot_job.result().to_dict()
cnot_res = get_job_data(cnot_job, average=False)
reshaped_cnot_res = reshape_complex_vec(cnot_res[0])
plt.scatter(np.real(cnot_res[0]), np.imag(cnot_res[0]))
plt.show()
cnot_output = discrim.predict(reshaped_cnot_res)
arr = [0,0,0]
for i in cnot_output:
if i==0:
arr[0]+=1
elif i==1:
arr[1]+=1
else:
arr[2]+=1
print(arr)
qc = QuantumCircuit(1)
qc.y(0)
with pulse.build(backend) as ypulse:
pulse.call(qc)
ypulse += measure << ypulse.duration
ypulse.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
LIB_IMPORT = """
from qiskit import QuantumCircuit
from qiskit import execute, Aer
from qiskit.visualization import *"""
CIRCUIT_SCRIPT = """
circuit = build_state()
circuit.measure_all()
figure = circuit.draw('mpl')
output = figure.savefig('circuit.png')"""
PLOT_SCRIPT = """
backend = Aer.get_backend("qasm_simulator")
job = execute(circuit,backend=backend, shots =1000)
counts = job.result().get_counts()
plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)"""
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram, plot_bloch_multivector
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
pi = np.pi
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-pi/float(2**(j-m)), m, j)
qc.h(j)
def generalised_qpe(amt_estimation_qubits, angle, shots=10000):
go = True
while go:
# Create and set up circuit
qpe3 = QuantumCircuit(amt_estimation_qubits+1, amt_estimation_qubits)
# Apply H-Gates to counting qubits:
for qubit in range(amt_estimation_qubits):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(amt_estimation_qubits)
repetitions = 1
for counting_qubit in range(amt_estimation_qubits):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, amt_estimation_qubits);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe3, amt_estimation_qubits)
# Measure of course!
qpe3.barrier()
for n in range(amt_estimation_qubits):
qpe3.measure(n,n)
aer_sim = Aer.get_backend('aer_simulator')
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
answer2 = {int(k,2)/2**amt_estimation_qubits: v for k, v in answer.items()}
print(answer2)
try:
freq = answer.most_frequent()
go = False
except:
pass
#print("Most frequent '" + answer.most_frequent() + "'")
print("Approx rotation angle by Z from the unitary in degrees '" + str(360 * int(answer.most_frequent(), 2)/2**amt_estimation_qubits) + "'")
#print("Phase Calculation " + answer.most_frequent())
##return(plot_histogram(answer))
##comment out the return if you want to see the histogram
return((int(answer.most_frequent(), 2)/2**amt_estimation_qubits))
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# qc-grader should be 0.18.11 (or higher)
import qc_grader
qc_grader.__version__
# Imports
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.visualization import plot_gate_map
from qiskit.quantum_info import SparsePauliOp
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler
from circuit_knitting.cutting import generate_cutting_experiments, cut_gates
# Setup the grader
from qc_grader.challenges.iqc_2024 import grade_lab3_ckt_ex1, grade_lab3_ckt_ex2
# create a bell pair
bell_state = QuantumCircuit(2)
bell_state.h(0)
bell_state.cx(0,1)
bell_state.draw("mpl")
## If this is your first time accessing the backend
## remove # and fill your API key, and run the code
#service = QiskitRuntimeService(
# channel='ibm_quantum',
# instance='ibm-q/open/main',
# token='<IBM Quantum API key>'
#)
service = QiskitRuntimeService(channel="ibm_quantum")
# Specify a system to use for transpilation, DO NOT change
backend = service.backend("ibm_kyoto")
layout=[122, 126]
qubit_color = []
for i in range(127):
if i in layout:
qubit_color.append("#ff0066")
else:
qubit_color.append("#6600cc")
plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8))
# transpile the circuit
pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0)
isa_qc = pm.run(bell_state)
# original circuit depth
isa_qc_depth = isa_qc.depth()
print(f"Transpiled circuit depth: ", isa_qc_depth)
isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False)
# Find the indices of the distant gates
cut_indices = [
i
for i, instruction in enumerate(bell_state.data)
if {bell_state.find_bit(q)[0] for q in instruction.qubits} == {0, 1}
]
# Decompose distant CNOTs into TwoQubitQPDGate instances
qpd_circuit, bases = cut_gates(bell_state, cut_indices)
qpd_circuit.draw("mpl", scale=0.6)
observable = SparsePauliOp(["ZI"])
# Generate the sub-experiments and sampling coefficients
sub_experiments, coefficients = generate_cutting_experiments(
circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf
)
# Transpile the circuit
pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0)
isa_qpd_circuit = pm.run(sub_experiments[5])
# depth using circuit cutting
isa_qpd_depth = isa_qpd_circuit.depth()
print(f"Original circuit depth after transpile: ", isa_qc_depth)
print(f"QPD sub-experiment depth after transpile: ", isa_qpd_depth)
print(f"Number of sub-experiments:", len(sub_experiments))
isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False)
x = np.array([c.depth() for c in pm.run(sub_experiments)])
print(x)
toffoli_layout = [122, 124, 126]
toffoli = QuantumCircuit(3)
toffoli.ccx(0, 1, 2)
toffoli.draw("mpl")
# To know the original circuit depth
### Write your code below here ###
# Transpile the circuit
pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0)
isa_qpd_circuit = pm.run(toffoli)
# Calculate original circuit depth
isa_toffoli_depth = isa_qpd_circuit.depth()
### Don't change any code past this line ###
print(f"Transpiled circuit depth: ", isa_toffoli_depth)
isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False)
# To know the depth using circuit cutting
# Decompose the toffoli circuit
toffoli_ = toffoli.decompose()
### Write your code below here ###
# Find the indices of the distant gates
gates_connecting_to_cut = {0, 2} # Hint: Expected type: set {int, int}. Docs: https://docs.python.org/3/tutorial/datastructures.html#sets
cut_indices = [
i for i, instruction in enumerate(toffoli_.data)
if {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut
]
# Decompose distant CNOTs into TwoQubitQPDGate instances
qpd_circuit, bases = cut_gates(toffoli_, cut_indices)
### Don't change any code past this line ###
qpd_circuit.draw("mpl", scale=0.6)
# set the observables
observable = SparsePauliOp(["ZZZ"])
### Write your code below here ###
# Generate the sub-experiments and sampling coefficients
sub_experiments, coefficients = generate_cutting_experiments(
circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf
)
# Transpile the circuit
# Note: Use optimization_level=1 and seed_transpiler=0
pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0)
isa_qpd_circuit = pm.run(sub_experiments[5])
# Depth using circuit cutting
isa_qpd_toffoli_depth = isa_qpd_circuit.depth()
### Don't change any code past this line ###
print(f"Transpiled circuit depth: ", isa_toffoli_depth)
print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth)
print(f"Number of sub-experiments:", len(sub_experiments))
isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False)
### Write your code below here ###
# mean of the depth of all sub-experiments
depth_list = np.array([c.depth() for c in pm.run(sub_experiments)])
isa_qpd_toffoli_depth_mean = np.mean(depth_list)
### Don't change any code past this line ###
print(isa_qpd_toffoli_depth_mean)
# Submit your answer using following code
grade_lab3_ckt_ex1(gates_connecting_to_cut, isa_toffoli_depth, depth_list)
# Expected result type: set, int, numpy.ndarray
### Write your code below here ###
# Find the indices of the distant gates
gates_connecting_to_cut_1 = {0,2} # Hint: Expected type: set {int, int}
gates_connecting_to_cut_2 = {1,2} # Hint: Expected type: set {int, int}
cut_indices = [
i for i, instruction in enumerate(toffoli_.data)
if {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_1 or {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_2
]
# Decompose distant CNOTs into TwoQubitQPDGate instances
qpd_circuit_2, bases = cut_gates(toffoli_, cut_indices)
### Don't change any code past this line ###
qpd_circuit_2.draw("mpl", scale=0.6)
# set the observables
observable = SparsePauliOp(["ZZZ"])
### Write your code below here ###
# Generate the sub-experiments and sampling coefficients
sub_experiments_2, coefficients = generate_cutting_experiments(
circuits=qpd_circuit_2, observables=observable.paulis, num_samples=np.inf
)
# Transpile the circuit
# Note: Use optimization_level=1 and seed_transpiler=0
pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0)
isa_qpd_circuit_2 = pm.run(sub_experiments[5])
# Depth using circuit cutting
isa_qpd_toffoli_depth_2 = isa_qpd_circuit_2.depth()
### Don't change any code past this line ###
print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth_2)
print(f"Number of sub-experiments:", len(sub_experiments_2))
isa_qpd_circuit_2.draw("mpl", scale=0.6, idle_wires=False, fold=False)
# Submit your answer using following code
grade_lab3_ckt_ex2(gates_connecting_to_cut_1, gates_connecting_to_cut_2, sub_experiments_2)
# Expected result type: set, set, list[QuantumCircuit]
### Write your code below here ###
# mean of the depth of all sub-experiments
depth_list_2 = np.array([c.depth() for c in pm.run(sub_experiments_2)])
isa_qpd_toffoli_depth_2_mean = np.mean(depth_list_2)
### Don't change any code past this line ###
print(isa_qpd_toffoli_depth_2_mean)
# Number of sub-experiments
num_sub_experiments_1_cut = len(sub_experiments)
num_sub_experiments_2_cut = len(sub_experiments_2)
# Data for plotting
categories = ['Before Cutting', 'After 1 Cut', 'After 2 Cuts']
depth_values = [isa_toffoli_depth, isa_qpd_toffoli_depth_mean, isa_qpd_toffoli_depth_2_mean]
num_sub_experiments = [1, num_sub_experiments_1_cut, num_sub_experiments_2_cut]
# Create figure and axis
fig, ax1 = plt.subplots()
# Plot depth values
color = 'tab:blue'
ax1.set_xlabel('Number of Cuts')
ax1.set_ylabel('Circuit Depth', color=color)
bars = ax1.bar(categories, depth_values, color=color, alpha=0.6)
ax1.tick_params(axis='y', labelcolor=color)
# Add value labels on bars
for bar in bars:
yval = bar.get_height()
ax1.text(bar.get_x() + bar.get_width() / 2, yval + 1, round(yval, 2), ha='center', color=color, fontsize=10)
# Create a second y-axis to plot the number of subexperiments
ax2 = ax1.twinx()
color = 'tab:green'
ax2.set_ylabel('Number of Sub-experiments', color=color)
ax2.plot(categories, num_sub_experiments, color=color, marker='o')
ax2.tick_params(axis='y', labelcolor=color)
# Add value labels on points
for i, num in enumerate(num_sub_experiments):
ax2.text(i, num + 0.1, num, ha='center', color=color, fontsize=10)
# Add titles and labels
plt.title('Circuit Knitting Toolbox Results')
fig.tight_layout() # Adjust layout to make room for both y-axes
# Show plot
plt.show()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
pip install qiskit
import qiskit
qiskit.__qiskit_version__
pip install qiskit-ibm-runtime
from qiskit_ibm_runtime import QiskitRuntimeService
QiskitRuntimeService.save_account(channel="ibm_quantum", token="463bc61b55d82149a7ec719c9e89eeb8bc80a916eac5331f2d98fc35be2b4650af627d457593b0050910aa0bd4a0f1e3a8361ff25874d214f01640e55e571d27")
from qiskit.test.reference_circuits import ReferenceCircuits
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler
service = QiskitRuntimeService()
backend = service.backend("ibmq_qasm_simulator")
job = Sampler(backend).run(ReferenceCircuits.bell())
print(f"job id: {job.job_id()}")
result = job.result()
print(result)
# General
import numpy as np
# Qiskit imports
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import SparsePauliOp
# Runtime imports
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session
# Plotting routines
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
# Add your token below
service = QiskitRuntimeService(channel="ibm_quantum")
# Select the system with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
# Initialize your session
session = Session(backend=backend)
backend.name
theta = Parameter("$\\theta$")
chsh_circuit_no_meas = QuantumCircuit(2)
chsh_circuit_no_meas.h(0)
chsh_circuit_no_meas.cx(0, 1)
chsh_circuit_no_meas.ry(theta, 0)
chsh_circuit_no_meas.draw()
number_of_phases = 21
phases = np.linspace(0, 2 * np.pi, number_of_phases)
# Phases need to be expressed as list of lists in order to work
individual_phases = [[ph] for ph in phases]
ZZ = SparsePauliOp.from_list([("ZZ", 1)])
ZX = SparsePauliOp.from_list([("ZX", 1)])
XZ = SparsePauliOp.from_list([("XZ", 1)])
XX = SparsePauliOp.from_list([("XX", 1)])
ops = [ZZ, ZX, XZ, XX]
num_ops = len(ops)
batch_circuits = [chsh_circuit_no_meas] * number_of_phases * num_ops
batch_ops = [op for op in ops for _ in individual_phases]
estimator = Estimator(session=session)
batch_expvals = (
estimator.run(
batch_circuits, batch_ops, parameter_values=individual_phases * num_ops, shots=int(1e4)
)
.result()
.values
)
ZZ_expval, ZX_expval, XZ_expval, XX_expval = [
batch_expvals[kk * number_of_phases : (kk + 1) * number_of_phases] for kk in range(num_ops)
]
# <CHSH1> = <AB> - <Ab> + <aB> + <ab>
chsh1_est = ZZ_expval - ZX_expval + XZ_expval + XX_expval
# <CHSH2> = <AB> + <Ab> - <aB> + <ab>
chsh2_est = ZZ_expval + ZX_expval - XZ_expval + XX_expval
fig, ax = plt.subplots(figsize=(10, 6))
# results from hardware
ax.plot(phases / np.pi, chsh1_est, "o-", label="CHSH1", zorder=3)
ax.plot(phases / np.pi, chsh2_est, "o-", label="CHSH2", zorder=3)
# classical bound +-2
ax.axhline(y=2, color="0.9", linestyle="--")
ax.axhline(y=-2, color="0.9", linestyle="--")
# quantum bound, +-2√2
ax.axhline(y=np.sqrt(2) * 2, color="0.9", linestyle="-.")
ax.axhline(y=-np.sqrt(2) * 2, color="0.9", linestyle="-.")
ax.fill_between(phases / np.pi, 2, 2 * np.sqrt(2), color="0.6", alpha=0.7)
ax.fill_between(phases / np.pi, -2, -2 * np.sqrt(2), color="0.6", alpha=0.7)
# set x tick labels to the unit of pi
ax.xaxis.set_major_formatter(tck.FormatStrFormatter("%g $\pi$"))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=0.5))
# set title, labels, and legend
plt.title(f"Violation of CHSH Inequality")
plt.xlabel("Theta")
plt.ylabel("CHSH witness")
plt.legend()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
#import Aer here, before calling qiskit_ionq_provider
from qiskit import Aer
from qiskit_ionq import IonQProvider
#Call provider and set token value
provider = IonQProvider(token='my token')
provider.backends()
from qiskit import QuantumCircuit, QuantumRegister
from math import pi
def get_qc(p):
qr = QuantumRegister(11,'q')
qc = QuantumCircuit(qr)
for i in range(1,12):
qc.rx(i*p,i-1)
return qc
qci = get_qc(pi/3)
qci.draw()
qca = get_qc(pi/3+pi/18)
qcr = get_qc(pi/3-pi/18)
from qiskit import ClassicalRegister
# Add the measurement register
circs = [qci,qca,qcr]
cr = ClassicalRegister(11,'c')
for qc in circs:
qc.add_register(cr)
qc.measure(range(11),range(11))
from qiskit.providers.jobstatus import JobStatus
from qiskit import Aer, execute
# Choose the simulator backend
backend = provider.get_backend("ionq_simulator")
#backend = Aer.get_backend("qasm_simulator")
# Run the circuit:
def run_jobs(backend,circs,nshots):
jobs = []
job_ids = []
qcs = []
for qc in circs:
qcs.append(qc)
job = backend.run(qc, shots=nshots)
#job = execute(qc, backend, shots=nshots, memory=True)
jobs.append(job)
#job_ids.append(job.job_id())
return jobs
jobs = run_jobs(backend,circs,1000)
# Calculate output state populations
def get_pops(res,nn,n):
#print(res)
pops = [0 for i in range(2**nn)]
for key in res.keys():
pops[int(key,16)] = res[key]/n
#pops[int(key,2)] = res[key]/n
return pops
# Fetch the result
def get_jobs(jobs,nshots):
results = []
for i in range(len(jobs)):
result = jobs[i].result()
#print(result.data()['counts'])
#print(get_pops(result.data()['counts'],11,nshots))
results.append(get_pops(result.data()['counts'],11,nshots))
return results
results = get_jobs(jobs,1000)
def get_ion(res,ion):
p1 = 0
for x in range(2**11):
if (x&(2**ion)):
p1 += res[x]
return p1
prbi = [get_ion(results[0],i) for i in range(11)]
prba = [get_ion(results[1],i) for i in range(11)]
prbr = [get_ion(results[2],i) for i in range(11)]
avres = [sum([results[i][j] for i in range(3)])/3 for j in range(2**11)]
prbs = [get_ion(avres,i) for i in range(11)]
import matplotlib.pyplot as plt
plt.plot(range(12),[0]+prbi,label="Ideal")
plt.plot(range(12),[0]+prba,label="Over-rotation")
plt.plot(range(12),[0]+prbr,label="Under-rotation")
plt.plot(range(12),[0]+prbs,label="Average",linewidth=3)
plt.ylim([0,1])
plt.ylabel("State |1> probability")
plt.xlabel("Qubit (*time*)")
plt.legend()
# Switch the backend to run circuits on a quantum computer
qpu_backend = provider.get_backend("ionq_qpu")
jobs = run_jobs(qpu_backend,circs,1000)
#Check if jobs are done
for i in range(len(jobs)):
print(jobs[i].status())
# Fetch the result
results = get_jobs(jobs,1000)
prbi_m = [get_ion(results[0],i) for i in range(11)]
prba_m = [get_ion(results[1],i) for i in range(11)]
prbr_m = [get_ion(results[2],i) for i in range(11)]
avres = [sum([results[i][j] for i in range(3)])/3 for j in range(2**11)]
prbs_m = [get_ion(avres,i) for i in range(11)]
plt.plot(range(12),[0]+prbi_m,label="Ideal")
plt.plot(range(12),[0]+prba_m,label="Over-rotation")
plt.plot(range(12),[0]+prbr_m,label="Under-rotation")
plt.plot(range(12),[0]+prbs_m,label="Average",linewidth=3)
plt.ylim([0,1])
plt.ylabel("State |1> probability")
plt.legend()
|
https://github.com/cjsproject/qiskit_learning
|
cjsproject
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
from sklearn import datasets
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumRegister
from qiskit import QuantumCircuit
from qiskit import Aer, execute
from math import pi,log
from qiskit import *
from qiskit.extensions import XGate, UnitaryGate
import tensorflow as tf
import cv2
#imported stuff from Weiwen's code
import torch
import torchvision
from torchvision import datasets
import torchvision.transforms as transforms
import torch.nn as nn
import shutil
import os
import time
import sys
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from skcuda.linalg import svd
from matplotlib import cm
import functools
%matplotlib inline
backend = Aer.get_backend('qasm_simulator')
print = functools.partial(print, flush=True)
interest_num = [3,6]
ori_img_size = 28 #original image is 28x28
img_size = 4 #size to downsize to (set to 28 if no downsizing)
# number of subprocesses to use for data loading
num_workers = 0
# how many samples per batch to load
batch_size = 1
inference_batch_size = 1
# Weiwen: modify the target classes starting from 0. Say, [3,6] -> [0,1]
def modify_target(target):
for j in range(len(target)):
for idx in range(len(interest_num)):
if target[j] == interest_num[idx]:
target[j] = idx
break
new_target = torch.zeros(target.shape[0],2)
for i in range(target.shape[0]):
if target[i].item() == 0:
new_target[i] = torch.tensor([1,0]).clone()
else:
new_target[i] = torch.tensor([0,1]).clone()
return target,new_target
def select_num(dataset,labels,interest_num):
valid_labels = np.array([])
for num in interest_num:
if valid_labels.size > 0:
valid_labels += labels== num
else:
valid_labels = labels == num
dataset = dataset[valid_labels]
labels = labels[valid_labels]
return (dataset,labels)
def nomalizatied(ori,fig):
row = fig['row']
col = fig['col']
transformed = []
for i in range(len(ori)):
transform = np.resize(ori[i],(row,col))
transformed.append(transform)
return transformed
################ Weiwen on 12-30-2020 ################
# Using torch to load MNIST data
######################################################
# convert data to torch.FloatTensor
transform = transforms.Compose([transforms.Resize((ori_img_size,ori_img_size)),
transforms.ToTensor()])
# Path to MNIST Dataset
(train_data,train_labels),(test_data,test_labels) = tf.keras.datasets.mnist.load_data()
(train_data,train_labels) = select_num(train_data,train_labels,interest_num)
(test_data,test_labels) = select_num(test_data,test_labels,interest_num)
#train_data = nomalizatied(train_data,{'row':4,'col':4})
#test_data = nomalizatied(test_data,{'row':4,'col':4})
train_data = train_data[:1000]
train_labels = train_labels[:1000]
train_data = torch.Tensor(train_data) # transform to torch tensor
train_labels = torch.Tensor(train_labels)
test_data = torch.Tensor(test_data)
test_labels = torch.Tensor(test_labels)
train = torch.utils.data.TensorDataset(train_data,train_labels) # create your datset
test =torch.utils.data.TensorDataset(test_data,test_labels)
u, s, v = svd(np.array(train_data[0:10]/255))
# prepare data loaders
train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size,
num_workers=num_workers, shuffle=False, drop_last=True)
test_loader = torch.utils.data.DataLoader(test, batch_size=inference_batch_size,
num_workers=num_workers, shuffle=False, drop_last=True)
class ToQuantumData(object):
def __call__(self, input_vec):
vec_len = len(input_vec)
input_matrix = np.zeros((vec_len, vec_len))
input_matrix[0] = input_vec
input_matrix = input_matrix.transpose()
u, s, v = np.linalg.svd(input_matrix)
output_matrix = np.dot(u, v)
output_data = output_matrix[:, 0].view()
return output_data
class ToQuantumMatrix(object):
def __call__(self, input_vec):
vec_len = len(input_vec)
input_matrix = np.zeros((vec_len, vec_len))
input_matrix[0] = input_vec
#print('new input vec')
input_matrix = input_matrix.transpose()
#print(input_vec)
u, s, v = np.linalg.svd(input_matrix)
output_matrix = np.dot(u, v)
return output_matrix
def data_pre_pro(vector):
# Converting classical data to quantum data
trans_to_vector = ToQuantumData()
trans_to_matrix = ToQuantumMatrix()
#print("Classical Data: {}".format(vector))
#print("Quantum Data: {}".format(trans_to_vector(vector)))
return trans_to_matrix(vector),trans_to_vector(vector)
def PaddingNeeded(n):
#check if n is a power of 2
num_decimal = np.log2(n)
num_int = int(-(-num_decimal//1)) #round any decimal number up
dims_needed = int(2**(num_int))
return dims_needed
def pad_zeros(data):
row = len(data)
col = len(data[0])
dims = max(row,col)
dims_needed = PaddingNeeded(dims)
return np.pad(data,((0,dims_needed-row),(0,dims_needed-col)),'constant', constant_values=(0,0))
from tqdm import tqdm
dataset = []
labels = []
# Use the first image from test loader as example
for batch_idx, (data, target) in tqdm(enumerate(train_loader)):
torch.set_printoptions(threshold=sys.maxsize)
np.set_printoptions(threshold=sys.maxsize)
data_grid = torchvision.utils.make_grid(data) #read the data from torch
np_data = data_grid.numpy() #convert tensor to numpy array
image = np.asarray(np_data[0] * 255, np.uint8)
im = Image.fromarray(image,mode="L")
im = im.resize((4,4),Image.BILINEAR)
np_image = np.asarray(im)*1/255 #normalize the resized image
data_pad = pad_zeros(np_image) #pad the data with zeros (if necessary) to make dimensionality a power of 2
np_1d = data_pad.ravel() #convert the padded data to 1-d array for encoding function
quantum_matrix,quantum_data = data_pre_pro(np_1d) #convert the data to unitary matrix
dataset.append(quantum_matrix)
labels.append(quantum_data)
for matrix in dataset:
print(is_unitary(np.matrix(matrix)))
train_labels_binary = train_labels == 3
train_labels_binary = np.array(train_labels_binary).astype('int') # 3 is Label 1, 6 is label 0
#------------------------------------------------------------------------------------------
#DATA ENCODING SECTION
#------------------------------------------------------------------------------------------
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
def quantum_encode(quantum_matrix):
dims = len(quantum_matrix[0]) #dimensionality of data
q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number)
print(dims, 'classical bits encoded onto ', q, ' qubits')
c=1 #one classical bit
#Create quantum register and circuit
inp = QuantumRegister(q,"in_qbit")
circ = QuantumCircuit(inp)
# Add classical register
c_reg = ClassicalRegister(c,"reg")
circ.add_register(c_reg)
# From Listing 3: create auxiliary qubits
#aux = QuantumRegister(1,"aux_qbit")
#circ.add_register(aux)
circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q])
return circ, q
#encode the classicaL data into a quantum circuit (2^N parameters onto N qubits)
circ, q= quantum_encode(quantum_matrix)
print(circ)
# Using StatevectorSimulator from the Aer provider
simulator = Aer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
statevector = result.get_statevector(circ)
print("Data to be encoded: \n {}\n".format(quantum_data))
print("Data read from the circuit: \n {}".format(statevector))
#All functions needed for the functionality of the circuit simulation
def generate_and_save_images(model, epoch, test_input):
# Notice `training` is set to False.
# This is so all layers run in inference mode (batchnorm).
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
dp = np.array((predictions[i] * 127.5) + 127.5).astype('uint8')
plt.imshow(dp)
plt.axis('off')
#plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
def ran_ang():
#return np.pi/2
return np.random.rand()*np.pi
def single_qubit_unitary(circ_ident,qubit_index,values):
circ_ident.ry(values[0],qubit_index)
def dual_qubit_unitary(circ_ident,qubit_1,qubit_2,values):
circ_ident.ryy(values[0],qubit_1,qubit_2)
def controlled_dual_qubit_unitary(circ_ident,control_qubit,act_qubit,values):
circ_ident.cry(values[0],control_qubit,act_qubit)
#circ_ident.cry(values[0],act_qubit,control_qubit)
def traditional_learning_layer(circ_ident,num_qubits,values,style="Dual",qubit_start=1,qubit_end=5):
if style == "Dual":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
for qub in np.arange(qubit_start,qubit_end-1):
dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)])
elif style =="Single":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
elif style=="Controlled-Dual":
for qub in np.arange(qubit_start,qubit_end):
single_qubit_unitary(circ_ident,qub,values[str(qub)])
for qub in np.arange(qubit_start,qubit_end-1):
dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)])
for qub in np.arange(qubit_start,qubit_end-1):
controlled_dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+"--"+str(qub+1)])
'''
def data_loading_circuit(circ_ident,num_qubits,values,qubit_start=1,qubit_end=5):
k = 0
for qub in np.arange(qubit_start,qubit_end):
circ_ident.ry(values[k],qub)
k += 1
'''
def data_loading_circuit(circ_ident,quantum_matrix,qubit_start=1,qubit_end=5):
circ_ident.append(UnitaryGate(quantum_matrix, label="Input"), circ_ident.qubits[qubit_start:qubit_end])
def quantum_encode(quantum_matrix):
dims = len(quantum_matrix[0]) #dimensionality of data
q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number)
print(dims, 'classical bits encoded onto ', q, ' qubits')
c=1 #one classical bit
#Create quantum register and circuit
inp = QuantumRegister(q,"in_qbit")
circ = QuantumCircuit(inp)
# Add classical register
c_reg = ClassicalRegister(c,"reg")
circ.add_register(c_reg)
# From Listing 3: create auxiliary qubits
#aux = QuantumRegister(1,"aux_qbit")
#circ.add_register(aux)
circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q])
return circ, q
def swap_test(circ_ident,num_qubits):
num_swap = num_qubits//2
for i in range(num_swap):
circ_ident.cswap(0,i+1,i+num_swap+1)
circ_ident.h(0)
circ_ident.measure(0,0)
def init_random_variables(q,style):
trainable_variables = {}
if style=="Single":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
elif style=="Dual":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
if i != q:
trainable_variables[str(i)+","+str(i+1)] = [ran_ang()]
elif style=="Controlled-Dual":
for i in np.arange(1,q+1):
trainable_variables[str(i)] = [ran_ang()]
if i != q:
trainable_variables[str(i)+","+str(i+1)] = [ran_ang()]
trainable_variables[str(i)+"--"+str(i+1)] = [ran_ang()]
return trainable_variables
def get_probabilities(circ,counts=5000):
job = execute(circ, backend, shots=counts)
results = job.result().get_counts(circ)
try:
prob = results['0']/(results['1']+results['0'])
prob = (prob-0.5)
if prob <= 0.005:
prob = 0.005
else:
prob = prob*2
except:
prob = 1
return prob
# Define loss function. SWAP Test returns probability, so minmax probability is logical
def cost_function(p,yreal,trimming):
if yreal == 0:
return -np.log(p)
#return 1-p
elif yreal == 1:
return -np.log(1-p)
#return p
def generator_cost_function(p):
return -np.log(p)
def update_weights(init_value,lr,grad):
while lr*grad > 2*np.pi:
lr /= 10
print("Warning - Gradient taking steps that are very large. Drop learning rate")
weight_update = lr*grad
new_value = init_value
print("Updating with a new value of " + str(weight_update))
if new_value-weight_update > 2*np.pi:
new_value = (new_value-weight_update) - 2*np.pi
elif new_value-weight_update < 0:
new_value = (new_value-weight_update) + 2*np.pi
else:
new_value = new_value - weight_update
return new_value
# Define loss function. SWAP Test returns probability, so minmax probability is logical
def cost_function(p,yreal,trimming):
if yreal == 0:
return -np.log(p)
#return 1-p
elif yreal == 1:
return -np.log(1-p)
#return p
def generator_cost_function(p):
return -np.log(p)
def update_weights(init_value,lr,grad):
while lr*grad > 2*np.pi:
lr /= 10
print("Warning - Gradient taking steps that are very large. Drop learning rate")
weight_update = lr*grad
new_value = init_value
print("Updating with a new value of " + str(weight_update))
if new_value-weight_update > 2*np.pi:
new_value = (new_value-weight_update) - 2*np.pi
elif new_value-weight_update < 0:
new_value = (new_value-weight_update) + 2*np.pi
else:
new_value = new_value - weight_update
return new_value
QuantumCircuit(5,1).qubits
# ------------------------------------------------------------------------------------
# We treat the first n qubits are the discriminators state. n is always defined as the
# integer division floor of the qubit count.
# This is due to the fact that a state will always be k qubits, therefore the
# number of total qubits must be 2k+1. 2k as we need k for the disc, and k to represent
# either the other learned quantum state, or k to represent a data point
# then +1 to perform the SWAP test. Therefore, we know that we will always end up
# with an odd number of qubits. We take the floor to solve for k. 1st k represents
# disc, 2nd k represents the "loaded" state be it gen or real data
# ------------------------------------------------------------------------------------
# Use different function calls to represent training a GENERATOR or training a DISCRIMINATOR
# ------------------------------------------------------------------------------------
# THIS SECTION IS FOR THE ONLINE GENERATION OF QUANTUM CIRCUITS
def disc_fake_training_circuit(trainable_variables,key,key_value,diff=False,fwd_diff = False,Sample=False):
if Sample:
z = q//2
circ = QuantumCircuit(q,z)
else:
circ = QuantumCircuit(q,c)
circ.h(0)
if diff == True and fwd_diff == True:
trainable_variables[key][key_value] += par_shift
if diff == True and fwd_diff == False:
trainable_variables[key][key_value] -= par_shift
traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1)
traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=q//2 +1,qubit_end=q)
if Sample:
for qub in range(q//2):
circ.measure(q//2 + 1 + qub,qub)
else:
swap_test(circ,q)
if diff == True and fwd_diff == True:
trainable_variables[key][key_value] -= par_shift
if diff == True and fwd_diff == False:
trainable_variables[key][key_value] += par_shift
return circ
def disc_real_training_circuit(training_variables,data,key,key_value,diff,fwd_diff):
circ = QuantumCircuit(q,c)
circ.h(0)
if diff == True & fwd_diff == True:
training_variables[key][key_value] += par_shift
if diff == True & fwd_diff == False:
training_variables[key][key_value] -= par_shift
traditional_learning_layer(circ,q,training_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1)
data_loading_circuit(circ,data,qubit_start=q//2+1,qubit_end=q)
if diff == True & fwd_diff == True:
training_variables[key][key_value] -= par_shift
if diff == True & fwd_diff == False:
training_variables[key][key_value] += par_shift
swap_test(circ,q)
return circ
def generate_kl_divergence_hist(actual_data, epoch_results_data):
plt.clf() # clears current figure
sns.set()
kl_div_vec = []
for kl_dim in range(actual_data.shape[1]):
kl_div = kl_divergence(actual_data[:,kl_dim],epoch_results_data[:,kl_dim])
kl_div_vec.append(kl_div)
return kl_div_vec
def bin_data(dataset):
bins = np.zeros(10)
for point in dataset:
indx = int(str(point).split('.')[-1][0]) # The shittest way imaginable to extract the first val aft decimal
bins[indx] +=1
bins /= sum(bins)
return bins
def kl_divergence(p_dist, q_dist):
p = bin_data(p_dist)
q = bin_data(q_dist)
kldiv = 0
for p_point,q_point in zip(p,q):
kldiv += (np.sqrt(p_point) - np.sqrt(q_point))**2
kldiv = (1/np.sqrt(2))*kldiv**0.5
return kldiv
#return sum(p[i] * log2(p[i]/q[i]) for i in range(len(p))) # ?... are we confident in this...
# Checkpointing code
def save_variables(train_var,epoch,number):
with open(f"Epoch-{epoch}-Variables-numbers-{number}",'w') as file:
file.write(str(train_var))
def load_variables(epoch,number):
with open(f"Epoch-{epoch}-Variables-numbers-{number}",'r') as file:
texts = file.read()
return eval(texts)
train_var_1 = load_variables(11,6)
train_var_0 = load_variables(49,3)
train_var_1
z = disc_real_training_circuit(train_var,quantum_matrix,'1',0,diff=False,fwd_diff=False)
#z.append(UnitaryGate(quantum_matrix, label="Input"), z.qubits[10:20])
quantum_matrix
dataset = np.array(dataset)
labels = np.array(labels)
train_labels_binary = train_labels_binary[:dataset.shape[0]]
dataset = dataset[:5000]
train_labels_binary = train_labels_binary[:5000]
q=9# Number of qubits = Dimensionality of data = round up to even number = num qubits
c=1
circ = QuantumCircuit(q,c)
circ.h(0)
layer_style = "Controlled-Dual"
train_var_0 = init_random_variables(q//2,layer_style)
train_var_1 = init_random_variables(q//2,layer_style)
#train_var_2 = init_random_variables(q//2,layer_style)
tracked_d_loss = []
tracked_d_loss1 = []
gradients = []
learning_rate=0.015
train_iter = 50
corr = 0
wrong= 0
loss_d_to_real = 0
print('Starting Training')
print('-'*20)
print("train_var_0 training")
for epoch in range(train_iter):
start = time.time()
loss = [0,0]
par_shift = 0.5*np.pi/((1+epoch)**0.5)
for index,point in enumerate(dataset[train_labels_binary==0]):
for key,value in train_var_0.items():
if str(q//2 + 1 ) in key:
break
for key_value in range(len(value)):
forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=True)))
backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=False)))
df = 0.5*(forward_diff-backward_diff)
train_var_0[key][key_value] -= df*learning_rate
#print(f"Updated Variable {key}-({key_value}) by {-df*learning_rate}")
print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start))
print("-"*20)
save_variables(train_var_0,epoch,3)
for epoch in range(train_iter):
start = time.time()
loss = [0,0]
par_shift = 0.5*np.pi/((1+epoch)**0.5)
for index,point in enumerate(dataset[train_labels_binary==1]):
for key,value in train_var_1.items():
if str(q//2 + 1 ) in key:
break
for key_value in range(len(value)):
forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=True)))
backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=False)))
df = 0.5*(forward_diff-backward_diff)
train_var_1[key][key_value] -= df*learning_rate
print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start))
print("-"*20)
save_variables(train_var_1,epoch,6)
def is_unitary(m):
return np.allclose(np.eye(m.shape[0]), m.H * m)
is_unitary(np.matrix(quantum_matrix[0]))
corr = 0
wron = 0
for index,point in enumerate(dataset[train_labels_binary==1]):
p1 = get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=False,fwd_diff=False))
p2 = get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=False,fwd_diff=False))
if p1<p2:
corr +=1
else:
wron+=1
acc = corr/(corr+wron)
print(acc)
corr
wron
829
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import *
IBMQ.load_accounts(hub=None)
from qiskit.tools.jupyter import *
from qiskit.tools.monitor import job_monitor
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c);
from qiskit.providers.ibmq import least_busy
backend = least_busy(IBMQ.backends(simulator=False))
backend.name()
job = execute(qc, backend)
job_monitor(job, monitor_async=True)
%%qiskit_job_status
job2 = execute(qc, backend)
num_jobs = 5
my_jobs = []
for j in range(num_jobs):
my_jobs.append(execute(qc, backend))
job_monitor(my_jobs[j], monitor_async=True)
%%qiskit_job_status
my_jobs2 = []
for j in range(num_jobs):
my_jobs2.append(execute(qc, backend))
%%qiskit_job_status
import numpy as np
my_jobs3 = np.empty(num_jobs, dtype=object)
for j in range(num_jobs):
my_jobs3[j] = execute(qc, backend)
%%qiskit_job_status -i 5
job4 = execute(qc, backend)
%%qiskit_job_status --interval 5
job5 = execute(qc, backend)
%qiskit_backend_monitor backend
%qiskit_backend_overview
|
https://github.com/menegolli/Quantum_synth
|
menegolli
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from qiskit import *
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit import Aer, IBMQ # import the Aer and IBMQ providers
from qiskit.providers.aer import noise # import Aer noise models
from qiskit.tools.monitor import job_monitor
from RenormalizeProbability import *
# In[7]:
def ChooseBackEnd(quantumCircuit, backendType="statevector_simulator", qubitsToBeMeasured=range(4), numberShots=4096, noisePresent=False, RealDeviceName="ibmq_ourense",number=12):
if backendType == "statevector_simulator":
backend = Aer.get_backend('statevector_simulator')
result = execute(quantumCircuit, backend).result()
probabilityVectors = np.square(np.absolute(result.get_statevector()))
listForMusic = []
for k in range(2**len(qubitsToBeMeasured)):
listForMusic.append("%.3f" % (probabilityVectors[k]))
elif backendType == "qasm_simulator":
if noisePresent == False:
# no noise
quantumCircuit.measure(qubitsToBeMeasured, qubitsToBeMeasured)
print(qubitsToBeMeasured)
backend = Aer.get_backend('qasm_simulator')
result = execute(quantumCircuit, backend, shots=numberShots).result()
counts = result.get_counts()
listForMusic = []
for i in range(2**len(qubitsToBeMeasured)):
bitstring = str(bin(i)[2:])
bitstring = "0"*(4-len(bitstring))+bitstring
if bitstring in counts.keys():
listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots)))
else:
listForMusic.append("0.000")
else:
print(qubitsToBeMeasured)
quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured)
provider=IBMQ.save_account('XXX-YOUR-TOKEN')
# simulate noise of a real device
IBMQ.load_account()
IBMQ.providers()
device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName)
properties = device.properties()
coupling_map = device.configuration().coupling_map
# Generate an Aer noise model for device
noise_model = noise.device.basic_device_noise_model(properties)
basis_gates = noise_model.basis_gates
# Perform noisy simulation
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(quantumCircuit, backend,
coupling_map=coupling_map,
noise_model=noise_model,
basis_gates=basis_gates)
result = job_sim.result()
counts = result.get_counts()
listForMusic = []
for i in range(2**len(qubitsToBeMeasured)):
bitstring = str(bin(i)[2:])
bitstring = "0"*(4-len(bitstring))+bitstring
if bitstring in counts.keys():
listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots)))
else:
listForMusic.append("0.000")
elif backendType == "real_device":
# real device
quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured)
provider=IBMQ.save_account('XXX-YOUR-TOKEN')
# simulate noise of a real device
IBMQ.load_account()
IBMQ.providers()
device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName)
job_exp = execute(quantumCircuit, backend=device)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts()
listForMusic = []
for i in range(2**len(qubitsToBeMeasured)):
bitstring = str(bin(i)[2:])
bitstring = "0"*(4-len(bitstring))+bitstring
if bitstring in counts.keys():
listForMusic.append(" %.3f" % (counts[bitstring]/float(numberShots)))
else:
listForMusic.append("0.000")
return listForMusic
# In[70]:
if __name__ == "__main__":
# qc = QuantumCircuit(2,2)
# qc.h(0)
# qc.x(1)
#
# res = ChooseBackEnd(qc,"qasm_simulator",200)
# In[8]:
music = QuantumCircuit(4,4)
desired_vector = np.zeros(np.power(2,4))
desired_vector[1] = 1 / np.sqrt(3)
desired_vector[3] = 1/np.sqrt(3)
desired_vector[10] = 1/np.sqrt(3)
music.initialize(desired_vector, range(4))
listForMusic= ChooseBackEnd(music,backendType="statevector_simulator",qubitsToBeMeasured=range(4),
numberShots=4096, noisePresent=True, RealDeviceName="ibmq_16_melbourne")
print(listForMusic)
# In[ ]:
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (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.
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
circuits = transpile(
circuits,
)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results
result = backend.run(circuits, **kwargs).result()
user_messenger.publish(result.to_dict(), final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
# PROGRAM_PREFIX = 'qiskit-test'
def main():
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
runtime_program = provider.runtime.program(program_id)
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
job.result(timeout=120)
if __name__ == "__main__":
main()
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# 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.
"""
QasmSimulator Integration Tests
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT, QuantumVolume
from qiskit.compiler import assemble, transpile
from qiskit.providers.qrack import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import ReadoutError, depolarizing_error
class QasmDelayMeasureTests:
"""QasmSimulator delay measure sampling optimization tests."""
SIMULATOR = QasmSimulator()
BACKEND_OPTS = {}
def delay_measure_circuit(self):
"""Test circuit that allows measure delay optimization"""
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.measure(0, 0)
circuit.barrier([0, 1])
circuit.x(1)
circuit.measure(0, 1)
return circuit
def test_delay_measure_enable(self):
"""Test measure sampling works with delay measure optimization"""
# Circuit that allows delay measure
circuit = self.delay_measure_circuit()
shots = 100
qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1)
# Delay measure default
backend_options = self.BACKEND_OPTS.copy()
backend_options['optimize_ideal_threshold'] = 0
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertTrue(metadata.get('measure_sampling'))
# Delay measure enabled
backend_options = self.BACKEND_OPTS.copy()
backend_options['delay_measure_enable'] = True
backend_options['optimize_ideal_threshold'] = 0
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertTrue(metadata.get('measure_sampling'))
# Delay measure disabled
backend_options = self.BACKEND_OPTS.copy()
backend_options['delay_measure_enable'] = False
backend_options['optimize_ideal_threshold'] = 0
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertFalse(metadata.get('measure_sampling'))
def test_delay_measure_verbose(self):
"""Test delay measure with verbose option"""
circuit = self.delay_measure_circuit()
shots = 100
qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1)
# Delay measure verbose enabled
backend_options = self.BACKEND_OPTS.copy()
backend_options['delay_measure_enable'] = True
backend_options['delay_measure_verbose'] = True
backend_options['optimize_ideal_threshold'] = 0
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertIn('delay_measure_verbose', metadata)
# Delay measure verbose disabled
backend_options = self.BACKEND_OPTS.copy()
backend_options['delay_measure_enable'] = True
backend_options['delay_measure_verbose'] = False
backend_options['optimize_ideal_threshold'] = 0
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertNotIn('delay_measure_verbose', metadata)
# Delay measure verbose default
backend_options = self.BACKEND_OPTS.copy()
backend_options['delay_measure_enable'] = True
backend_options['optimize_ideal_threshold'] = 1
backend_options['optimize_noise_threshold'] = 1
result = self.SIMULATOR.run(
qobj,
**backend_options).result()
self.assertSuccess(result)
#metadata = result.results[0].metadata
#self.assertNotIn('delay_measure_verbose', metadata)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import (
MinimumEigenOptimizer,
RecursiveMinimumEigenOptimizer,
SolutionSample,
OptimizationResultStatus,
)
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from typing import List, Tuple
import numpy as np
# create a QUBO
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
op, offset = qubo.to_ising()
print("offset: {}".format(offset))
print("operator:")
print(op)
qp = QuadraticProgram()
qp.from_ising(op, offset, linear=True)
print(qp.prettyprint())
algorithm_globals.random_seed = 10598
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 0.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA
exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver
exact_result = exact.solve(qubo)
print(exact_result.prettyprint())
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
print("variable order:", [var.name for var in qaoa_result.variables])
for s in qaoa_result.samples:
print(s)
def get_filtered_samples(
samples: List[SolutionSample],
threshold: float = 0,
allowed_status: Tuple[OptimizationResultStatus] = (OptimizationResultStatus.SUCCESS,),
):
res = []
for s in samples:
if s.status in allowed_status and s.probability > threshold:
res.append(s)
return res
filtered_samples = get_filtered_samples(
qaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
for s in filtered_samples:
print(s)
fvals = [s.fval for s in qaoa_result.samples]
probabilities = [s.probability for s in qaoa_result.samples]
np.mean(fvals)
np.std(fvals)
samples_for_plot = {
" ".join(f"{qaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
rqaoa = RecursiveMinimumEigenOptimizer(qaoa, min_num_vars=1, min_num_vars_optimizer=exact)
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result.prettyprint())
filtered_samples = get_filtered_samples(
rqaoa_result.samples, threshold=0.005, allowed_status=(OptimizationResultStatus.SUCCESS,)
)
samples_for_plot = {
" ".join(f"{rqaoa_result.variables[i].name}={int(v)}" for i, v in enumerate(s.x)): s.probability
for s in filtered_samples
}
samples_for_plot
plot_histogram(samples_for_plot)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
excited = Statevector.from_int(1, 2)
plot_bloch_multivector(excited.data)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The Rabi sweep will be at the given qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
from qiskit import pulse, assemble # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[0])
# Rabi experiment parameters
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
num_rabi_points = 50
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# drive waveforms mush be in units of 16
drive_sigma = 80 # in dt
drive_samples = 8*drive_sigma # in dt
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True, scaling=1.0)
# assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: center_frequency_Hz}]
* num_rabi_points)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job("5ef3bf17dc3044001186c011")
rabi_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
scale_factor = 1e-14
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values
plt.show()
from scipy.optimize import curve_fit
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
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[10, 0.1, 0.6, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
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.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule += Play(x90_pulse, drive_chan)
this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay)
this_schedule += measure << this_schedule.duration
ramsey_schedules.append(this_schedule)
ramsey_schedules[-1].draw(label=True, scaling=1.0)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
# RUN the job on a real device
#job = backend.run(ramsey_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive job from previous run
job = backend.retrieve_job('5ef3ed3a84b1b70012374317')
ramsey_results = job.result()
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# 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.
"""
Simulator command to snapshot internal simulator representation.
"""
from warnings import warn
from qiskit import QuantumCircuit
from .snapshot import Snapshot
class SnapshotDensityMatrix(Snapshot):
"""Snapshot instruction for density matrix method of Qasm simulator."""
def __init__(self, label, num_qubits):
"""Create a density matrix state snapshot instruction.
Args:
label (str): the snapshot label.
num_qubits (int): the number of qubits to snapshot.
Raises:
ExtensionError: if snapshot is invalid.
.. deprecated:: 0.9.0
This instruction has been deprecated and will be removed no earlier
than 3 months from the 0.9.0 release date. It has been superseded by the
:class:`qiskit.providers.aer.library.SaveDensityMatrix` instruction.
"""
warn('The `SnapshotDensityMatrix` instruction has been deprecated as of'
' qiskit-aer 0.9. It has been superseded by the `SaveDensityMatrix`'
' instructions.', DeprecationWarning, stacklevel=2)
super().__init__(label,
snapshot_type='density_matrix',
num_qubits=num_qubits)
def snapshot_density_matrix(self, label, qubits=None):
"""Take a density matrix snapshot of simulator state.
Args:
label (str): a snapshot label to report the result
qubits (list or None): the qubits to apply snapshot to. If None all
qubits will be snapshot [Default: None].
Returns:
QuantumCircuit: with attached instruction.
Raises:
ExtensionError: if snapshot is invalid.
.. deprecated:: 0.9.0
This instruction has been deprecated and will be removed no earlier
than 3 months from the 0.9.0 release date. It has been superseded by the
:class:`qiskit.providers.aer.library.save_density_matrix`
circuit method.
"""
warn('The `snapshot_density_matrix` circuit method has been deprecated as of'
' qiskit-aer 0.9 and will be removed in a future release.'
' It has been superseded by the `save_density_matrix`'
' circuit method.', DeprecationWarning, stacklevel=2)
snapshot_register = Snapshot.define_snapshot_register(self, qubits=qubits)
return self.append(
SnapshotDensityMatrix(label, num_qubits=len(snapshot_register)),
snapshot_register)
QuantumCircuit.snapshot_density_matrix = snapshot_density_matrix
|
https://github.com/bawejagb/Quantum_Computing
|
bawejagb
|
#Import Libraries
from qiskit import QuantumCircuit, transpile, Aer, assemble
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.visualization import array_to_latex, plot_state_qsphere
#Input State: 01
qc_ha=QuantumCircuit(4,2)
qc_ha.x(0)
qc_ha.barrier()
qc_ha.cx(0,2)
qc_ha.cx(1,2)
qc_ha.ccx(0,1,3)
# Draw the circuit
qc_ha.draw(output='mpl')
# Let's get the result:
svsim=Aer.get_backend('aer_simulator')
qc_ha.save_statevector()
qobj = assemble(qc_ha)
result = svsim.run(qobj).result()
# Print the statevector neatly:
final_state = result.get_statevector()
array_to_latex(final_state, prefix="\\text{Statevector = }")
#Plot Sphere
plot_state_qsphere(final_state)
# Map the quantum measurement to the classical bits
qc_ha.measure(2,0)
qc_ha.measure(3,1)
# Draw the circuit
qc_ha.draw(output='mpl')
# compile the circuit down to low-level QASM instructions
simulator = QasmSimulator()
compiled_circuit = transpile(qc_ha, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
print("\nTotal count for 00 and 11 are:",counts)
#Plot histogram of result
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
antisymmetric_part = np.array(
[
[0.0, 3.0, 0.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[0.0, -3.0, 0.0, 3.0],
[0.0, 0.0, -3.0, 0.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
antisymmetric_part=antisymmetric_part,
constant=constant,
)
# convert it to a FermionicOp and print it
hamiltonian_ferm = hamiltonian.second_q_op()
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.second_q.mappers import JordanWignerMapper
# simulate the circuit to get the final state
state = np.array(Statevector(circuit))
# convert the Hamiltonian to a matrix
hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix()
# check that the state is an eigenvector with the expected eigenvalue
np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8)
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
constant=constant,
)
print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}")
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit_nature.second_q.circuit.library import BogoliubovTransform
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity
from scipy.linalg import expm
# create Hamiltonian
n_modes = 5
hermitian_part = np.array(random_hermitian(n_modes))
hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part)
# diagonalize Hamiltonian
(
transformation_matrix,
orbital_energies,
_,
) = hamiltonian.diagonalizing_bogoliubov_transform()
# set simulation time and construct time evolution circuit
time = 1.0
register = QuantumRegister(n_modes)
circuit = QuantumCircuit(register)
bog_circuit = BogoliubovTransform(transformation_matrix)
# change to the diagonal basis of the Hamiltonian
circuit.append(bog_circuit.inverse(), register)
# perform time evolution by applying z rotations
for q, energy in zip(register, orbital_energies):
circuit.rz(-energy * time, q)
# change back to the original basis
circuit.append(bog_circuit, register)
# simulate the circuit
initial_state = random_statevector(2**n_modes)
final_state = initial_state.evolve(circuit)
# compute the correct state by direct exponentiation
hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix()
exact_evolution_op = expm(-1j * time * hamiltonian_jw)
expected_state = exact_evolution_op @ np.array(initial_state)
# check that the simulated state is correct
fidelity = state_fidelity(final_state, expected_state)
np.testing.assert_allclose(fidelity, 1.0, atol=1e-8)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Compiler Test."""
import os
import unittest
from qiskit import BasicAer
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit import execute
from qiskit.circuit.library import U1Gate, U2Gate
from qiskit.compiler import transpile, assemble
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife
from qiskit.qobj import QasmQobj
class TestCompiler(QiskitTestCase):
"""Qiskit Compiler Tests."""
def setUp(self):
super().setUp()
self.seed_simulator = 42
self.backend = BasicAer.get_backend("qasm_simulator")
def test_example_multiple_compile(self):
"""Test a toy example compiling multiple circuits.
Pass if the results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
bell = QuantumCircuit(qr, cr)
ghz = QuantumCircuit(qr, cr)
# Create a GHZ state
ghz.h(qr[0])
for i in range(4):
ghz.cx(qr[i], qr[i + 1])
# Insert a barrier before measurement
ghz.barrier()
# Measure all of the qubits in the standard basis
for i in range(5):
ghz.measure(qr[i], cr[i])
# Create a Bell state
bell.h(qr[0])
bell.cx(qr[0], qr[1])
bell.barrier()
bell.measure(qr[0], cr[0])
bell.measure(qr[1], cr[1])
shots = 2048
bell_backend = transpile(bell, backend=backend)
ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map)
bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10)
ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10)
bell_result = backend.run(bell_qobj).result()
ghz_result = backend.run(ghz_qobj).result()
threshold = 0.05 * shots
counts_bell = bell_result.get_counts()
target_bell = {"00000": shots / 2, "00011": shots / 2}
self.assertDictAlmostEqual(counts_bell, target_bell, threshold)
counts_ghz = ghz_result.get_counts()
target_ghz = {"00000": shots / 2, "11111": shots / 2}
self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold)
def test_compile_coupling_map(self):
"""Test compile_coupling_map.
If all correct should return data with the same stats. The circuit may
be different.
"""
backend = BasicAer.get_backend("qasm_simulator")
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr, cr, name="qccccccc")
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 = 2048
coupling_map = [[0, 1], [1, 2]]
initial_layout = [0, 1, 2]
qc_b = transpile(
qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout
)
qobj = assemble(qc_b, shots=shots, seed_simulator=88)
job = backend.run(qobj)
result = job.result()
qasm_to_check = qc.qasm()
self.assertEqual(len(qasm_to_check), 173)
counts = result.get_counts(qc)
target = {"000": shots / 2, "111": shots / 2}
threshold = 0.05 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_example_swap_bits(self):
"""Test a toy example swapping a set bit around.
Uses the mapper. Pass if results are correct.
"""
backend = BasicAer.get_backend("qasm_simulator")
coupling_map = [
[0, 1],
[0, 8],
[1, 2],
[1, 9],
[2, 3],
[2, 10],
[3, 4],
[3, 11],
[4, 5],
[4, 12],
[5, 6],
[5, 13],
[6, 7],
[6, 14],
[7, 15],
[8, 9],
[9, 10],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[14, 15],
]
# ┌───┐ ░ ┌─┐
# q0_0: ┤ X ├─X───────────░─┤M├───────────────
# └───┘ │ ░ └╥┘ ┌─┐
# q0_1: ──────┼─────X──X──░──╫────┤M├─────────
# │ │ │ ░ ║ └╥┘ ┌─┐
# q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├───
# │ │ │ ░ ║ ┌─┐ ║ └╥┘
# q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫────
# │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║
# q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫────
# │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐
# q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├
# ░ ║ ║ ║ ║ ║ └╥┘
# c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═
# 0 3 1 4 2 5
n = 3 # make this at least 3
qr0 = QuantumRegister(n)
qr1 = QuantumRegister(n)
ans = ClassicalRegister(2 * n)
qc = QuantumCircuit(qr0, qr1, ans)
# Set the first bit of qr0
qc.x(qr0[0])
# Swap the set bit
qc.swap(qr0[0], qr0[n - 1])
qc.swap(qr0[n - 1], qr1[n - 1])
qc.swap(qr1[n - 1], qr0[1])
qc.swap(qr0[1], qr1[1])
# Insert a barrier before measurement
qc.barrier()
# Measure all of the qubits in the standard basis
for j in range(n):
qc.measure(qr0[j], ans[j])
qc.measure(qr1[j], ans[j + n])
# First version: no mapping
result = execute(
qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
# Second version: map to coupling graph
result = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14
).result()
self.assertEqual(result.get_counts(qc), {"010000": 1024})
def test_parallel_compile(self):
"""Trigger parallel routines in compile."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr[5], cr[0])
qlist = [qc for k in range(10)]
qobj = assemble(transpile(qlist, backend=backend))
self.assertEqual(len(qobj.experiments), 10)
def test_no_conflict_backend_passmanager(self):
"""execute(qc, backend=..., passmanager=...)
See: https://github.com/Qiskit/qiskit-terra/issues/5037
"""
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(2)
qc.append(U1Gate(0), [0])
qc.measure_all()
job = execute(qc, backend=backend, pass_manager=PassManager())
result = job.result().get_counts()
self.assertEqual(result, {"00": 1024})
def test_compile_single_qubit(self):
"""Compile a single-qubit circuit in a non-trivial layout"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
layout = {qr[0]: 12}
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit2 = transpile(
circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qobj = assemble(circuit2)
compiled_instruction = qobj.experiments[0].instructions[0]
self.assertEqual(compiled_instruction.name, "u2")
self.assertEqual(compiled_instruction.qubits, [12])
self.assertEqual(compiled_instruction.params, [0, 3.141592653589793])
def test_compile_pass_manager(self):
"""Test compile with and without an empty pass manager."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.append(U1Gate(3.14), [qr[0]])
qc.append(U2Gate(3.14, 1.57), [qr[0]])
qc.barrier(qr)
qc.measure(qr, cr)
backend = BasicAer.get_backend("qasm_simulator")
qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42)
rtrue = backend.run(qrtrue).result()
qrfalse = assemble(PassManager().run(qc), seed_simulator=42)
rfalse = backend.run(qrfalse).result()
self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
def test_mapper_overoptimization(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
# ┌───┐ ┌─┐
# q0_0: ┤ X ├──■───────┤M├───────────
# ├───┤┌─┴─┐┌───┐└╥┘ ┌─┐
# q0_1: ┤ Y ├┤ X ├┤ S ├─╫───■──┤M├───
# ├───┤└───┘├───┤ ║ ┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├──■──┤ T ├─╫─┤ X ├─╫─┤M├
# └───┘┌─┴─┐├───┤ ║ └┬─┬┘ ║ └╥┘
# q0_3: ─────┤ X ├┤ H ├─╫──┤M├──╫──╫─
# └───┘└───┘ ║ └╥┘ ║ ║
# c0: 4/════════════════╩═══╩═══╩══╩═
# 0 3 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.x(qr[0])
circ.y(qr[1])
circ.z(qr[2])
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.s(qr[1])
circ.t(qr[2])
circ.h(qr[3])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 1000
result1 = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count1 = result1.result().get_counts()
result2 = execute(
circ,
backend=self.backend,
coupling_map=None,
seed_simulator=self.seed_simulator,
seed_transpiler=8,
shots=shots,
)
count2 = result2.result().get_counts()
self.assertDictAlmostEqual(count1, count2, shots * 0.02)
def test_grovers_circuit(self):
"""Testing a circuit originated in the Grover algorithm"""
shots = 1000
coupling_map = None
# 6-qubit grovers
#
# ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐
# q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├───
# ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐
# q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├
# ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘
# q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─
# ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║
# q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─
# └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║
# q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─
# └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║
# q0_5: ────────────────────────────────────────────────────────░──╫──╫─
# ░ ║ ║
# c0: 2/═══════════════════════════════════════════════════════════╩══╩═
# 0 1
qr = QuantumRegister(6)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr, name="grovers")
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.x(qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.cx(qr[1], qr[3])
circuit.ccx(qr[2], qr[3], qr[4])
circuit.cx(qr[1], qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[4])
circuit.ccx(qr[0], qr[1], qr[4])
circuit.h(qr[4])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[4])
circuit.barrier(qr)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
result = execute(
circuit,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = result.result().get_counts()
expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_domain_error(self):
"""Check for floating point errors.
The math library operates over floats and introduces floating point
errors that should be avoided.
See: https://github.com/Qiskit/qiskit-terra/issues/111
"""
# ┌───┐┌───┐ ┌─┐
# q0_0: ┤ Y ├┤ X ├─────┤M├─────────────────────
# └───┘└─┬─┘ └╥┘ ┌─┐
# q0_1: ───────■────────╫─────────────■──┤M├───
# ┌───┐┌───┐┌───┐ ║ ┌───┐┌───┐┌─┴─┐└╥┘┌─┐
# q0_2: ┤ Z ├┤ H ├┤ Y ├─╫─┤ T ├┤ Z ├┤ X ├─╫─┤M├
# └┬─┬┘└───┘└───┘ ║ └───┘└───┘└───┘ ║ └╥┘
# q0_3: ─┤M├────────────╫─────────────────╫──╫─
# └╥┘ ║ ║ ║
# c0: 4/══╩═════════════╩═════════════════╩══╩═
# 3 0 1 2
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circ = QuantumCircuit(qr, cr)
circ.y(qr[0])
circ.z(qr[2])
circ.h(qr[2])
circ.cx(qr[1], qr[0])
circ.y(qr[2])
circ.t(qr[2])
circ.z(qr[2])
circ.cx(qr[1], qr[2])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
coupling_map = [[0, 2], [1, 2], [2, 3]]
shots = 2000
job = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
seed_simulator=self.seed_simulator,
shots=shots,
)
counts = job.result().get_counts()
target = {"0001": shots / 2, "0101": shots / 2}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_random_parameter_circuit(self):
"""Run a circuit with randomly generated parameters."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm"))
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
shots = 1024
qobj = execute(
circ,
backend=self.backend,
coupling_map=coupling_map,
shots=shots,
seed_simulator=self.seed_simulator,
)
counts = qobj.result().get_counts()
expected_probs = {
"00000": 0.079239867254200971,
"00001": 0.032859032998526903,
"00010": 0.10752610993531816,
"00011": 0.018818532050952699,
"00100": 0.054830807251011054,
"00101": 0.0034141983951965164,
"00110": 0.041649309748902276,
"00111": 0.039967731207338125,
"01000": 0.10516937819949743,
"01001": 0.026635620063700002,
"01010": 0.0053475143548793866,
"01011": 0.01940513314416064,
"01100": 0.0044028405481225047,
"01101": 0.057524760052126644,
"01110": 0.010795354134597078,
"01111": 0.026491296821535528,
"10000": 0.094827455395274859,
"10001": 0.0008373965072688836,
"10010": 0.029082297894094441,
"10011": 0.012386622870598416,
"10100": 0.018739140061148799,
"10101": 0.01367656456536896,
"10110": 0.039184170706009248,
"10111": 0.062339335178438288,
"11000": 0.00293674365989009,
"11001": 0.012848433960739968,
"11010": 0.018472497159499782,
"11011": 0.0088903691234912003,
"11100": 0.031305389080034329,
"11101": 0.0004788556283690458,
"11110": 0.002232419390471667,
"11111": 0.017684822659235985,
}
target = {key: shots * val for key, val in expected_probs.items()}
threshold = 0.04 * shots
self.assertDictAlmostEqual(counts, target, threshold)
def test_yzy_zyz_cases(self):
"""yzy_to_zyz works in previously failed cases.
See: https://github.com/Qiskit/qiskit-terra/issues/607
"""
backend = FakeTenerife()
qr = QuantumRegister(2)
circ1 = QuantumCircuit(qr)
circ1.cx(qr[0], qr[1])
circ1.rz(0.7, qr[1])
circ1.rx(1.570796, qr[1])
qobj1 = assemble(transpile(circ1, backend))
self.assertIsInstance(qobj1, QasmQobj)
circ2 = QuantumCircuit(qr)
circ2.y(qr[0])
circ2.h(qr[0])
circ2.s(qr[0])
circ2.h(qr[0])
qobj2 = assemble(transpile(circ2, backend))
self.assertIsInstance(qobj2, QasmQobj)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/kanavsetia/qiskitcamp
|
kanavsetia
|
import numpy as np
from qiskit.chemistry import bksf
from qiskit.chemistry.fermionic_operator import FermionicOperator as FO
import pdb
from collections import OrderedDict
from pyscf import gto, scf, ao2mo
from pyscf.lib import param
from scipy import linalg as scila
from pyscf.lib import logger as pylogger
# from qiskit.chemistry import AquaChemistryError
from qiskit.chemistry import QMolecule
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager, transpile_dag, transpile
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms.adaptive import VQE
from qiskit.aqua.algorithms.classical import ExactEigensolver
from qiskit.chemistry import FermionicOperator
from qiskit.quantum_info import Pauli
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import CXCancellation, Optimize1qGates
from qiskit import BasicAer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
import networkx as nx
import int_func
########## Random Test Case ##############
np.set_printoptions(linewidth=230,suppress=True)
two_body = np.zeros([4,4,4,4])
one_body=np.zeros([4,4])
one_body[3,2]=.5
one_body[2,3]=0.5
one_body[0,3]=0.4
one_body[3,0]=0.4
one_body[3,1]=0.3
one_body[1,3]=0.3
one_body[1,2]=0.21
one_body[2,1]=0.21
########### H2O ######################
mol = gto.Mole()
mol.atom = [['O',(0.0, 0.0,0.0)],['H',(1, 0, 0)], ['H',(-1.0,0.0,0.0)]]
mol.basis = 'sto-3g'
_q_=int_func.qmol_func(mol, atomic=True)
one_body=_q_.one_body_integrals
obs=np.size(one_body,1)
two_body=np.zeros([obs,obs,obs,obs])
########### NH3 ######################
mol = gto.Mole()
mol.atom = [['N', (0.0000, 0.0000, 0.0000)],
['H', (0.0000, -0.9377, -0.3816)],
['H', (0.8121, 0.4689 ,-0.3816)],
['H', (-0.8121, 0.4689 ,-0.3816)]]
mol.basis = 'sto-3g'
_q_=int_func.qmol_func(mol, atomic=True)
one_body=_q_.one_body_integrals
obs=np.size(one_body,1)
two_body=np.zeros([obs,obs,obs,obs])
########### CH4 ######################
mol = gto.Mole()
mol.atom=[['C', (2.5369, 0.0000, 0.0000)],
['H', (3.0739, 0.3100, 0.0000)],
['H', (2.0000, -0.3100, 0.0000)],
['H', (2.2269, 0.5369, 0.0000)],
['H', (2.8469, -0.5369, 0.0000)]]
mol.basis = 'sto-3g'
_q_=int_func.qmol_func(mol, atomic=True)
one_body=_q_.one_body_integrals
obs=np.size(one_body,1)
two_body=np.zeros([obs,obs,obs,obs])
fer_op1=FO(h1=one_body,h2=np.einsum('ijkl->iljk',two_body))
jw_qo=fer_op1.mapping('jordan_wigner')
# print(jw_qo.print_operators())
simulator = BasicAer.get_backend('qasm_simulator')
q = QuantumRegister(np.size(one_body,1), name='q')
q_circ=jw_qo.evolve(None, 1, 'circuit', 1,q)
print("Gate count without using any optimization")
print(q_circ.count_ops())
pass_manager = PassManager()
pass_manager.append(Optimize1qGates())
# q_circ.draw()
new_circ = transpile(q_circ, simulator, pass_manager=pass_manager)
pass_manager=PassManager()
pass_manager.append(CXCancellation())
for i in range(np.size(one_body,1)):
new_circ = transpile(new_circ, simulator, pass_manager=pass_manager)
# new_circ = transpile(new_circ, simulator, pass_manager=pass_manager)
print("Gate count using transpiler")
print(new_circ.count_ops())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
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.
#
# 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 of circuit with Latex drawer."""
import os
import unittest
import math
import numpy as np
from qiskit.visualization import circuit_drawer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate, CPhaseGate
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
from .visualization import QiskitVisualizationTestCase
pi = np.pi
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
class TestLatexSourceGenerator(QiskitVisualizationTestCase):
"""Qiskit latex source generator tests."""
def _get_resource_path(self, filename):
reference_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(reference_dir, filename)
def test_empty_circuit(self):
"""Test draw an empty circuit"""
filename = self._get_resource_path("test_latex_empty.tex")
circuit = QuantumCircuit(1)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_tiny_circuit(self):
"""Test draw tiny circuit."""
filename = self._get_resource_path("test_latex_tiny.tex")
circuit = QuantumCircuit(1)
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_multi_underscore_reg_names(self):
"""Test multi-underscores in register names display properly"""
filename1 = self._get_resource_path("test_latex_multi_underscore_true.tex")
filename2 = self._get_resource_path("test_latex_multi_underscore_false.tex")
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)
circuit_drawer(circuit, cregbundle=True, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=False, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_normal_circuit(self):
"""Test draw normal size circuit."""
filename = self._get_resource_path("test_latex_normal.tex")
circuit = QuantumCircuit(5)
for qubit in range(5):
circuit.h(qubit)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_4597(self):
"""Test cregbundle and conditional gates.
See: https://github.com/Qiskit/qiskit-terra/pull/4597"""
filename = self._get_resource_path("test_latex_4597.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[2]).c_if(cr, 2)
circuit.draw(output="latex_source", cregbundle=True)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_deep_circuit(self):
"""Test draw deep circuit."""
filename = self._get_resource_path("test_latex_deep.tex")
circuit = QuantumCircuit(1)
for _ in range(100):
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_huge_circuit(self):
"""Test draw huge circuit."""
filename = self._get_resource_path("test_latex_huge.tex")
circuit = QuantumCircuit(40)
for qubit in range(39):
circuit.h(qubit)
circuit.cx(qubit, 39)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_teleport(self):
"""Test draw teleport circuit."""
filename = self._get_resource_path("test_latex_teleport.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
# Prepare an initial state
circuit.u(0.3, 0.2, 0.1, [qr[0]])
# Prepare a Bell pair
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
# Barrier following state preparation
circuit.barrier(qr)
# Measure in the Bell basis
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
# Apply a correction
circuit.z(qr[2]).c_if(cr, 1)
circuit.x(qr[2]).c_if(cr, 2)
circuit.measure(qr[2], cr[2])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_global_phase(self):
"""Test circuit with global phase"""
filename = self._get_resource_path("test_latex_global_phase.tex")
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
filename = self._get_resource_path("test_latex_no_ops.tex")
circuit = QuantumCircuit(2, 3)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
filename = self._get_resource_path("test_latex_long_name.tex")
# 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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
filename = self._get_resource_path("test_latex_conditional.tex")
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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
filename = self._get_resource_path("test_latex_plot_partial_barriers.tex")
# 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])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
filename1 = self._get_resource_path("test_latex_plot_barriers_true.tex")
filename2 = self._get_resource_path("test_latex_plot_barriers_false.tex")
# 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("sn 1")
# check the barriers plot properly when plot_barriers= True
circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True)
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", plot_barriers=False)
self.assertEqualToReference(filename2)
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"""
filename = self._get_resource_path("test_latex_no_barriers_false.tex")
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_barrier_label(self):
"""Test the barrier label"""
filename = self._get_resource_path("test_latex_barrier_label.tex")
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_big_gates(self):
"""Test large gates with params"""
filename = self._get_resource_path("test_latex_big_gates.tex")
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)), [])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
filename = self._get_resource_path("test_latex_cnot.tex")
qr = QuantumRegister(5, "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_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
filename = self._get_resource_path("test_latex_pauli_clifford.tex")
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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_u_gates(self):
"""Test U 1, 2, & 3 gates"""
filename = self._get_resource_path("test_latex_u_gates.tex")
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(3 * pi / 2), [0])
circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1])
circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2])
circuit.append(CU1Gate(pi / 4), [0, 1])
circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3])
circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
filename1 = self._get_resource_path("test_latex_creg_initial_true.tex")
filename2 = self._get_resource_path("test_latex_creg_initial_false.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
circuit_drawer(
circuit, filename=filename1, output="latex_source", cregbundle=True, initial_state=True
)
self.assertEqualToReference(filename1)
circuit_drawer(
circuit,
filename=filename2,
output="latex_source",
cregbundle=False,
initial_state=False,
)
self.assertEqualToReference(filename2)
def test_r_gates(self):
"""Test all R gates"""
filename = self._get_resource_path("test_latex_r_gates.tex")
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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
filename = self._get_resource_path("test_latex_cswap_rzz.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.x(1)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
filename = self._get_resource_path("test_latex_ghz_to_gate.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, 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])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
filename1 = self._get_resource_path("test_latex_scale_default.tex")
filename2 = self._get_resource_path("test_latex_scale_half.tex")
filename3 = self._get_resource_path("test_latex_scale_double.tex")
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
circuit_drawer(circuit, filename=filename1, output="latex_source")
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", scale=0.5)
self.assertEqualToReference(filename2)
circuit_drawer(circuit, filename=filename3, output="latex_source", scale=2.0)
self.assertEqualToReference(filename3)
def test_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
filename = self._get_resource_path("test_latex_pi_param_expr.tex")
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
filename = self._get_resource_path("test_latex_partial_layout.tex")
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
circuit_drawer(transpiled, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
filename = self._get_resource_path("test_latex_init_reset.tex")
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_iqx_colors(self):
"""Tests with iqx color scheme"""
filename = self._get_resource_path("test_latex_iqx.tex")
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.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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
filename = self._get_resource_path("test_latex_reverse_bits.tex")
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit_drawer(circuit, filename=filename, output="latex_source", reverse_bits=True)
self.assertEqualToReference(filename)
def test_meas_condition(self):
"""Tests measure with a condition"""
filename = self._get_resource_path("test_latex_meas_condition.tex")
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)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_inst_with_cbits(self):
"""Test custom instructions with classical bits"""
filename = self._get_resource_path("test_latex_inst_with_cbits.tex")
qinst = QuantumRegister(2, "q")
cinst = ClassicalRegister(2, "c")
inst = QuantumCircuit(qinst, cinst, name="instruction").to_instruction()
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit(self):
"""Tests conditioning gates on single classical bit"""
filename = self._get_resource_path("test_latex_cif_single_bit.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit_cregbundle(self):
"""Tests conditioning gates on single classical bit with cregbundle"""
filename = self._get_resource_path("test_latex_cif_single_bit_bundle.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=True, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
filename = self._get_resource_path("test_latex_registerless_one_bit.tex")
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
filename1 = self._get_resource_path("test_latex_meas_cond_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_true.tex")
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)
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_measures_with_conditions_with_bits(self):
"""Condition and measure on single bits cregbundle true"""
filename1 = self._get_resource_path("test_latex_meas_cond_bits_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_bits_true.tex")
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])
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions and measures work with bits reversed"""
filename = self._get_resource_path("test_latex_cond_reverse.tex")
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
circuit_drawer(
circuit, cregbundle=False, reverse_bits=True, filename=filename, output="latex_source"
)
self.assertEqualToReference(filename)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with a condition"""
filename = self._get_resource_path("test_latex_sidetext_condition.tex")
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)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
filename = self._get_resource_path("test_latex_idle_wires_barrier.tex")
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_wire_order(self):
"""Test the wire_order option to latex drawer"""
filename = self._get_resource_path("test_latex_wire_order.tex")
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 12)
circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=filename,
output="latex_source",
)
self.assertEqualToReference(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, execute
from qiskit_quantinuum import Quantinuum
from qiskit.visualization import plot_histogram
# Quantinuum.save_account(user_name="first.last@company.com")
Quantinuum.save_account(user_name="megan.l.kohagen@quantinuum.com")
Quantinuum.load_account()
Quantinuum.backends()
device = 'H1-2E'
backend = Quantinuum.get_backend(device)
status = backend.status()
print(device, "status :", status.status_msg)
n_qubits = 2
circuit = QuantumCircuit(n_qubits, n_qubits, name='Bell Test')
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
circuit.draw()
shots = 100
job = execute(circuit, backend, shots=shots)
job.status()
result = job.result()
print("Job ID:", result.job_id)
print("Job success:", result.success)
counts = result.get_counts()
print("Total count for 00 and 11 are:",counts)
# Result should not be '0', it should be '00'!
plot_histogram(counts)
import json
with open(f'results_{result.job_id}.json', 'w') as f:
json.dump(result.get_counts(), f)
device = 'H1-2E'
job_id = 'insert job id'
backend = Quantinuum.get_backend(device)
job = backend.retrieve_job(job_id)
result = job.result()
counts = result.get_counts()
print(counts)
device = 'H1'
shots = 100
backend = Quantinuum.get_backend(device)
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts()
print(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
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)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を用意
q = QuantumCircuit(1)
# 回路を描画
q.draw(output="mpl")
# 量子ゲートで回路を作成
q.x(0) # Xゲートを0番目の量子ビットに操作します。
# 回路を描画
q.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute( q, vector_sim )
result = job.result().get_statevector(q, decimals=3)
print(result)
|
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.
"""Expression-tree nodes."""
# Given the nature of the tree representation and that there are helper functions associated with
# many of the classes whose arguments naturally share names with themselves, it's inconvenient to
# use synonyms everywhere. This goes for the builtin 'type' as well.
# pylint: disable=redefined-builtin,redefined-outer-name
from __future__ import annotations
__all__ = [
"Expr",
"Var",
"Value",
"Cast",
"Unary",
"Binary",
]
import abc
import enum
import typing
from .. import types
if typing.TYPE_CHECKING:
import qiskit
_T_co = typing.TypeVar("_T_co", covariant=True)
# If adding nodes, remember to update `visitors.ExprVisitor` as well.
class Expr(abc.ABC):
"""Root base class of all nodes in the expression tree. The base case should never be
instantiated directly.
This must not be subclassed by users; subclasses form the internal data of the representation of
expressions, and it does not make sense to add more outside of Qiskit library code.
All subclasses are responsible for setting their ``type`` attribute in their ``__init__``, and
should not call the parent initialiser."""
__slots__ = ("type",)
type: types.Type
# Sentinel to prevent instantiation of the base class.
@abc.abstractmethod
def __init__(self): # pragma: no cover
pass
def accept(
self, visitor: qiskit.circuit.classical.expr.ExprVisitor[_T_co], /
) -> _T_co: # pragma: no cover
"""Call the relevant ``visit_*`` method on the given :class:`ExprVisitor`. The usual entry
point for a simple visitor is to construct it, and then call :meth:`accept` on the root
object to be visited. For example::
expr = ...
visitor = MyVisitor()
visitor.accept(expr)
Subclasses of :class:`Expr` should override this to call the correct virtual method on the
visitor. This implements double dispatch with the visitor."""
return visitor.visit_generic(self)
@typing.final
class Cast(Expr):
"""A cast from one type to another, implied by the use of an expression in a different
context."""
__slots__ = ("operand", "implicit")
def __init__(self, operand: Expr, type: types.Type, implicit: bool = False):
self.type = type
self.operand = operand
self.implicit = implicit
def accept(self, visitor, /):
return visitor.visit_cast(self)
def __eq__(self, other):
return (
isinstance(other, Cast)
and self.type == other.type
and self.operand == other.operand
and self.implicit == other.implicit
)
def __repr__(self):
return f"Cast({self.operand}, {self.type}, implicit={self.implicit})"
@typing.final
class Var(Expr):
"""A classical variable."""
__slots__ = ("var",)
def __init__(
self, var: qiskit.circuit.Clbit | qiskit.circuit.ClassicalRegister, type: types.Type
):
self.type = type
self.var = var
def accept(self, visitor, /):
return visitor.visit_var(self)
def __eq__(self, other):
return isinstance(other, Var) and self.type == other.type and self.var == other.var
def __repr__(self):
return f"Var({self.var}, {self.type})"
@typing.final
class Value(Expr):
"""A single scalar value."""
__slots__ = ("value",)
def __init__(self, value: typing.Any, type: types.Type):
self.type = type
self.value = value
def accept(self, visitor, /):
return visitor.visit_value(self)
def __eq__(self, other):
return isinstance(other, Value) and self.type == other.type and self.value == other.value
def __repr__(self):
return f"Value({self.value}, {self.type})"
@typing.final
class Unary(Expr):
"""A unary expression.
Args:
op: The opcode describing which operation is being done.
operand: The operand of the operation.
type: The resolved type of the result.
"""
__slots__ = ("op", "operand")
class Op(enum.Enum):
"""Enumeration of the opcodes for unary operations.
The bitwise negation :data:`BIT_NOT` takes a single bit or an unsigned integer of known
width, and returns a value of the same type.
The logical negation :data:`LOGIC_NOT` takes an input that is implicitly coerced to a
Boolean, and returns a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`.
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_NOT = 1
"""Bitwise negation. ``~operand``."""
LOGIC_NOT = 2
"""Logical negation. ``!operand``."""
def __str__(self):
return f"Unary.{super().__str__()}"
def __repr__(self):
return f"Unary.{super().__repr__()}"
def __init__(self, op: Unary.Op, operand: Expr, type: types.Type):
self.op = op
self.operand = operand
self.type = type
def accept(self, visitor, /):
return visitor.visit_unary(self)
def __eq__(self, other):
return (
isinstance(other, Unary)
and self.type == other.type
and self.op is other.op
and self.operand == other.operand
)
def __repr__(self):
return f"Unary({self.op}, {self.operand}, {self.type})"
@typing.final
class Binary(Expr):
"""A binary expression.
Args:
op: The opcode describing which operation is being done.
left: The left-hand operand.
right: The right-hand operand.
type: The resolved type of the result.
"""
__slots__ = ("op", "left", "right")
class Op(enum.Enum):
"""Enumeration of the opcodes for binary operations.
The bitwise operations :data:`BIT_AND`, :data:`BIT_OR` and :data:`BIT_XOR` apply to two
operands of the same type, which must be a single bit or an unsigned integer of fixed width.
The resultant type is the same as the two input types.
The logical operations :data:`LOGIC_AND` and :data:`LOGIC_OR` first implicitly coerce their
arguments to Booleans, and then apply the logical operation. The resultant type is always
Boolean.
The binary mathematical relations :data:`EQUAL`, :data:`NOT_EQUAL`, :data:`LESS`,
:data:`LESS_EQUAL`, :data:`GREATER` and :data:`GREATER_EQUAL` take unsigned integers
(with an implicit cast to make them the same width), and return a Boolean.
"""
# If adding opcodes, remember to add helper constructor functions in `constructors.py`
# The opcode integers should be considered a public interface; they are used by
# serialisation formats that may transfer data between different versions of Qiskit.
BIT_AND = 1
"""Bitwise "and". ``lhs & rhs``."""
BIT_OR = 2
"""Bitwise "or". ``lhs | rhs``."""
BIT_XOR = 3
"""Bitwise "exclusive or". ``lhs ^ rhs``."""
LOGIC_AND = 4
"""Logical "and". ``lhs && rhs``."""
LOGIC_OR = 5
"""Logical "or". ``lhs || rhs``."""
EQUAL = 6
"""Numeric equality. ``lhs == rhs``."""
NOT_EQUAL = 7
"""Numeric inequality. ``lhs != rhs``."""
LESS = 8
"""Numeric less than. ``lhs < rhs``."""
LESS_EQUAL = 9
"""Numeric less than or equal to. ``lhs <= rhs``"""
GREATER = 10
"""Numeric greater than. ``lhs > rhs``."""
GREATER_EQUAL = 11
"""Numeric greater than or equal to. ``lhs >= rhs``."""
def __str__(self):
return f"Binary.{super().__str__()}"
def __repr__(self):
return f"Binary.{super().__repr__()}"
def __init__(self, op: Binary.Op, left: Expr, right: Expr, type: types.Type):
self.op = op
self.left = left
self.right = right
self.type = type
def accept(self, visitor, /):
return visitor.visit_binary(self)
def __eq__(self, other):
return (
isinstance(other, Binary)
and self.type == other.type
and self.op is other.op
and self.left == other.left
and self.right == other.right
)
def __repr__(self):
return f"Binary({self.op}, {self.left}, {self.right}, {self.type})"
|
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_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the pulse scheduler passes."""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule
from qiskit.circuit import Gate, Parameter
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate
from qiskit.exceptions import QiskitError
from qiskit.pulse import (
Schedule,
DriveChannel,
AcquireChannel,
Acquire,
MeasureChannel,
MemorySlot,
Gaussian,
Play,
transforms,
)
from qiskit.pulse import build, macros, play, InstructionScheduleMap
from qiskit.providers.fake_provider import FakeBackend, FakeOpenPulse2Q, FakeOpenPulse3Q
from qiskit.test import QiskitTestCase
class TestBasicSchedule(QiskitTestCase):
"""Scheduling tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.inst_map = self.backend.defaults().instruction_schedule_map
def test_unavailable_defaults(self):
"""Test backend with unavailable defaults."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
backend = FakeBackend(None)
backend.defaults = backend.configuration
self.assertRaises(QiskitError, lambda: schedule(qc, backend))
def test_alap_pass(self):
"""Test ALAP scheduling."""
# ┌───────────────┐ ░ ┌─┐
# q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├───
# └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐
# q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├
# └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘
# c0: 2/═════════════════════════════════════════════╩══╩═
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], [q[1]])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend)
# X pulse on q0 should end at the start of the CNOT
expected = Schedule(
(2, self.inst_map.get("u2", [0], 3.14, 1.57)),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_single_circuit_list_schedule(self):
"""Test that passing a single circuit list to schedule() returns a list."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule([qc], self.backend, method="alap")
expected = Schedule()
self.assertIsInstance(sched, list)
self.assertEqual(sched[0].instructions, expected.instructions)
def test_alap_with_barriers(self):
"""Test that ALAP respects barriers on new qubits."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0), (2, self.inst_map.get("u2", [1], 0, 0))
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_empty_circuit_schedule(self):
"""Test empty circuit being scheduled."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule(qc, self.backend, method="alap")
expected = Schedule()
self.assertEqual(sched.instructions, expected.instructions)
def test_alap_aligns_end(self):
"""Test that ALAP always acts as though there is a final global barrier."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U3Gate(0, 0, 0), [q[0]])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected_sched = Schedule(
(2, self.inst_map.get("u2", [1], 0, 0)), self.inst_map.get("u3", [0], 0, 0, 0)
)
for actual, expected in zip(sched.instructions, expected_sched.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
self.assertEqual(
sched.ch_duration(DriveChannel(0)), expected_sched.ch_duration(DriveChannel(1))
)
def test_asap_pass(self):
"""Test ASAP scheduling."""
# ┌───────────────┐ ░ ┌─┐
# q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├───
# └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐
# q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├
# └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘
# c0: 2/═════════════════════════════════════════════╩══╩═
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_soon_as_possible")
# X pulse on q0 should start at t=0
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_alap_resource_respecting(self):
"""Test that the ALAP pass properly respects busy resources when backwards scheduling.
For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits'
timeline."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
sched = schedule(qc, self.backend, method="as_late_as_possible")
insts = sched.instructions
self.assertEqual(insts[0][0], 0)
self.assertEqual(insts[6][0], 22)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_late_as_possible")
self.assertEqual(sched.instructions[-1][0], 24)
def test_inst_map_schedules_unaltered(self):
"""Test that forward scheduling doesn't change relative timing with a command."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
sched1 = schedule(qc, self.backend, method="as_soon_as_possible")
sched2 = schedule(qc, self.backend, method="as_late_as_possible")
for asap, alap in zip(sched1.instructions, sched2.instructions):
self.assertEqual(asap[0], alap[0])
self.assertEqual(asap[1], alap[1])
insts = sched1.instructions
self.assertEqual(insts[0][0], 0) # shift phase
self.assertEqual(insts[1][0], 0) # ym_d0
self.assertEqual(insts[2][0], 0) # x90p_d1
self.assertEqual(insts[3][0], 2) # cr90p_u0
self.assertEqual(insts[4][0], 11) # xp_d0
self.assertEqual(insts[5][0], 13) # cr90m_u0
def test_measure_combined(self):
"""
Test to check for measure on the same qubit which generated another measure schedule.
The measures on different qubits are combined, but measures on the same qubit
adds another measure to the schedule.
"""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.cx(q[0], q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[1], c[1])
sched = schedule(qc, self.backend, method="as_soon_as_possible")
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
(2, self.inst_map.get("cx", [0, 1])),
(24, self.inst_map.get("measure", [0, 1])),
(34, self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(1)])),
(34, Acquire(10, AcquireChannel(1), MemorySlot(1))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_3q_schedule(self):
"""Test a schedule that was recommended by David McKay :D"""
# ┌─────────────────┐
# q0_0: ─────────■─────────┤ U3(3.14,1.57,0) ├────────────────────────
# ┌─┴─┐ └┬───────────────┬┘
# q0_1: ───────┤ X ├────────┤ U2(3.14,1.57) ├───■─────────────────────
# ┌──────┴───┴──────┐ └───────────────┘ ┌─┴─┐┌─────────────────┐
# q0_2: ┤ U2(0.778,0.122) ├───────────────────┤ X ├┤ U2(0.778,0.122) ├
# └─────────────────┘ └───┘└─────────────────┘
backend = FakeOpenPulse3Q()
inst_map = backend.defaults().instruction_schedule_map
q = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.778, 0.122), [q[2]])
qc.append(U3Gate(3.14, 1.57, 0), [q[0]])
qc.append(U2Gate(3.14, 1.57), [q[1]])
qc.cx(q[1], q[2])
qc.append(U2Gate(0.778, 0.122), [q[2]])
sched = schedule(qc, backend)
expected = Schedule(
inst_map.get("cx", [0, 1]),
(22, inst_map.get("u2", [1], 3.14, 1.57)),
(22, inst_map.get("u2", [2], 0.778, 0.122)),
(24, inst_map.get("cx", [1, 2])),
(44, inst_map.get("u3", [0], 3.14, 1.57, 0)),
(46, inst_map.get("u2", [2], 0.778, 0.122)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_schedule_multi(self):
"""Test scheduling multiple circuits at once."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc0 = QuantumCircuit(q, c)
qc0.cx(q[0], q[1])
qc1 = QuantumCircuit(q, c)
qc1.cx(q[0], q[1])
schedules = schedule([qc0, qc1], self.backend)
expected_insts = schedule(qc0, self.backend).instructions
for actual, expected in zip(schedules[0].instructions, expected_insts):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_circuit_name_kept(self):
"""Test that the new schedule gets its name from the circuit."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c, name="CIRCNAME")
qc.cx(q[0], q[1])
sched = schedule(qc, self.backend, method="asap")
self.assertEqual(sched.name, qc.name)
sched = schedule(qc, self.backend, method="alap")
self.assertEqual(sched.name, qc.name)
def test_can_add_gates_into_free_space(self):
"""The scheduler does some time bookkeeping to know when qubits are free to be
scheduled. Make sure this works for qubits that are used in the future. This was
a bug, uncovered by this example:
q0 = - - - - |X|
q1 = |X| |u2| |X|
In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather
than immediately before the X gate.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.append(U1Gate(3.14), [qr[i]])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_barriers_in_middle(self):
"""As a follow on to `test_can_add_gates_into_free_space`, similar issues
arose for barriers, specifically.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.barrier(qr[i])
qc.append(U1Gate(3.14), [qr[i]])
qc.barrier(qr[i])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_parametric_input(self):
"""Test that scheduling works with parametric pulses as input."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.append(Gate("gauss", 1, []), qargs=[qr[0]])
custom_gauss = Schedule(
Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=pi / 2), DriveChannel(0))
)
self.inst_map.add("gauss", [0], custom_gauss)
sched = schedule(qc, self.backend, inst_map=self.inst_map)
self.assertEqual(sched.instructions[0], custom_gauss.instructions[0])
def test_pulse_gates(self):
"""Test scheduling calibrated pulse gates."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.add_calibration("u2", [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0])
qc.add_calibration("u2", [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0])
sched = schedule(qc, self.backend)
expected = Schedule(
Play(Gaussian(28, 0.2, 4), DriveChannel(0)),
(28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1)))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_calibrated_measurements(self):
"""Test scheduling calibrated measurements."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.measure(q[0], c[0])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
expected = Schedule(self.inst_map.get("u2", [0], 0, 0), (2, meas_sched))
self.assertEqual(sched.instructions, expected.instructions)
def test_subset_calibrated_measurements(self):
"""Test that measurement calibrations can be added and used for some qubits, even
if the other qubits do not also have calibrated measurements."""
qc = QuantumCircuit(3, 3)
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
meas_scheds = []
for qubit in [0, 2]:
meas = Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) + Acquire(
1200, AcquireChannel(qubit), MemorySlot(qubit)
)
meas_scheds.append(meas)
qc.add_calibration("measure", [qubit], meas)
meas = macros.measure([1], FakeOpenPulse3Q())
meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)])
sched = schedule(qc, FakeOpenPulse3Q())
expected = Schedule(meas_scheds[0], meas_scheds[1], meas)
self.assertEqual(sched.instructions, expected.instructions)
def test_clbits_of_calibrated_measurements(self):
"""Test that calibrated measurements are only used when the classical bits also match."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.measure(q[0], c[1])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
# Doesn't use the calibrated schedule because the classical memory slots do not match
expected = Schedule(macros.measure([0], self.backend, qubit_mem_slots={0: 1}))
self.assertEqual(sched.instructions, expected.instructions)
def test_metadata_is_preserved_alap(self):
"""Test that circuit metadata is preserved in output schedule with alap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="alap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_metadata_is_preserved_asap(self):
"""Test that circuit metadata is preserved in output schedule with asap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="asap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_scheduler_with_params_bound(self):
"""Test scheduler with parameters defined and bound"""
x = Parameter("x")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
expected_schedule = Schedule()
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
qc = qc.assign_parameters({x: 1})
sched = schedule(qc, self.backend)
self.assertEqual(sched, expected_schedule)
def test_scheduler_with_params_not_bound(self):
"""Test scheduler with parameters defined but not bound"""
x = Parameter("amp")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
with build() as expected_schedule:
play(Gaussian(duration=160, amp=x, sigma=40), DriveChannel(0))
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
sched = schedule(qc, self.backend)
self.assertEqual(sched, transforms.target_qobj_transform(expected_schedule))
def test_schedule_block_in_instmap(self):
"""Test schedule block in instmap can be scheduled."""
duration = Parameter("duration")
with build() as pulse_prog:
play(Gaussian(duration, 0.1, 10), DriveChannel(0))
instmap = InstructionScheduleMap()
instmap.add("block_gate", (0,), pulse_prog, ["duration"])
qc = QuantumCircuit(1)
qc.append(Gate("block_gate", 1, [duration]), [0])
qc.assign_parameters({duration: 100}, inplace=True)
sched = schedule(qc, self.backend, inst_map=instmap)
ref_sched = Schedule()
ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0))
self.assertEqual(sched, ref_sched)
|
https://github.com/luis6156/Shor-s-Quantum-Algorithm
|
luis6156
|
from qiskit import QuantumCircuit, Aer, execute, IBMQ
from qiskit.utils import QuantumInstance
import numpy as np
from qiskit.algorithms import Shor
IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor = Shor(quantum_instance)
result_dict = my_shor.factor(15)
print(result_dict)
|
https://github.com/taalexander/IEEE-Quantum-Week-2021
|
taalexander
|
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
hub = 'ibm-q-community'
group = 'ieee-session'
project = 'event-2021'
backend_name = 'ibm_perth'
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq.exceptions import IBMQAccountCredentialsNotFound
#IBMQ.save_account("<token>")
try:
IBMQ.load_account()
except IBMQAccountCredentialsNotFound:
print("Could not find your credentials"
"Uncomment the lines above and insert your API token "
"which can be found here https://quantum-computing.ibm.com/account."
"After saving your credentials add back the comment."
)
raise
from qiskit.providers.ibmq.exceptions import IBMQProviderError
# load provider
try:
provider = IBMQ.get_provider(hub=hub, group=group, project=project)
except IBMQProviderError:
print(
"The provider was not found. "
"This means your IBM Quantum Services account was not yet added. "
"Contact one of the tutorial presenters to add you."
)
raise
# Get our backend
backend = provider.get_backend(backend_name)
qubit = 0
from qiskit import QuantumCircuit
h_qc = QuantumCircuit(1, 1, name="|+> Prep")
h_qc.h(0)
h_qc.measure(0, 0)
h_qc.draw(idle_wires=False)
from qiskit import transpile
h_qc_transpiled = transpile(h_qc, backend, initial_layout=[1])
h_qc_transpiled.draw(idle_wires=False)
job = backend.run(h_qc_transpiled)
print(f"Your job's id: {job.job_id()}")
result = job.result()
print(f"|+> preparation results: {result.get_counts(0)}")
job.error_message()
from run_openqasm3 import run_openqasm3
job = run_openqasm3(h_qc_transpiled, backend)
|
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 all BasicAer simulators."""
import io
from logging import StreamHandler, getLogger
import sys
from qiskit import BasicAer
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile
from qiskit.compiler import assemble
from qiskit.qobj import QobjHeader
from qiskit.test import QiskitTestCase
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestBasicAerQobj(QiskitTestCase):
"""Tests for all the Terra simulators."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
self.qc1 = QuantumCircuit(qr, cr, name="circuit0")
self.qc1.h(qr[0])
def test_qobj_headers_in_result(self):
"""Test that the qobj headers are passed onto the results."""
custom_qobj_header = {"x": 1, "y": [1, 2, 3], "z": {"a": 4}}
for backend in BasicAer.backends():
with self.subTest(backend=backend):
new_circ = transpile(self.qc1, backend=backend)
qobj = assemble(new_circ, shots=1024)
# Update the Qobj header.
qobj.header = QobjHeader.from_dict(custom_qobj_header)
# Update the Qobj.experiment header.
qobj.experiments[0].header.some_field = "extra info"
result = backend.run(qobj).result()
self.assertEqual(result.header.to_dict(), custom_qobj_header)
self.assertEqual(result.results[0].header.some_field, "extra info")
|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTrainingData.csv"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTestData.csv"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Pick training size number of samples from each distro
training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
import numpy as np
import scipy
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
feature_dim = 4 # dimension of each data point
training_dataset_size = 80
testing_dataset_size = 20
random_seed = 10598
np.random.seed(random_seed)
sample_Total, training_input, test_input, class_labels = Currency(
training_size=training_dataset_size,
test_size=testing_dataset_size,
n=feature_dim, PLOT_DATA=False
)
classification_input = ClassificationInput(training_input, test_input)
params = {
'problem': {'name': 'classification', 'random_seed': random_seed},
'algorithm': {'name': 'VQC'},
'backend': {'provider': 'qiskit.BasicAer', 'name': 'statevector_simulator'},
'optimizer': {'name': 'COBYLA', 'maxiter':200},
'variational_form': {'name': 'RYRZ', 'depth': 3},
'feature_map': {'name': None},
}
params['feature_map']['name'] = 'RawFeatureVector'
result = run_algorithm(params, classification_input)
print("VQC accuracy with RawFeatureVector: ", result['testing_accuracy'])
params['feature_map']['name'] = 'SecondOrderExpansion'
result = run_algorithm(params, classification_input)
print("Test accuracy with SecondOrderExpansion: ", result['testing_accuracy'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
import scqubits as sc
tmon = sc.Transmon(
EJ = 31,
EC = .8,
ng = 0,
ncut = 110
)
evals = tmon.eigenvals()[:5]
omega = evals[1]-evals[0]
osc = sc.Oscillator(
E_osc = omega
)
import numpy as np
from matplotlib import pyplot as plt
xlist = np.linspace(-np.pi,np.pi,100)
mineng = min([tmon.potential(x) for x in xlist])
plt.plot(xlist, [(tmon.potential(x)-mineng)/omega for x in xlist], c = "blue", label = "qubit")
plt.plot(xlist, [(x**2 * 31/2)/omega for x in xlist], c = "red", label = "qumode")
plt.hlines([(n+.5) for n in range(5)], -1, 1, color="red")
plt.hlines((evals-mineng)/omega, -1, 1, color="blue")
plt.xlabel(r"$\varphi$")
plt.ylabel(r"E/$\omega$")
plt.ylim([0,6])
plt.legend()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator, QMolecule
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit_chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit_chemistry import QMolecule as qm
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import VQE, ExactEigensolver
from qiskit import Aer
from scipy import linalg as la
import numpy as np
import yaml as yml
from yaml import SafeLoader as Loader
import os
import Load_Hamiltonians as lh
#################### WALK ROOT DIR ############################
root_dir = 'IntegralData/vqe-data-master/Li2_cc-pVTZ/4_ORBITALS'
data_file_list = []
data_file_list_oe = []
for dirName, subdirList, fileList in os.walk(root_dir):
print('Found directory: %s' % dirName)
for fname in sorted(fileList):
if fname.endswith('.yaml'):
data_file_list.append(fname)
#I added an x in front of the 10s for distance to force the sorting, else it sees 13 as 1
#If any distance is in the 100s (unlikely) then add a 'y' in front of dist in file name
###############################################################
############# Output Files to Plot stuff ###############
Fout = open('Li2_ExactEnergies_wMP2_4-orbitals_060319.dat',"w")
#Fout = open('Li2_ExactEnergiesG&FE_wMP2_4-orbitals_052919.dat',"w")
###########################################################
#Variables that can be assigned outside of Loop
map_type = str('jordan_wigner')
truncation_threshold = 0.01
################# IBM BACKEND #####################
backend1 = Aer.get_backend('statevector_simulator')
backend2 = Aer.get_backend('qasm_simulator')
###################################################
output_data = []
#Looping over all of the yaml files in a particular directory and saving the energies from VQE and Exact
ind = 0
for key, file in enumerate(data_file_list):
NW_data_file = str(os.path.join(root_dir,file))
print(NW_data_file)
try:
doc = open(NW_data_file, 'r')
data = yml.load(doc, Loader)
finally:
doc.close()
#Import all the data from a yaml file
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Populating the QMolecule class with the data to make calculations easier
qm.num_orbitals = n_spatial_orbitals
qm.num_alpha = n_particles // 2
qm.num_beta = n_particles // 2
qm.core_orbitals = 0
qm.nuclear_repulsion_energy = nuclear_repulsion_energy
qm.hf_energy = data['integral_sets'][0]['scf_energy']['value']
#Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
#Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.trunctate_spatial_integrals(
one_electron_spatial_integrals, two_electron_spatial_integrals, .001)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals, two_electron_spatial_integrals,
n_spatial_orbitals, truncation_threshold)
#For the MP2 Calculation
qm.mo_eri_ints = two_electron_spatial_integrals
#Constructing the fermion operator and qubit operator from integrals data
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
qop = Operator(paulis=qop_paulis.paulis)
################### EXACT RESULT ##################################
exact_eigensolver = ExactEigensolver(qop, k=12)
ret = exact_eigensolver.run()
print('The electronic energy is: {:.12f}'.format(ret['eigvals'][0].real))
print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real + nuclear_repulsion_energy))
exact_energy = ret['eigvals'][0].real + nuclear_repulsion_energy
exact_energy_fe = ret['eigvals'][1].real + nuclear_repulsion_energy
# qop.to_matrix()
# #print(qop)
# eigval, eigvec = np.linalg.eigh(qop.matrix.toarray())
# exact_energy = eigval[0].real + nuclear_repulsion_energy
# exact_energy_fe = eigval[1].real + nuclear_repulsion_energy
# print('{} is the groundstate energy and {} is the first excited state'.format(eigval[0].real,eigval[1].real))
###################################################################
# my_info = [dist, exact_energy,eigval[1].real + nuclear_repulsion_energy, eigval[2].real + nuclear_repulsion_energy, eigval[3].real\
# + nuclear_repulsion_energy, eigval[4].real + nuclear_repulsion_energy, eigval[5].real + nuclear_repulsion_energy, \
# eigval[6].real + nuclear_repulsion_energy, eigval[7].real + nuclear_repulsion_energy, eigval[8].real + nuclear_repulsion_energy, eigval[9].real + nuclear_repulsion_energy, \
# eigval[10].real + nuclear_repulsion_energy, eigval[11].real + nuclear_repulsion_energy]
my_info = [dist, ret['eigvals'][0].real + nuclear_repulsion_energy, exact_energy,ret['eigvals'][1].real + nuclear_repulsion_energy, ret['eigvals'][2].real + nuclear_repulsion_energy, ret['eigvals'][3].real\
+ nuclear_repulsion_energy, ret['eigvals'][4].real + nuclear_repulsion_energy, ret['eigvals'][5].real + nuclear_repulsion_energy, \
ret['eigvals'][6].real + nuclear_repulsion_energy, ret['eigvals'][7].real + nuclear_repulsion_energy, ret['eigvals'][8].real + nuclear_repulsion_energy, ret['eigvals'][9].real + nuclear_repulsion_energy, \
ret['eigvals'][10].real + nuclear_repulsion_energy, ret['eigvals'][11].real + nuclear_repulsion_energy]
output_data.append(my_info)
my_info_to_str = " ".join(str(e) for e in my_info)
Fout.write(my_info_to_str + "\n")
print(output_data)
Fout.close()
# output_data[:,0] = np.sort(output_data[:,0],axis=0)
# print(output_data)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""Univariate Marginal Distribution Algorithm (Estimation-of-Distribution-Algorithm)."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
import numpy as np
from scipy.stats import norm
from qiskit.utils import algorithm_globals
from .optimizer import OptimizerResult, POINT
from .scipy_optimizer import Optimizer, OptimizerSupportLevel
class UMDA(Optimizer):
"""Continuous Univariate Marginal Distribution Algorithm (UMDA).
UMDA [1] is a specific type of Estimation of Distribution Algorithm (EDA) where new individuals
are sampled from univariate normal distributions and are updated in each iteration of the
algorithm by the best individuals found in the previous iteration.
.. seealso::
This original implementation of the UDMA optimizer for Qiskit was inspired by my
(Vicente P. Soloviev) work on the EDAspy Python package [2].
EDAs are stochastic search algorithms and belong to the family of the evolutionary algorithms.
The main difference is that EDAs have a probabilistic model which is updated in each iteration
from the best individuals of previous generations (elite selection). Depending on the complexity
of the probabilistic model, EDAs can be classified in different ways. In this case, UMDA is a
univariate EDA as the embedded probabilistic model is univariate.
UMDA has been compared to some of the already implemented algorithms in Qiskit library to
optimize the parameters of variational algorithms such as QAOA or VQE and competitive results
have been obtained [1]. UMDA seems to provide very good solutions for those circuits in which
the number of layers is not big.
The optimization process can be personalized depending on the paremeters chosen in the
initialization. The main parameter is the population size. The bigger it is, the final result
will be better. However, this increases the complexity of the algorithm and the runtime will
be much heavier. In the work [1] different experiments have been performed where population
size has been set to 20 - 30.
.. note::
The UMDA implementation has more parameters but these have default values for the
initialization for better understanding of the user. For example, ``\alpha`` parameter has
been set to 0.5 and is the percentage of the population which is selected in each iteration
to update the probabilistic model.
Example:
This short example runs UMDA to optimize the parameters of a variational algorithm. Here we
will use the same operator as used in the algorithms introduction, which was originally
computed by Qiskit Nature for an H2 molecule. The minimum energy of the H2 Hamiltonian can
be found quite easily so we are able to set maxiters to a small value.
.. code-block:: python
from qiskit.opflow import X, Z, I
from qiskit import Aer
from qiskit_algorithms.optimizers import UMDA
from qiskit_algorithms import QAOA
from qiskit.utils import QuantumInstance
H2_op = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
p = 2 # Toy example: 2 layers with 2 parameters in each layer: 4 variables
opt = UMDA(maxiter=100, size_gen=20)
backend = Aer.get_backend('statevector_simulator')
vqe = QAOA(opt,
quantum_instance=QuantumInstance(backend=backend),
reps=p)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
If it is desired to modify the percentage of individuals considered to update the
probabilistic model, then this code can be used. Here for example we set the 60% instead
of the 50% predefined.
.. code-block:: python
opt = UMDA(maxiter=100, size_gen=20, alpha = 0.6)
backend = Aer.get_backend('statevector_simulator')
vqe = QAOA(opt,
quantum_instance=QuantumInstance(backend=backend),
reps=p)
result = vqe.compute_minimum_eigenvalue(operator=qubit_op)
References:
[1]: Vicente P. Soloviev, Pedro Larrañaga and Concha Bielza (2022, July). Quantum Parametric
Circuit Optimization with Estimation of Distribution Algorithms. In 2022 The Genetic and
Evolutionary Computation Conference (GECCO). DOI: https://doi.org/10.1145/3520304.3533963
[2]: Vicente P. Soloviev. Python package EDAspy.
https://github.com/VicentePerezSoloviev/EDAspy.
"""
ELITE_FACTOR = 0.4
STD_BOUND = 0.3
def __init__(
self,
maxiter: int = 100,
size_gen: int = 20,
alpha: float = 0.5,
callback: Callable[[int, np.array, float], None] | None = None,
) -> None:
r"""
Args:
maxiter: Maximum number of iterations.
size_gen: Population size of each generation.
alpha: Percentage (0, 1] of the population to be selected as elite selection.
callback: A callback function passed information in each iteration step. The
information is, in this order: the number of function evaluations, the parameters,
the best function value in this iteration.
"""
self.size_gen = size_gen
self.maxiter = maxiter
self.alpha = alpha
self._vector: np.ndarray | None = None
# initialization of generation
self._generation: np.ndarray | None = None
self._dead_iter = int(self._maxiter / 5)
self._truncation_length = int(size_gen * alpha)
super().__init__()
self._best_cost_global: float | None = None
self._best_ind_global: int | None = None
self._evaluations: np.ndarray | None = None
self._n_variables: int | None = None
self.callback = callback
def _initialization(self) -> np.ndarray:
vector = np.zeros((4, self._n_variables))
vector[0, :] = np.pi # mu
vector[1, :] = 0.5 # std
return vector
# build a generation of size SIZE_GEN from prob vector
def _new_generation(self):
"""Build a new generation sampled from the vector of probabilities.
Updates the generation pandas dataframe
"""
gen = algorithm_globals.random.normal(
self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables]
)
self._generation = self._generation[: int(self.ELITE_FACTOR * len(self._generation))]
self._generation = np.vstack((self._generation, gen))
# truncate the generation at alpha percent
def _truncation(self):
"""Selection of the best individuals of the actual generation.
Updates the generation by selecting the best individuals.
"""
best_indices = self._evaluations.argsort()[: self._truncation_length]
self._generation = self._generation[best_indices, :]
self._evaluations = np.take(self._evaluations, best_indices)
# check each individual of the generation
def _check_generation(self, objective_function):
"""Check the cost of each individual in the cost function implemented by the user."""
self._evaluations = np.apply_along_axis(objective_function, 1, self._generation)
# update the probability vector
def _update_vector(self):
"""From the best individuals update the vector of normal distributions in order to the next
generation can sample from it. Update the vector of normal distributions
"""
for i in range(self._n_variables):
self._vector[0, i], self._vector[1, i] = norm.fit(self._generation[:, i])
if self._vector[1, i] < self.STD_BOUND:
self._vector[1, i] = self.STD_BOUND
def minimize(
self,
fun: Callable[[POINT], float],
x0: POINT,
jac: Callable[[POINT], POINT] | None = None,
bounds: list[tuple[float, float]] | None = None,
) -> OptimizerResult:
not_better_count = 0
result = OptimizerResult()
if isinstance(x0, float):
x0 = [x0]
self._n_variables = len(x0)
self._best_cost_global = 999999999999
self._best_ind_global = 9999999
history = []
self._evaluations = np.array(0)
self._vector = self._initialization()
# initialization of generation
self._generation = algorithm_globals.random.normal(
self._vector[0, :], self._vector[1, :], [self._size_gen, self._n_variables]
)
for _ in range(self._maxiter):
self._check_generation(fun)
self._truncation()
self._update_vector()
best_mae_local: float = min(self._evaluations)
history.append(best_mae_local)
best_ind_local = np.where(self._evaluations == best_mae_local)[0][0]
best_ind_local = self._generation[best_ind_local]
# update the best values ever
if best_mae_local < self._best_cost_global:
self._best_cost_global = best_mae_local
self._best_ind_global = best_ind_local
not_better_count = 0
else:
not_better_count += 1
if not_better_count >= self._dead_iter:
break
if self.callback is not None:
self.callback(
len(history) * self._size_gen, self._best_ind_global, self._best_cost_global
)
self._new_generation()
result.x = self._best_ind_global
result.fun = self._best_cost_global
result.nfev = len(history) * self._size_gen
return result
@property
def size_gen(self) -> int:
"""Returns the size of the generations (number of individuals per generation)"""
return self._size_gen
@size_gen.setter
def size_gen(self, value: int):
"""
Sets the size of the generations of the algorithm.
Args:
value: Size of the generations (number of individuals per generation).
Raises:
ValueError: If `value` is lower than 1.
"""
if value <= 0:
raise ValueError("The size of the generation should be greater than 0.")
self._size_gen = value
@property
def maxiter(self) -> int:
"""Returns the maximum number of iterations"""
return self._maxiter
@maxiter.setter
def maxiter(self, value: int):
"""
Sets the maximum number of iterations of the algorithm.
Args:
value: Maximum number of iterations of the algorithm.
Raises:
ValueError: If `value` is lower than 1.
"""
if value <= 0:
raise ValueError("The maximum number of iterations should be greater than 0.")
self._maxiter = value
@property
def alpha(self) -> float:
"""Returns the alpha parameter value (percentage of population selected to update
probabilistic model)"""
return self._alpha
@alpha.setter
def alpha(self, value: float):
"""
Sets the alpha parameter (percentage of individuals selected to update the probabilistic
model)
Args:
value: Percentage (0,1] of generation selected to update the probabilistic model.
Raises:
ValueError: If `value` is lower than 0 or greater than 1.
"""
if (value <= 0) or (value > 1):
raise ValueError(f"alpha must be in the range (0, 1], value given was {value}")
self._alpha = value
@property
def settings(self) -> dict[str, Any]:
return {
"maxiter": self.maxiter,
"alpha": self.alpha,
"size_gen": self.size_gen,
"callback": self.callback,
}
def get_support_level(self):
"""Get the support level dictionary."""
return {
"gradient": OptimizerSupportLevel.ignored,
"bounds": OptimizerSupportLevel.ignored,
"initial_point": OptimizerSupportLevel.required,
}
|
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=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
import os
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
class QUEKOTranspilerBench:
params = ([0, 1, 2, 3], [None, "sabre"])
param_names = ["optimization level", "routing/layout method"]
timeout = 600
# pylint: disable=unused-argument
def setup(self, optimization_level, routing_method):
self.rochester_coupling_map = [
[0, 5],
[0, 1],
[1, 2],
[1, 0],
[2, 3],
[2, 1],
[3, 4],
[3, 2],
[4, 6],
[4, 3],
[5, 9],
[5, 0],
[6, 13],
[6, 4],
[7, 16],
[7, 8],
[8, 9],
[8, 7],
[9, 10],
[9, 8],
[9, 5],
[10, 11],
[10, 9],
[11, 17],
[11, 12],
[11, 10],
[12, 13],
[12, 11],
[13, 14],
[13, 12],
[13, 6],
[14, 15],
[14, 13],
[15, 18],
[15, 14],
[16, 19],
[16, 7],
[17, 23],
[17, 11],
[18, 27],
[18, 15],
[19, 20],
[19, 16],
[20, 21],
[20, 19],
[21, 28],
[21, 22],
[21, 20],
[22, 23],
[22, 21],
[23, 24],
[23, 22],
[23, 17],
[24, 25],
[24, 23],
[25, 29],
[25, 26],
[25, 24],
[26, 27],
[26, 25],
[27, 26],
[27, 18],
[28, 32],
[28, 21],
[29, 36],
[29, 25],
[30, 39],
[30, 31],
[31, 32],
[31, 30],
[32, 33],
[32, 31],
[32, 28],
[33, 34],
[33, 32],
[34, 40],
[34, 35],
[34, 33],
[35, 36],
[35, 34],
[36, 37],
[36, 35],
[36, 29],
[37, 38],
[37, 36],
[38, 41],
[38, 37],
[39, 42],
[39, 30],
[40, 46],
[40, 34],
[41, 50],
[41, 38],
[42, 43],
[42, 39],
[43, 44],
[43, 42],
[44, 51],
[44, 45],
[44, 43],
[45, 46],
[45, 44],
[46, 47],
[46, 45],
[46, 40],
[47, 48],
[47, 46],
[48, 52],
[48, 49],
[48, 47],
[49, 50],
[49, 48],
[50, 49],
[50, 41],
[51, 44],
[52, 48],
]
self.tokyo_coupling_map = [
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[0, 5],
[1, 6],
[1, 7],
[2, 6],
[2, 7],
[3, 8],
[3, 9],
[4, 8],
[4, 9],
[5, 6],
[6, 7],
[7, 8],
[8, 9],
[5, 10],
[5, 11],
[6, 10],
[6, 11],
[7, 12],
[7, 13],
[8, 12],
[8, 13],
[9, 14],
[10, 11],
[11, 12],
[12, 13],
[13, 14],
[10, 15],
[11, 16],
[11, 17],
[12, 16],
[12, 17],
[13, 18],
[13, 19],
[14, 18],
[14, 19],
[15, 16],
[16, 17],
[17, 18],
[18, 19],
]
self.sycamore_coupling_map = [
[0, 6],
[1, 6],
[1, 7],
[2, 7],
[2, 8],
[3, 8],
[3, 9],
[4, 9],
[4, 10],
[5, 10],
[5, 11],
[6, 12],
[6, 13],
[7, 13],
[7, 14],
[8, 14],
[8, 15],
[9, 15],
[9, 16],
[10, 16],
[10, 17],
[11, 17],
[12, 18],
[13, 18],
[13, 19],
[14, 19],
[14, 20],
[15, 20],
[15, 21],
[16, 21],
[16, 22],
[17, 22],
[17, 23],
[18, 24],
[18, 25],
[19, 25],
[19, 26],
[20, 26],
[20, 27],
[21, 27],
[21, 28],
[22, 28],
[22, 29],
[23, 29],
[24, 30],
[25, 30],
[25, 31],
[26, 31],
[26, 32],
[27, 32],
[27, 33],
[28, 33],
[28, 34],
[29, 34],
[29, 35],
[30, 36],
[30, 37],
[31, 37],
[31, 38],
[32, 38],
[32, 39],
[33, 39],
[33, 40],
[34, 40],
[34, 41],
[35, 41],
[36, 42],
[37, 42],
[37, 43],
[38, 43],
[38, 44],
[39, 44],
[39, 45],
[40, 45],
[40, 46],
[41, 46],
[41, 47],
[42, 48],
[42, 49],
[43, 49],
[43, 50],
[44, 50],
[44, 51],
[45, 51],
[45, 52],
[46, 52],
[46, 53],
[47, 53],
]
self.basis_gates = ["id", "rz", "sx", "x", "cx"]
self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm"))
self.bigd = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "20QBT_45CYC_.0D1_.1D2_3.qasm")
)
self.bss = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "53QBT_100CYC_QSE_3.qasm")
)
self.bntf = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "54QBT_25CYC_QSE_3.qasm")
)
def track_depth_bntf_optimal_depth_25(self, optimization_level, routing_method):
return transpile(
self.bntf,
coupling_map=self.sycamore_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_bss_optimal_depth_100(self, optimization_level, routing_method):
return transpile(
self.bss,
coupling_map=self.rochester_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_bigd_optimal_depth_45(self, optimization_level, routing_method):
return transpile(
self.bigd,
coupling_map=self.tokyo_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bntf(self, optimization_level, routing_method):
transpile(
self.bntf,
coupling_map=self.sycamore_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bss(self, optimization_level, routing_method):
transpile(
self.bss,
coupling_map=self.rochester_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_bigd(self, optimization_level, routing_method):
transpile(
self.bigd,
coupling_map=self.tokyo_coupling_map,
basis_gates=self.basis_gates,
routing_method=routing_method,
layout_method=routing_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import dwavebinarycsp
import dimod
import neal
import numpy as np
from dwavebinarycsp.core.constraint import Constraint
from dwave.system import DWaveSampler, EmbeddingComposite
A = np.array([[1,1,1,1,1],
[2,2,2,2,2],
[0,1,2,3,4],
[2,1,4,1,0],
[0,1,0,1,0]])
b = np.array([2, 4, 3, 5, 1])
solution = {'x0':0, 'x1':1,'x2':1,'x3':0,'x4':0 }
no_solution = {'x0':0, 'x1':1,'x2':1,'x3':1,'x4':1 }
m, n = A.shape
vartype = dimod.Vartype.BINARY
csp = dwavebinarycsp.ConstraintSatisfactionProblem(vartype)
x = tuple(['x' + str(j) for j in range(n)])
def make_f(i): # avoid late binding of i in for loop
return lambda *z : (sum(A[i,j]*z[j] for j in range(n)) == b[i])
for v in x:
csp.add_variable(v)
for i in range(m):
constraint = Constraint.from_func(make_f(i),x,vartype)
csp.add_constraint(constraint)
def printAndGetTestResults(sampler, bqm):
sampleset = sampler.sample(bqm)
print("Sampling by ", sampler)
for sample, energy in sampleset.data(['sample', 'energy']):
isValid = csp.check(sample)
print(sample, isValid, energy)
if not isValid : return sampleset
bqm = dwavebinarycsp.stitch(csp)
samplers = {"BruteForce" : dimod.ExactSolver() , "Neal" : neal.SimulatedAnnealingSampler()}
samplesets = {s: printAndGetTestResults(samplers[s],bqm) for s in samplers.keys()}
sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm,num_reads = 100)
sampleset.to_pandas_dataframe()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Visualization function for a pass manager. Passes are grouped based on their
flow controller, and coloured based on the type of pass.
"""
import os
import inspect
import tempfile
from qiskit.utils import optionals as _optionals
from qiskit.transpiler.basepasses import AnalysisPass, TransformationPass
from .exceptions import VisualizationError
DEFAULT_STYLE = {AnalysisPass: "red", TransformationPass: "blue"}
@_optionals.HAS_GRAPHVIZ.require_in_call
@_optionals.HAS_PYDOT.require_in_call
def pass_manager_drawer(pass_manager, filename=None, style=None, raw=False):
"""
Draws the pass manager.
This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs
`Graphviz <https://www.graphviz.org/>`__ to be installed.
Args:
pass_manager (PassManager): the pass manager to be drawn
filename (str): file path to save image to
style (dict or OrderedDict): keys are the pass classes and the values are
the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered
dict can be used to ensure a priority coloring when pass falls into multiple
categories. Any values not included in the provided dict will be filled in from
the default dict
raw (Bool) : True if you want to save the raw Dot output not an image. The
default is False.
Returns:
PIL.Image or None: an in-memory representation of the pass manager. Or None if
no image was generated or PIL is not installed.
Raises:
MissingOptionalLibraryError: when nxpd or pydot not installed.
VisualizationError: If raw=True and filename=None.
Example:
.. code-block::
%matplotlib inline
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
from qiskit.visualization import pass_manager_drawer
from qiskit.transpiler.passes import Unroller
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw()
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
pass_manager_drawer(pm, "passmanager.jpg")
"""
import pydot
passes = pass_manager.passes()
if not style:
style = DEFAULT_STYLE
# create the overall graph
graph = pydot.Dot()
# identifiers for nodes need to be unique, so assign an id
# can't just use python's id in case the exact same pass was
# appended more than once
component_id = 0
prev_node = None
for index, controller_group in enumerate(passes):
subgraph, component_id, prev_node = draw_subgraph(
controller_group, component_id, style, prev_node, index
)
graph.add_subgraph(subgraph)
output = make_output(graph, raw, filename)
return output
def _get_node_color(pss, style):
# look in the user provided dict first
for typ, color in style.items():
if isinstance(pss, typ):
return color
# failing that, look in the default
for typ, color in DEFAULT_STYLE.items():
if isinstance(pss, typ):
return color
return "black"
@_optionals.HAS_GRAPHVIZ.require_in_call
@_optionals.HAS_PYDOT.require_in_call
def staged_pass_manager_drawer(pass_manager, filename=None, style=None, raw=False):
"""
Draws the staged pass manager.
This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs
`Graphviz <https://www.graphviz.org/>`__ to be installed.
Args:
pass_manager (StagedPassManager): the staged pass manager to be drawn
filename (str): file path to save image to
style (dict or OrderedDict): keys are the pass classes and the values are
the colors to make them. An example can be seen in the DEFAULT_STYLE. An ordered
dict can be used to ensure a priority coloring when pass falls into multiple
categories. Any values not included in the provided dict will be filled in from
the default dict
raw (Bool) : True if you want to save the raw Dot output not an image. The
default is False.
Returns:
PIL.Image or None: an in-memory representation of the pass manager. Or None if
no image was generated or PIL is not installed.
Raises:
MissingOptionalLibraryError: when nxpd or pydot not installed.
VisualizationError: If raw=True and filename=None.
Example:
.. code-block::
%matplotlib inline
from qiskit.providers.fake_provider import FakeLagosV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
pass_manager = generate_preset_pass_manager(3, FakeLagosV2())
pass_manager.draw()
"""
import pydot
# only include stages that have passes
stages = list(filter(lambda s: s is not None, pass_manager.expanded_stages))
if not style:
style = DEFAULT_STYLE
# create the overall graph
graph = pydot.Dot()
# identifiers for nodes need to be unique, so assign an id
# can't just use python's id in case the exact same pass was
# appended more than once
component_id = 0
# keep a running count of indexes across stages
idx = 0
prev_node = None
for st in stages:
stage = getattr(pass_manager, st)
if stage is not None:
passes = stage.passes()
stagegraph = pydot.Cluster(str(st), label=str(st), fontname="helvetica", labeljust="l")
for controller_group in passes:
subgraph, component_id, prev_node = draw_subgraph(
controller_group, component_id, style, prev_node, idx
)
stagegraph.add_subgraph(subgraph)
idx += 1
graph.add_subgraph(stagegraph)
output = make_output(graph, raw, filename)
return output
def draw_subgraph(controller_group, component_id, style, prev_node, idx):
"""Draw subgraph."""
import pydot
# label is the name of the flow controller parameter
label = "[{}] {}".format(idx, ", ".join(controller_group["flow_controllers"]))
# create the subgraph for this controller
subgraph = pydot.Cluster(str(component_id), label=label, fontname="helvetica", labeljust="l")
component_id += 1
for pass_ in controller_group["passes"]:
# label is the name of the pass
node = pydot.Node(
str(component_id),
label=str(type(pass_).__name__),
color=_get_node_color(pass_, style),
shape="rectangle",
fontname="helvetica",
)
subgraph.add_node(node)
component_id += 1
# the arguments that were provided to the pass when it was created
arg_spec = inspect.getfullargspec(pass_.__init__)
# 0 is the args, 1: to remove the self arg
args = arg_spec[0][1:]
num_optional = len(arg_spec[3]) if arg_spec[3] else 0
# add in the inputs to the pass
for arg_index, arg in enumerate(args):
nd_style = "solid"
# any optional args are dashed
# the num of optional counts from the end towards the start of the list
if arg_index >= (len(args) - num_optional):
nd_style = "dashed"
input_node = pydot.Node(
component_id,
label=arg,
color="black",
shape="ellipse",
fontsize=10,
style=nd_style,
fontname="helvetica",
)
subgraph.add_node(input_node)
component_id += 1
subgraph.add_edge(pydot.Edge(input_node, node))
# if there is a previous node, add an edge between them
if prev_node:
subgraph.add_edge(pydot.Edge(prev_node, node))
prev_node = node
return subgraph, component_id, prev_node
def make_output(graph, raw, filename):
"""Produce output for pass_manager."""
if raw:
if filename:
graph.write(filename, format="raw")
return None
else:
raise VisualizationError("if format=raw, then a filename is required.")
if not _optionals.HAS_PIL and filename:
# pylint says this isn't a method - it is
graph.write_png(filename)
return None
_optionals.HAS_PIL.require_now("pass manager drawer")
with tempfile.TemporaryDirectory() as tmpdirname:
from PIL import Image
tmppath = os.path.join(tmpdirname, "pass_manager.png")
# pylint says this isn't a method - it is
graph.write_png(tmppath)
image = Image.open(tmppath)
os.remove(tmppath)
if filename:
image.save(filename, "PNG")
return image
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""The n-local circuit class."""
from __future__ import annotations
import typing
from collections.abc import Callable, Mapping, Sequence
from itertools import combinations
import numpy
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit import Instruction, Parameter, ParameterVector, ParameterExpression
from qiskit.exceptions import QiskitError
from ..blueprintcircuit import BlueprintCircuit
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
class NLocal(BlueprintCircuit):
"""The n-local circuit class.
The structure of the n-local circuit are alternating rotation and entanglement layers.
In both layers, parameterized circuit-blocks act on the circuit in a defined way.
In the rotation layer, the blocks are applied stacked on top of each other, while in the
entanglement layer according to the ``entanglement`` strategy.
The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the
circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is
appended.
For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using
``'linear'`` entanglement yields the following circuit.
.. parsed-literal::
┌──────┐ ░ ┌──────┐ ░ ┌──────┐
┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├
│ Rot │ ░ │ │┌──────┐ ░ │ Rot │
┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├
├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤
┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├
│ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │
┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├
├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤
┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├
│ Rot │ ░ └──────┘│ │ ░ │ Rot │
┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├
└──────┘ ░ └──────┘ ░ └──────┘
| |
+---------------------------------+
repeated reps times
If specified, barriers can be inserted in between every block.
If an initial state object is provided, it is added in front of the NLocal.
"""
def __init__(
self,
num_qubits: int | None = None,
rotation_blocks: QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None = None,
entanglement_blocks: QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None = None,
entanglement: list[int] | list[list[int]] | None = None,
reps: int = 1,
insert_barriers: bool = False,
parameter_prefix: str = "θ",
overwrite_block_parameters: bool | list[list[Parameter]] = True,
skip_final_rotation_layer: bool = False,
skip_unentangled_qubits: bool = False,
initial_state: QuantumCircuit | None = None,
name: str | None = "nlocal",
flatten: bool | None = None,
) -> None:
"""
Args:
num_qubits: The number of qubits of the circuit.
rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
these will be applied one after another (like new sub-layers).
entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
these will be applied one after another. To use different entanglements for
the sub-layers, see :meth:`get_entangler_map`.
entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the
entanglement blocks are applied at the top of the circuit.
reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
no barriers are inserted.
parameter_prefix: The prefix used if default parameters are generated.
overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
If ``False``, the parameters in the blocks are not changed.
skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
are entangled. If ``False``, the rotation gates act on all qubits.
initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial
state prepended to the NLocal circuit.
name: The name of the circuit.
flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
layers of gate objects. By default currently the contents of
the output circuit will be wrapped in nested objects for
cleaner visualization. However, if you're using this circuit
for anything besides visualization its **strongly** recommended
to set this flag to ``True`` to avoid a large performance
overhead for parameter binding.
Raises:
ValueError: If ``reps`` parameter is less than or equal to 0.
TypeError: If ``reps`` parameter is not an int value.
"""
super().__init__(name=name)
self._num_qubits: int | None = None
self._insert_barriers = insert_barriers
self._reps = reps
self._entanglement_blocks: list[QuantumCircuit] = []
self._rotation_blocks: list[QuantumCircuit] = []
self._prepended_blocks: list[QuantumCircuit] = []
self._prepended_entanglement: list[list[list[int]] | str] = []
self._appended_blocks: list[QuantumCircuit] = []
self._appended_entanglement: list[list[list[int]] | str] = []
self._entanglement = None
self._entangler_maps = None
self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector(
name=parameter_prefix
)
self._overwrite_block_parameters = overwrite_block_parameters
self._skip_final_rotation_layer = skip_final_rotation_layer
self._skip_unentangled_qubits = skip_unentangled_qubits
self._initial_state: QuantumCircuit | None = None
self._initial_state_circuit: QuantumCircuit | None = None
self._bounds: list[tuple[float | None, float | None]] | None = None
self._flatten = flatten
if int(reps) != reps:
raise TypeError("The value of reps should be int")
if reps < 0:
raise ValueError("The value of reps should be larger than or equal to 0")
if num_qubits is not None:
self.num_qubits = num_qubits
if entanglement_blocks is not None:
self.entanglement_blocks = entanglement_blocks
if rotation_blocks is not None:
self.rotation_blocks = rotation_blocks
if entanglement is not None:
self.entanglement = entanglement
if initial_state is not None:
self.initial_state = initial_state
@property
def num_qubits(self) -> int:
"""Returns the number of qubits in this circuit.
Returns:
The number of qubits.
"""
return self._num_qubits if self._num_qubits is not None else 0
@num_qubits.setter
def num_qubits(self, num_qubits: int) -> None:
"""Set the number of qubits for the n-local circuit.
Args:
The new number of qubits.
"""
if self._num_qubits != num_qubits:
# invalidate the circuit
self._invalidate()
self._num_qubits = num_qubits
self.qregs = [QuantumRegister(num_qubits, name="q")]
@property
def flatten(self) -> bool:
"""Returns whether the circuit is wrapped in nested gates/instructions or flattened."""
return bool(self._flatten)
@flatten.setter
def flatten(self, flatten: bool) -> None:
self._invalidate()
self._flatten = flatten
def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit:
"""Try to convert ``layer`` to a QuantumCircuit.
Args:
layer: The object to be converted to an NLocal block / Instruction.
Returns:
The layer converted to a circuit.
Raises:
TypeError: If the input cannot be converted to a circuit.
"""
if isinstance(layer, QuantumCircuit):
return layer
if isinstance(layer, Instruction):
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer, list(range(layer.num_qubits)))
return circuit
try:
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer.to_instruction(), list(range(layer.num_qubits)))
return circuit
except AttributeError:
pass
raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.")
@property
def rotation_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the rotation layers.
Returns:
The blocks in the rotation layers.
"""
return self._rotation_blocks
@rotation_blocks.setter
def rotation_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the rotation layers.
Args:
blocks: The new blocks for the rotation layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._rotation_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the entanglement layers.
Returns:
The blocks in the entanglement layers.
"""
return self._entanglement_blocks
@entanglement_blocks.setter
def entanglement_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the entanglement layers.
Args:
blocks: The new blocks for the entanglement layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._entanglement_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement(
self,
) -> str | list[str] | list[list[str]] | list[int] | list[list[int]] | list[
list[list[int]]
] | list[list[list[list[int]]]] | Callable[[int], str] | Callable[[int], list[list[int]]]:
"""Get the entanglement strategy.
Returns:
The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the
format is interpreted.
"""
return self._entanglement
@entanglement.setter
def entanglement(
self,
entanglement: str
| list[str]
| list[list[str]]
| list[int]
| list[list[int]]
| list[list[list[int]]]
| list[list[list[list[int]]]]
| Callable[[int], str]
| Callable[[int], list[list[int]]]
| None,
) -> None:
"""Set the entanglement strategy.
Args:
entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail
on the supported formats.
"""
self._invalidate()
self._entanglement = entanglement
@property
def num_layers(self) -> int:
"""Return the number of layers in the n-local circuit.
Returns:
The number of layers in the circuit.
"""
return 2 * self._reps + int(not self._skip_final_rotation_layer)
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the configuration of the NLocal class is valid.
Args:
raise_on_failure: Whether to raise on failure.
Returns:
True, if the configuration is valid and the circuit can be constructed. Otherwise
an ValueError is raised.
Raises:
ValueError: If the blocks are not set.
ValueError: If the number of repetitions is not set.
ValueError: If the qubit indices are not set.
ValueError: If the number of qubit indices does not match the number of blocks.
ValueError: If an index in the repetitions list exceeds the number of blocks.
ValueError: If the number of repetitions does not match the number of block-wise
parameters.
ValueError: If a specified qubit index is larger than the (manually set) number of
qubits.
"""
valid = True
if self.num_qubits is None:
valid = False
if raise_on_failure:
raise ValueError("No number of qubits specified.")
# check no needed parameters are None
if self.entanglement_blocks is None and self.rotation_blocks is None:
valid = False
if raise_on_failure:
raise ValueError("The blocks are not set.")
return valid
@property
def ordered_parameters(self) -> list[Parameter]:
"""The parameters used in the underlying circuit.
This includes float values and duplicates.
Examples:
>>> # prepare circuit ...
>>> print(nlocal)
┌───────┐┌──────────┐┌──────────┐┌──────────┐
q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├
└───────┘└──────────┘└──────────┘└──────────┘
>>> nlocal.parameters
{Parameter(θ[1]), Parameter(θ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])]
Returns:
The parameters objects used in the circuit.
"""
if isinstance(self._ordered_parameters, ParameterVector):
self._ordered_parameters.resize(self.num_parameters_settable)
return list(self._ordered_parameters)
return self._ordered_parameters
@ordered_parameters.setter
def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None:
"""Set the parameters used in the underlying circuit.
Args:
The parameters to be used in the underlying circuit.
Raises:
ValueError: If the length of ordered parameters does not match the number of
parameters in the circuit and they are not a ``ParameterVector`` (which could
be resized to fit the number of parameters).
"""
if (
not isinstance(parameters, ParameterVector)
and len(parameters) != self.num_parameters_settable
):
raise ValueError(
"The length of ordered parameters must be equal to the number of "
"settable parameters in the circuit ({}), but is {}".format(
self.num_parameters_settable, len(parameters)
)
)
self._ordered_parameters = parameters
self._invalidate()
@property
def insert_barriers(self) -> bool:
"""If barriers are inserted in between the layers or not.
Returns:
``True``, if barriers are inserted in between the layers, ``False`` if not.
"""
return self._insert_barriers
@insert_barriers.setter
def insert_barriers(self, insert_barriers: bool) -> None:
"""Specify whether barriers should be inserted in between the layers or not.
Args:
insert_barriers: If True, barriers are inserted, if False not.
"""
# if insert_barriers changes, we have to invalidate the circuit definition,
# if it is the same as before we can leave the NLocal instance as it is
if insert_barriers is not self._insert_barriers:
self._invalidate()
self._insert_barriers = insert_barriers
def get_unentangled_qubits(self) -> set[int]:
"""Get the indices of unentangled qubits in a set.
Returns:
The unentangled qubits.
"""
entangled_qubits = set()
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
entangled_qubits.update([idx for indices in entangler_map for idx in indices])
unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits
return unentangled_qubits
@property
def num_parameters_settable(self) -> int:
"""The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters,
and therefore is different from ``num_parameters`` which counts the number of unique
:class:`~qiskit.circuit.Parameter` objects currently in the circuit.
Returns:
The number of parameters originally available in the circuit.
Note:
This quantity does not require the circuit to be built yet.
"""
num = 0
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
num += len(entangler_map) * len(get_parameters(block))
if self._skip_unentangled_qubits:
unentangled_qubits = self.get_unentangled_qubits()
num_rot = 0
for block in self.rotation_blocks:
block_indices = [
list(range(j * block.num_qubits, (j + 1) * block.num_qubits))
for j in range(self.num_qubits // block.num_qubits)
]
if self._skip_unentangled_qubits:
block_indices = [
indices
for indices in block_indices
if set(indices).isdisjoint(unentangled_qubits)
]
num_rot += len(block_indices) * len(get_parameters(block))
num += num_rot * (self._reps + int(not self._skip_final_rotation_layer))
return num
@property
def reps(self) -> int:
"""The number of times rotation and entanglement block are repeated.
Returns:
The number of repetitions.
"""
return self._reps
@reps.setter
def reps(self, repetitions: int) -> None:
"""Set the repetitions.
If the repetitions are `0`, only one rotation layer with no entanglement
layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``).
Args:
repetitions: The new repetitions.
Raises:
ValueError: If reps setter has parameter repetitions < 0.
"""
if repetitions < 0:
raise ValueError("The repetitions should be larger than or equal to 0")
if repetitions != self._reps:
self._invalidate()
self._reps = repetitions
def print_settings(self) -> str:
"""Returns information about the setting.
Returns:
The class name and the attributes/parameters of the instance as ``str``.
"""
ret = f"NLocal: {self.__class__.__name__}\n"
params = ""
for key, value in self.__dict__.items():
if key[0] == "_":
params += f"-- {key[1:]}: {value}\n"
ret += f"{params}"
return ret
@property
def preferred_init_points(self) -> list[float] | None:
"""The initial points for the parameters. Can be stored as initial guess in optimization.
Returns:
The initial values for the parameters, or None, if none have been set.
"""
return None
# pylint: disable=too-many-return-statements
def get_entangler_map(
self, rep_num: int, block_num: int, num_block_qubits: int
) -> Sequence[Sequence[int]]:
"""Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``.
The entangler map for the current block is derived from the value of ``self.entanglement``.
Below the different cases are listed, where ``i`` and ``j`` denote the repetition number
and the block number, respectively, and ``n`` the number of qubits in the block.
=================================== ========================================================
entanglement type entangler map
=================================== ========================================================
``None`` ``[[0, ..., n - 1]]``
``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits
``List[int]`` [``entanglement``]
``List[List[int]]`` ``entanglement``
``List[List[List[int]]]`` ``entanglement[i]``
``List[List[List[List[int]]]]`` ``entanglement[i][j]``
``List[str]`` the connectivity specified in ``entanglement[i]``
``List[List[str]]`` the connectivity specified in ``entanglement[i][j]``
``Callable[int, str]`` same as ``List[str]``
``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]``
=================================== ========================================================
Note that all indices are to be taken modulo the length of the array they act on, i.e.
no out-of-bounds index error will be raised but we re-iterate from the beginning of the
list.
Args:
rep_num: The current repetition we are in.
block_num: The block number within the entanglement layers.
num_block_qubits: The number of qubits in the block.
Returns:
The entangler map for the current block in the current repetition.
Raises:
ValueError: If the value of ``entanglement`` could not be cast to a corresponding
entangler map.
"""
i, j, n = rep_num, block_num, num_block_qubits
entanglement = self._entanglement
# entanglement is None
if entanglement is None:
return [list(range(n))]
# entanglement is callable
if callable(entanglement):
entanglement = entanglement(i)
# entanglement is str
if isinstance(entanglement, str):
return get_entangler_map(n, self.num_qubits, entanglement, offset=i)
# check if entanglement is list of something
if not isinstance(entanglement, (tuple, list)):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_i = len(entanglement)
# entanglement is List[str]
if all(isinstance(en, str) for en in entanglement):
return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i)
# entanglement is List[int]
if all(isinstance(en, (int, numpy.integer)) for en in entanglement):
return [[int(en) for en in entanglement]]
# check if entanglement is List[List]
if not all(isinstance(en, (tuple, list)) for en in entanglement):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_j = len(entanglement[i % num_i])
# entanglement is List[List[str]]
if all(isinstance(e2, str) for en in entanglement for e2 in en):
return get_entangler_map(
n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i
)
# entanglement is List[List[int]]
if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en):
for ind, en in enumerate(entanglement):
entanglement[ind] = tuple(map(int, en))
return entanglement
# check if entanglement is List[List[List]]
if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[int]]]
if all(
isinstance(e3, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
):
for en in entanglement:
for ind, e2 in enumerate(en):
en[ind] = tuple(map(int, e2))
return entanglement[i % num_i]
# check if entanglement is List[List[List[List]]]
if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[List[int]]]]
if all(
isinstance(e4, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
for e4 in e3
):
for en in entanglement:
for e2 in en:
for ind, e3 in enumerate(e2):
e2[ind] = tuple(map(int, e3))
return entanglement[i % num_i][j % num_j]
raise ValueError(f"Invalid value of entanglement: {entanglement}")
@property
def initial_state(self) -> QuantumCircuit:
"""Return the initial state that is added in front of the n-local circuit.
Returns:
The initial state.
"""
return self._initial_state
@initial_state.setter
def initial_state(self, initial_state: QuantumCircuit) -> None:
"""Set the initial state.
Args:
initial_state: The new initial state.
Raises:
ValueError: If the number of qubits has been set before and the initial state
does not match the number of qubits.
"""
self._initial_state = initial_state
self._invalidate()
@property
def parameter_bounds(self) -> list[tuple[float, float]] | None:
"""The parameter bounds for the unbound parameters in the circuit.
Returns:
A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded
parameter in the corresponding direction. If ``None`` is returned, problem is fully
unbounded.
"""
if not self._is_built:
self._build()
return self._bounds
@parameter_bounds.setter
def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None:
"""Set the parameter bounds.
Args:
bounds: The new parameter bounds.
"""
self._bounds = bounds
def add_layer(
self,
other: QuantumCircuit | qiskit.circuit.Instruction,
entanglement: list[int] | str | list[list[int]] | None = None,
front: bool = False,
) -> "NLocal":
"""Append another layer to the NLocal.
Args:
other: The layer to compose, can be another NLocal, an Instruction or Gate,
or a QuantumCircuit.
entanglement: The entanglement or qubit indices.
front: If True, ``other`` is appended to the front, else to the back.
Returns:
self, such that chained composes are possible.
Raises:
TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a
`to_instruction` method.
"""
block = self._convert_to_block(other)
if entanglement is None:
entanglement = [list(range(block.num_qubits))]
elif isinstance(entanglement, list) and not isinstance(entanglement[0], list):
entanglement = [entanglement]
if front:
self._prepended_blocks += [block]
self._prepended_entanglement += [entanglement]
else:
self._appended_blocks += [block]
self._appended_entanglement += [entanglement]
if isinstance(entanglement, list):
num_qubits = 1 + max(max(indices) for indices in entanglement)
if num_qubits > self.num_qubits:
self._invalidate() # rebuild circuit
self.num_qubits = num_qubits
# modify the circuit accordingly
if front is False and self._is_built:
if self._insert_barriers and len(self.data) > 0:
self.barrier()
if isinstance(entanglement, str):
entangler_map: Sequence[Sequence[int]] = get_entangler_map(
block.num_qubits, self.num_qubits, entanglement
)
else:
entangler_map = entanglement
layer = QuantumCircuit(self.num_qubits)
for i in entangler_map:
params = self.ordered_parameters[-len(get_parameters(block)) :]
parameterized_block = self._parameterize_block(block, params=params)
layer.compose(parameterized_block, i, inplace=True)
self.compose(layer, inplace=True)
else:
# cannot prepend a block currently, just rebuild
self._invalidate()
return self
def assign_parameters(
self,
parameters: Mapping[Parameter, ParameterExpression | float]
| Sequence[ParameterExpression | float],
inplace: bool = False,
**kwargs,
) -> QuantumCircuit | None:
"""Assign parameters to the n-local circuit.
This method also supports passing a list instead of a dictionary. If a list
is passed, the list must have the same length as the number of unbound parameters in
the circuit. The parameters are assigned in the order of the parameters in
:meth:`ordered_parameters`.
Returns:
A copy of the NLocal circuit with the specified parameters.
Raises:
AttributeError: If the parameters are given as list and do not match the number
of parameters.
"""
if parameters is None or len(parameters) == 0:
return self
if not self._is_built:
self._build()
return super().assign_parameters(parameters, inplace=inplace, **kwargs)
def _parameterize_block(
self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None
):
"""Convert ``block`` to a circuit of correct width and parameterized using the iterator."""
if self._overwrite_block_parameters:
# check if special parameters should be used
# pylint: disable=assignment-from-none
if params is None:
params = self._parameter_generator(rep_num, block_num, indices)
if params is None:
params = [next(param_iter) for _ in range(len(get_parameters(block)))]
update = dict(zip(block.parameters, params))
return block.assign_parameters(update)
return block.copy()
def _build_rotation_layer(self, circuit, param_iter, i):
"""Build a rotation layer."""
# if the unentangled qubits are skipped, compute the set of qubits that are not entangled
if self._skip_unentangled_qubits:
unentangled_qubits = self.get_unentangled_qubits()
# iterate over all rotation blocks
for j, block in enumerate(self.rotation_blocks):
# create a new layer
layer = QuantumCircuit(*self.qregs)
# we apply the rotation gates stacked on top of each other, i.e.
# if we have 4 qubits and a rotation block of width 2, we apply two instances
block_indices = [
list(range(k * block.num_qubits, (k + 1) * block.num_qubits))
for k in range(self.num_qubits // block.num_qubits)
]
# if unentangled qubits should not be acted on, remove all operations that
# touch an unentangled qubit
if self._skip_unentangled_qubits:
block_indices = [
indices
for indices in block_indices
if set(indices).isdisjoint(unentangled_qubits)
]
# apply the operations in the layer
for indices in block_indices:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
layer.compose(parameterized_block, indices, inplace=True)
# add the layer to the circuit
circuit.compose(layer, inplace=True)
def _build_entanglement_layer(self, circuit, param_iter, i):
"""Build an entanglement layer."""
# iterate over all entanglement blocks
for j, block in enumerate(self.entanglement_blocks):
# create a new layer and get the entangler map for this block
layer = QuantumCircuit(*self.qregs)
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
# apply the operations in the layer
for indices in entangler_map:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
layer.compose(parameterized_block, indices, inplace=True)
# add the layer to the circuit
circuit.compose(layer, inplace=True)
def _build_additional_layers(self, circuit, which):
if which == "appended":
blocks = self._appended_blocks
entanglements = self._appended_entanglement
elif which == "prepended":
blocks = reversed(self._prepended_blocks)
entanglements = reversed(self._prepended_entanglement)
else:
raise ValueError("`which` must be either `appended` or `prepended`.")
for block, ent in zip(blocks, entanglements):
layer = QuantumCircuit(*self.qregs)
if isinstance(ent, str):
ent = get_entangler_map(block.num_qubits, self.num_qubits, ent)
for indices in ent:
layer.compose(block, indices, inplace=True)
circuit.compose(layer, inplace=True)
def _build(self) -> None:
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
if self.num_qubits == 0:
return
if not self._flatten:
circuit = QuantumCircuit(*self.qregs, name=self.name)
else:
circuit = self
# use the initial state as starting circuit, if it is set
if self.initial_state:
circuit.compose(self.initial_state.copy(), inplace=True)
param_iter = iter(self.ordered_parameters)
# build the prepended layers
self._build_additional_layers(circuit, "prepended")
# main loop to build the entanglement and rotation layers
for i in range(self.reps):
# insert barrier if specified and there is a preceding layer
if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0):
circuit.barrier()
# build the rotation layer
self._build_rotation_layer(circuit, param_iter, i)
# barrier in between rotation and entanglement layer
if self._insert_barriers and len(self._rotation_blocks) > 0:
circuit.barrier()
# build the entanglement layer
self._build_entanglement_layer(circuit, param_iter, i)
# add the final rotation layer
if not self._skip_final_rotation_layer:
if self.insert_barriers and self.reps > 0:
circuit.barrier()
self._build_rotation_layer(circuit, param_iter, self.reps)
# add the appended layers
self._build_additional_layers(circuit, "appended")
# cast global phase to float if it has no free parameters
if isinstance(circuit.global_phase, ParameterExpression):
try:
circuit.global_phase = float(circuit.global_phase)
except TypeError:
# expression contains free parameters
pass
if not self._flatten:
try:
block = circuit.to_gate()
except QiskitError:
block = circuit.to_instruction()
self.append(block, self.qubits)
# pylint: disable=unused-argument
def _parameter_generator(self, rep: int, block: int, indices: list[int]) -> Parameter | None:
"""If certain blocks should use certain parameters this method can be overridden."""
return None
def get_parameters(block: QuantumCircuit | Instruction) -> list[Parameter]:
"""Return the list of Parameters objects inside a circuit or instruction.
This is required since, in a standard gate the parameters are not necessarily Parameter
objects (e.g. U3Gate(0.1, 0.2, 0.3).params == [0.1, 0.2, 0.3]) and instructions and
circuits do not have the same interface for parameters.
"""
if isinstance(block, QuantumCircuit):
return list(block.parameters)
else:
return [p for p in block.params if isinstance(p, ParameterExpression)]
def get_entangler_map(
num_block_qubits: int, num_circuit_qubits: int, entanglement: str, offset: int = 0
) -> Sequence[tuple[int, ...]]:
"""Get an entangler map for an arbitrary number of qubits.
Args:
num_block_qubits: The number of qubits of the entangling block.
num_circuit_qubits: The number of qubits of the circuit.
entanglement: The entanglement strategy.
offset: The block offset, can be used if the entanglements differ per block.
See mode ``sca`` for instance.
Returns:
The entangler map using mode ``entanglement`` to scatter a block of ``num_block_qubits``
qubits on ``num_circuit_qubits`` qubits.
Raises:
ValueError: If the entanglement mode ist not supported.
"""
n, m = num_circuit_qubits, num_block_qubits
if m > n:
raise ValueError(
"The number of block qubits must be smaller or equal to the number of "
"qubits in the circuit."
)
if entanglement == "pairwise" and num_block_qubits > 2:
raise ValueError("Pairwise entanglement is not defined for blocks with more than 2 qubits.")
if entanglement == "full":
return list(combinations(list(range(n)), m))
elif entanglement == "reverse_linear":
# reverse linear connectivity. In the case of m=2 and the entanglement_block='cx'
# then it's equivalent to 'full' entanglement
reverse = [tuple(range(n - i - m, n - i)) for i in range(n - m + 1)]
return reverse
elif entanglement in ["linear", "circular", "sca", "pairwise"]:
linear = [tuple(range(i, i + m)) for i in range(n - m + 1)]
# if the number of block qubits is 1, we don't have to add the 'circular' part
if entanglement == "linear" or m == 1:
return linear
if entanglement == "pairwise":
return linear[::2] + linear[1::2]
# circular equals linear plus top-bottom entanglement (if there's space for it)
if n > m:
circular = [tuple(range(n - m + 1, n)) + (0,)] + linear
else:
circular = linear
if entanglement == "circular":
return circular
# sca is circular plus shift and reverse
shifted = circular[-offset:] + circular[:-offset]
if offset % 2 == 1: # if odd, reverse the qubit indices
sca = [ind[::-1] for ind in shifted]
else:
sca = shifted
return sca
else:
raise ValueError(f"Unsupported entanglement type: {entanglement}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
1 + 1
a = 1
b = 0.5
a + b
an_integer = 42 # Just an integer
a_float = 0.1 # A non-integer number, up to a fixed precision
a_boolean = True # A value that can be True or False
a_string = '''just enclose text between two 's, or two "s, or do what we did for this string''' # Text
none_of_the_above = None # The absence of any actual value or variable type
a_list = [0,1,2,3]
a_list = [ 42, 0.5, True, [0,1], None, 'Banana' ]
a_list[0]
a_tuple = ( 42, 0.5, True, [0,1], None, 'Banana' )
a_tuple[0]
a_list[5] = 'apple'
print(a_list)
a_tuple[5] = 'apple'
a_list.append( 3.14 )
print(a_list)
a_dict = { 1:'This is the value, for the key 1', 'This is the key for a value 1':1, False:':)', (0,1):256 }
a_dict['This is the key for a value 1']
a_dict['new key'] = 'new_value'
for j in range(5):
print(j)
for j in a_list:
print(j)
for key in a_dict:
value = a_dict[key]
print('key =',key)
print('value =',value)
print()
if 'strawberry' in a_list:
print('We have a strawberry!')
elif a_list[5]=='apple':
print('We have an apple!')
else:
print('Not much fruit here!')
import numpy
numpy.sin( numpy.pi/2 )
import numpy as np
np.sin( np.pi/2 )
from numpy import *
sin( pi/2 )
def do_some_maths ( Input1, Input2 ):
the_answer = Input1 + Input2
return the_answer
x = do_some_maths(1,72)
print(x)
def add_sausages ( input_list ):
if 'sausages' not in input_list:
input_list.append('sausages')
print('List before the function')
print(a_list)
add_sausages(a_list) # function called without an output
print('\nList after the function')
print(a_list)
import random
for j in range(5):
print('* Results from sample',j+1)
print('\n Random number from 0 to 1:', random.random() )
print("\n Random choice from our list:", random.choice( a_list ) )
print('\n')
|
https://github.com/OscarCharlieST/QISKIT_lab
|
OscarCharlieST
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0],cr[0])
circuit_drawer(circuit)
from qiskit import Aer
backend = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend,shots=1024)
result=job.result()
result.get_counts(circuit)
expectation =(result.get_counts(circuit)['0']-result.get_counts(circuit)['1'])/(result.get_counts(circuit)['0']
+result.get_counts(circuit)['1'])
print(expectation)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Import requisite modules
import math
import datetime
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit_aer.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# The data providers of stock-market data
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_finance.applications.optimization import PortfolioDiversification
# Generate a pairwise time-series similarity matrix
seed = 123
stocks = ["TICKER1", "TICKER2"]
n = len(stocks)
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
rho = data.get_similarity_matrix()
q = 1 # q less or equal than n
class ClassicalOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n # number of inner variables
self.q = q # number of required selection
def compute_allowed_combinations(self):
f = math.factorial
return int(f(self.n) / f(self.q) / f(self.n - self.q))
def cplex_solution(self):
# refactoring
rho = self.rho
n = self.n
q = self.q
my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)]
my_ub = [1 for x in range(0, n**2 + n)]
my_lb = [0 for x in range(0, n**2 + n)]
my_ctype = "".join(["I" for x in range(0, n**2 + n)])
my_rhs = (
[q]
+ [1 for x in range(0, n)]
+ [0 for x in range(0, n)]
+ [0.1 for x in range(0, n**2)]
)
my_sense = (
"".join(["E" for x in range(0, 1 + n)])
+ "".join(["E" for x in range(0, n)])
+ "".join(["L" for x in range(0, n**2)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
col = [x for x in range(n**2, n**2 + n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [ii * n + ii, n**2 + ii]
coef = [1, -1]
rows.append([col, coef])
for ii in range(0, n):
for jj in range(0, n):
col = [ii * n + jj, n**2 + jj]
coef = [1, -1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(rho, n, q)
# Compute the number of feasible solutions:
print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations()))
# Compute the total number of possible combinations (feasible + unfeasible)
print("Total number of combinations= " + str(2 ** (n * (n + 1))))
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r")
plt.grid()
for ii in range(n**2, n**2 + n):
if x[ii] > 0:
plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20)
for ii in range(0, n**2):
if x[ii] > 0:
iy = ii // n
ix = ii % n
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2")
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
from qiskit.utils import algorithm_globals
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q)
self.qp = self.pdf.to_quadratic_program()
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(self.qp)
return self.decode_result(result)
def vqe_solution(self):
algorithm_globals.random_seed = 100
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(self.qp)
return self.decode_result(result)
def qaoa_solution(self):
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(self.qp)
return self.decode_result(result)
def decode_result(self, result, offset=0):
quantum_solution = 1 - (result.x)
ground_level = self.qp.objective.evaluate(result.x)
return quantum_solution, ground_level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(rho, n, q)
# Check if the binary representation is correct. This requires CPLEX
try:
import cplex
# warnings.filterwarnings('ignore')
quantum_solution, quantum_cost = quantum_optimizer.exact_solution()
print(quantum_solution, quantum_cost)
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(classical_solution, classical_cost)
if np.abs(quantum_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the formulation of the Hamiltonian")
except Exception as ex:
print(ex)
ground_state, ground_level = quantum_optimizer.exact_solution()
print(ground_state)
classical_cost = 1.000779571614484 # obtained from the CPLEX solution
try:
if np.abs(ground_level - classical_cost) < 0.01:
print("Ising Hamiltonian in Z basis is correct")
else:
print("Error in the Ising Hamiltonian formulation")
except Exception as ex:
print(ex)
vqe_state, vqe_level = quantum_optimizer.vqe_solution()
print(vqe_state, vqe_level)
try:
if np.linalg.norm(ground_state - vqe_state) < 0.01:
print("SamplingVQE produces the same solution as the exact eigensolver.")
else:
print(
"SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected."
)
except Exception as ex:
print(ex)
xc, yc = data.get_coordinates()
visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical")
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/sebasmos/QuantumVE
|
sebasmos
|
API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3"
import qiskit as q
from qiskit import IBMQ,schedule
import numpy as np
import qiskit.pulse as pulse
from qiskit.circuit import Parameter
%matplotlib inline
import sys
sys.path.insert(0, '..') # Add qiskit_runtime directory to the path
IBMQ.save_account(API_KEY)
# Details in: https://qiskit.org/documentation/install.html
IBMQ.save_account(API_KEY, overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider("ibm-q")
for backend in provider.backends():
try:
qubit_count = len(backend.properties().quibits)
except:
qubit_count = "simulated"
print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits")
from qiskit.tools.monitor import job_monitor
backend = provider.get_backend("ibmq_lima")
# Checking for backend support
# https://github.com/delapuente/qiskit-runtime/#test-server
from qiskit import IBMQ
provider = IBMQ.load_account()
print(f"Do I have access to Qiskit Runtime? {provider.has_service('runtime')}")
backend = provider.backend.ibmq_lima
support_runtime = 'runtime' in backend.configuration().input_allowed
print(f"Does {backend.name()} support Qiskit Runtime? {support_runtime}")
# Get a list of all backends that support runtime.
runtime_backends = provider.backends(input_allowed='runtime')
print(f"Backends that support Qiskit Runtime: {runtime_backends}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
((10+9.8+9.5)/3+10)/2
(9.77+10)/2
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Functions to convert between Mitiq's internal circuit representation and
Qiskit's circuit representation.
"""
import re
from typing import Any, List, Optional, Set, Tuple
import cirq
import numpy as np
import qiskit
from cirq.contrib.qasm_import import circuit_from_qasm
from cirq.contrib.qasm_import.exception import QasmException
from qiskit import qasm2
from qiskit.transpiler import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler.passes import SetLayout
from mitiq.interface.mitiq_qiskit.transpiler import (
ApplyMitiqLayout,
ClearLayout,
)
from mitiq.utils import _simplify_circuit_exponents
QASMType = str
def _remove_qasm_barriers(qasm: QASMType) -> QASMType:
"""Returns a copy of the input QASM with all barriers removed.
Args:
qasm: QASM to remove barriers from.
Note:
According to the OpenQASM 2.X language specification
(https://arxiv.org/pdf/1707.03429v2.pdf), "Statements are separated by
semicolons. Whitespace is ignored. The language is case sensitive.
Comments begin with a pair of forward slashes and end with a new line."
"""
quoted_re = r"(?:\"[^\"]*?\")"
statement_re = r"((?:[^;{}\"]*?" + quoted_re + r"?)*[;{}])?"
comment_re = r"(\n?//[^\n]*(?:\n|$))?"
statements_comments = re.findall(statement_re + comment_re, qasm)
lines = []
for statement, comment in statements_comments:
if re.match(r"^\s*barrier(?:(?:\s+)|(?:;))", statement) is None:
lines.append(statement + comment)
return "".join(lines)
def _map_bit_index(
bit_index: int, new_register_sizes: List[int]
) -> Tuple[int, int]:
"""Returns the register index and (qu)bit index in this register for the
mapped bit_index.
Args:
bit_index: Index of (qu)bit in the original register.
new_register_sizes: List of sizes of the new registers.
Example:
bit_index = 3, new_register_sizes = [2, 3]
returns (1, 0), meaning the mapped (qu)bit is in the 1st new register
and has index 0 in this register.
Note:
The bit_index is assumed to come from a circuit with 1 or n registers
where n is the maximum bit_index.
"""
max_indices_in_registers = np.cumsum(new_register_sizes) - 1
# Could be faster via bisection.
register_index = None
for i in range(len(max_indices_in_registers)):
if bit_index <= max_indices_in_registers[i]:
register_index = i
break
assert register_index is not None
if register_index == 0:
return register_index, bit_index
return (
register_index,
bit_index - max_indices_in_registers[register_index - 1] - 1,
)
def _add_identity_to_idle(
circuit: qiskit.QuantumCircuit,
) -> Set[qiskit.circuit.Qubit]:
"""Adds identities to idle qubits in the circuit and returns the altered
indices. Used to preserve idle qubits and indices in conversion.
Args:
circuit: Qiskit circuit to have identities added to idle qubits
Returns:
An unordered set of the indices that were altered
Note: An idle qubit is a qubit without any gates (including Qiskit
barriers) acting on it.
"""
all_qubits = set(circuit.qubits)
used_qubits = set()
idle_qubits = set()
# Get used qubits
for op in circuit.data:
_, qubits, _ = op
used_qubits.update(set(qubits))
idle_qubits = all_qubits - used_qubits
# Modify input circuit applying I to idle qubits
for q in idle_qubits:
circuit.id(q)
return idle_qubits
def _remove_identity_from_idle(
circuit: qiskit.QuantumCircuit,
idle_qubits: Set[qiskit.circuit.Qubit],
) -> None:
"""Removes identities from the circuit corresponding to the input
idle qubits.
Used in conjunction with _add_identity_to_idle to preserve idle qubits in
conversion.
Args:
circuit: Qiskit circuit to have identities removed
idle_indices: Set of altered idle qubits.
"""
to_delete_indices: List[int] = []
for index, op in enumerate(circuit._data):
gate, qubits, cbits = op
if gate.name == "id" and set(qubits).intersection(idle_qubits):
to_delete_indices.append(index)
# Traverse data from list end to preserve index
for index in to_delete_indices[::-1]:
del circuit._data[index]
def _measurement_order(
circuit: qiskit.QuantumCircuit,
) -> List[Tuple[Any, ...]]:
"""Returns the left-to-right measurement order in the circuit.
The "measurement order" is a list of tuples (qubit, bit) involved in
measurements ordered as they appear going left-to-right through the circuit
(i.e., iterating through circuit.data). The purpose of this is to be able
to do
>>> for (qubit, bit) in _measurement_order(circuit):
>>> other_circuit.measure(qubit, bit)
which ensures ``other_circuit`` has the same measurement order as
``circuit``, assuming ``other_circuit`` has the same register(s) as
``circuit``.
Args:
circuit: Qiskit circuit to get the measurement order of.
"""
order = []
for gate, qubits, cbits in circuit.data:
if isinstance(gate, qiskit.circuit.Measure):
if len(qubits) != 1 or len(cbits) != 1:
raise ValueError(
f"Only measurements with one qubit and one bit are "
f"supported, but this measurement has {len(qubits)} "
f"qubit(s) and {len(cbits)} bit(s). If you think this "
f"should be supported and is a bug, please open an issue "
f"at https://github.com/unitaryfund/mitiq."
)
order.append((*qubits, *cbits))
return order
def _transform_registers(
circuit: qiskit.QuantumCircuit,
new_qregs: Optional[List[qiskit.QuantumRegister]] = None,
) -> qiskit.QuantumCircuit:
"""Transforms the registers in the circuit to the new registers.
Args:
circuit: Qiskit circuit.
new_qregs: The new quantum registers for the circuit.
Raises:
ValueError:
* If the number of qubits in the new quantum registers is
greater than the number of qubits in the circuit.
"""
if new_qregs is None:
return circuit
qreg_sizes = [qreg.size for qreg in new_qregs]
nqubits_in_circuit = circuit.num_qubits
if len(qreg_sizes) and sum(qreg_sizes) < nqubits_in_circuit:
raise ValueError(
f"The circuit has {nqubits_in_circuit} qubit(s), but the provided "
f"quantum registers have {sum(qreg_sizes)} qubit(s)."
)
circuit_layout = Layout.from_qubit_list(circuit.qubits)
pass_manager = PassManager(
[SetLayout(circuit_layout), ApplyMitiqLayout(new_qregs), ClearLayout()]
)
return pass_manager.run(circuit)
def to_qasm(circuit: cirq.Circuit) -> QASMType:
"""Returns a QASM string representing the input Mitiq circuit.
Args:
circuit: Mitiq circuit to convert to a QASM string.
Returns:
QASMType: QASM string equivalent to the input Mitiq circuit.
"""
# Simplify exponents of gates. For example, H**-1 is simplified to H.
_simplify_circuit_exponents(circuit)
return circuit.to_qasm()
def to_qiskit(circuit: cirq.Circuit) -> qiskit.QuantumCircuit:
"""Returns a Qiskit circuit equivalent to the input Mitiq circuit. Note
that the output circuit registers may not match the input circuit
registers.
Args:
circuit: Mitiq circuit to convert to a Qiskit circuit.
Returns:
Qiskit.QuantumCircuit object equivalent to the input Mitiq circuit.
"""
return qiskit.QuantumCircuit.from_qasm_str(to_qasm(circuit))
def from_qiskit(circuit: qiskit.QuantumCircuit) -> cirq.Circuit:
"""Returns a Mitiq circuit equivalent to the input Qiskit circuit.
Args:
circuit: Qiskit circuit to convert to a Mitiq circuit.
Returns:
Mitiq circuit representation equivalent to the input Qiskit circuit.
"""
try:
mitiq_circuit = from_qasm(qasm2.dumps(circuit))
except QasmException:
# Try to decompose circuit before running
# This is necessary for converting qiskit circuits with
# custom packaged gates, e.g., QFT gates
circuit = circuit.decompose()
mitiq_circuit = from_qasm(qasm2.dumps(circuit))
return mitiq_circuit
def from_qasm(qasm: QASMType) -> cirq.Circuit:
"""Returns a Mitiq circuit equivalent to the input QASM string.
Args:
qasm: QASM string to convert to a Mitiq circuit.
Returns:
Mitiq circuit representation equivalent to the input QASM string.
"""
qasm = _remove_qasm_barriers(qasm)
return circuit_from_qasm(qasm)
|
https://github.com/kuehnste/QiskitTutorial
|
kuehnste
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import *
from qiskit.quantum_info import state_fidelity
# Magic function to render plots in the notebook after the cell executing the plot command
%matplotlib inline
def run_on_qasm_simulator(quantum_circuit, num_shots):
"""Takes a circuit, the number of shots and a backend and returns the counts for running the circuit
on the qasm_simulator backend."""
qasm_simulator = Aer.get_backend('qasm_simulator')
job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots)
result = job.result()
counts = result.get_counts(quantum_circuit)
return counts
# Create a quantum circuit with a single qubit
qc = QuantumCircuit(1)
# Add the Hadamard gate
# Add the final measurement
# Visualize the circuit
qc.draw('mpl')
# Now we run the circuit various number of shots
# Visualize the results in form of a histogram
# Create a quantum circuit with two qubits
# Add the gates creating a Bell state
# Add the final measurement
# Visualize the circuit
# Now we run the circuit various number of shots
# Visualize the results in form of a histogram
# We prepare a similar function for running on the state vector simulator
# This way we can obtain the state vectors and check for orthogonality
def run_on_statevector_simulator(quantum_circuit, decimals=6):
"""Takes a circuit, and runs it on the state vector simulator backend."""
statevector_simulator = Aer.get_backend('statevector_simulator')
job = execute(quantum_circuit, backend=statevector_simulator)
result = job.result()
statevector = result.get_statevector(quantum_circuit, decimals=decimals)
return statevector
# A quantum circuit for two qubits
qc_phi_minus = QuantumCircuit(2)
# Now add the gates
# Visualize the circuit
qc_phi_minus.draw('mpl')
# To obtain the statevector, we run on Aer's state vector simulator. Note, that there is no measurement at the end
# when running on the state vector simulator, as otherwise the state would collapse onto one of the computational
# basis states and we do not get the actual state vector prepared by the circuit
phi_minus_state = run_on_statevector_simulator(qc_phi_minus)
print('|Phi^-> =', phi_minus_state)
#The psi^+ state
qc_psi_plus = QuantumCircuit(2)
# Now add the gates
# Visualize the circuit
qc_psi_plus.draw('mpl')
psi_plus_state = run_on_statevector_simulator(qc_psi_plus)
print('|Psi^+> =', psi_plus_state)
# Let us first prepare the psi^- state
qc_psi_minus = QuantumCircuit(2)
# Now add the gates
# Visualize the circuit
qc_psi_minus.draw('mpl')
psi_minus_state = run_on_statevector_simulator(qc_psi_minus)
print('|Psi^-> =', psi_minus_state)
# The Phi^+ state
qc_phi_plus = QuantumCircuit(2)
qc_phi_plus.h(0)
qc_phi_plus.cnot(0,1)
qc_phi_plus.draw('mpl')
phi_plus_state = run_on_statevector_simulator(qc_phi_plus)
print('|Phi^+> =', phi_plus_state)
# Check all of the six possible combinations
print('|<Phi^+|Phi^->|^2 =', state_fidelity(phi_plus_state, phi_minus_state))
# ...
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Testing legacy instruction alignment pass."""
from qiskit import QuantumCircuit, pulse
from qiskit.test import QiskitTestCase
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import (
AlignMeasures,
ValidatePulseGates,
ALAPSchedule,
TimeUnitConversion,
)
class TestAlignMeasures(QiskitTestCase):
"""A test for measurement alignment pass."""
def setUp(self):
super().setUp()
instruction_durations = InstructionDurations()
instruction_durations.update(
[
("rz", (0,), 0),
("rz", (1,), 0),
("x", (0,), 160),
("x", (1,), 160),
("sx", (0,), 160),
("sx", (1,), 160),
("cx", (0, 1), 800),
("cx", (1, 0), 800),
("measure", None, 1600),
]
)
self.time_conversion_pass = TimeUnitConversion(inst_durations=instruction_durations)
# reproduce old behavior of 0.20.0 before #7655
# currently default write latency is 0
self.scheduling_pass = ALAPSchedule(
durations=instruction_durations,
clbit_write_latency=1600,
conditional_latency=0,
)
self.align_measure_pass = AlignMeasures(alignment=16)
def test_t1_experiment_type(self):
"""Test T1 experiment type circuit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
(aligned)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├
└───┘└────────────────┘└╥┘
c: 1/════════════════════════╩═
0
This type of experiment slightly changes delay duration of interest.
However the quantization error should be less than alignment * dt.
"""
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_hanh_echo_experiment_type(self):
"""Test Hahn echo experiment type circuit.
(input)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└╥┘
c: 1/══════════════════════════════════════════════════════╩═
0
(output)
┌────┐┌────────────────┐┌───┐┌────────────────┐┌────┐┌──────────────┐┌─┐
q_0: ┤ √X ├┤ Delay(100[dt]) ├┤ X ├┤ Delay(100[dt]) ├┤ √X ├┤ Delay(8[dt]) ├┤M├
└────┘└────────────────┘└───┘└────────────────┘└────┘└──────────────┘└╥┘
c: 1/══════════════════════════════════════════════════════════════════════╩═
0
This type of experiment doesn't change duration of interest (two in the middle).
However induces slight delay less than alignment * dt before measurement.
This might induce extra amplitude damping error.
"""
circuit = QuantumCircuit(1, 1)
circuit.sx(0)
circuit.delay(100, 0, unit="dt")
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.sx(0)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 1)
ref_circuit.sx(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(100, 0, unit="dt")
ref_circuit.sx(0)
ref_circuit.delay(8, 0, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_measure(self):
"""Test circuit with mid circuit measurement.
(input)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(120[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
(output)
┌───┐┌────────────────┐┌─┐┌───────────────┐┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(112[dt]) ├┤M├┤ Delay(10[dt]) ├┤ X ├┤ Delay(134[dt]) ├┤M├
└───┘└────────────────┘└╥┘└───────────────┘└───┘└────────────────┘└╥┘
c: 2/════════════════════════╩══════════════════════════════════════════╩═
0 1
Extra delay is always added to the existing delay right before the measurement.
Delay after measurement is unchanged.
"""
circuit = QuantumCircuit(1, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.delay(10, 0, unit="dt")
circuit.x(0)
circuit.delay(120, 0, unit="dt")
circuit.measure(0, 1)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(1, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(10, 0, unit="dt")
ref_circuit.x(0)
ref_circuit.delay(134, 0, unit="dt")
ref_circuit.measure(0, 1)
self.assertEqual(aligned_circuit, ref_circuit)
def test_mid_circuit_multiq_gates(self):
"""Test circuit with mid circuit measurement and multi qubit gates.
(input)
┌───┐┌────────────────┐┌─┐ ┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──■───────■──┤M├
└───┘└────────────────┘└╥┘┌─┴─┐┌─┐┌─┴─┐└╥┘
q_1: ────────────────────────╫─┤ X ├┤M├┤ X ├─╫─
║ └───┘└╥┘└───┘ ║
c: 2/════════════════════════╩═══════╩═══════╩═
0 1 0
(output)
┌───┐ ┌────────────────┐┌─┐ ┌─────────────────┐ ┌─┐»
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├──■──┤ Delay(1600[dt]) ├──■──┤M├»
┌──────┴───┴──────┐└────────────────┘└╥┘┌─┴─┐└───────┬─┬───────┘┌─┴─┐└╥┘»
q_1: ┤ Delay(1872[dt]) ├───────────────────╫─┤ X ├────────┤M├────────┤ X ├─╫─»
└─────────────────┘ ║ └───┘ └╥┘ └───┘ ║ »
c: 2/══════════════════════════════════════╩═══════════════╩═══════════════╩═»
0 1 0 »
«
«q_0: ───────────────────
« ┌─────────────────┐
«q_1: ┤ Delay(1600[dt]) ├
« └─────────────────┘
«c: 2/═══════════════════
«
Delay for the other channel paired by multi-qubit instruction is also scheduled.
Delay (1872dt) = X (160dt) + Delay (100dt + extra 12dt) + Measure (1600dt).
"""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
ref_circuit = QuantumCircuit(2, 2)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.measure(0, 0)
ref_circuit.delay(160 + 112 + 1600, 1, unit="dt")
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 0, unit="dt")
ref_circuit.measure(1, 1)
ref_circuit.cx(0, 1)
ref_circuit.delay(1600, 1, unit="dt")
ref_circuit.measure(0, 0)
self.assertEqual(aligned_circuit, ref_circuit)
def test_alignment_is_not_processed(self):
"""Test avoid pass processing if delay is aligned."""
circuit = QuantumCircuit(2, 2)
circuit.x(0)
circuit.delay(160, 0, unit="dt")
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.measure(1, 1)
circuit.cx(0, 1)
circuit.measure(0, 0)
# pre scheduling is not necessary because alignment is skipped
# this is to minimize breaking changes to existing code.
transpiled = self.align_measure_pass(circuit, property_set={"time_unit": "dt"})
self.assertEqual(transpiled, circuit)
def test_circuit_using_clbit(self):
"""Test a circuit with instructions using a common clbit.
(input)
┌───┐┌────────────────┐┌─┐
q_0: ┤ X ├┤ Delay(100[dt]) ├┤M├──────────────
└───┘└────────────────┘└╥┘ ┌───┐
q_1: ────────────────────────╫────┤ X ├──────
║ └─╥─┘ ┌─┐
q_2: ────────────────────────╫──────╫─────┤M├
║ ┌────╨────┐└╥┘
c: 1/════════════════════════╩═╡ c_0 = T ╞═╩═
0 └─────────┘ 0
(aligned)
┌───┐ ┌────────────────┐┌─┐┌────────────────┐
q_0: ───────┤ X ├───────┤ Delay(112[dt]) ├┤M├┤ Delay(160[dt]) ├───
┌──────┴───┴──────┐└────────────────┘└╥┘└─────┬───┬──────┘
q_1: ┤ Delay(1872[dt]) ├───────────────────╫───────┤ X ├──────────
└┬────────────────┤ ║ └─╥─┘ ┌─┐
q_2: ─┤ Delay(432[dt]) ├───────────────────╫─────────╫─────────┤M├
└────────────────┘ ║ ┌────╨────┐ └╥┘
c: 1/══════════════════════════════════════╩════╡ c_0 = T ╞═════╩═
0 └─────────┘ 0
Looking at the q_0, the total schedule length T becomes
160 (x) + 112 (aligned delay) + 1600 (measure) + 160 (delay) = 2032.
The last delay comes from ALAP scheduling called before the AlignMeasure pass,
which aligns stop times as late as possible, so the start time of x(1).c_if(0)
and the stop time of measure(0, 0) become T - 160.
"""
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.delay(100, 0, unit="dt")
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
timed_circuit = self.time_conversion_pass(circuit)
scheduled_circuit = self.scheduling_pass(timed_circuit, property_set={"time_unit": "dt"})
aligned_circuit = self.align_measure_pass(
scheduled_circuit, property_set={"time_unit": "dt"}
)
self.assertEqual(aligned_circuit.duration, 2032)
ref_circuit = QuantumCircuit(3, 1)
ref_circuit.x(0)
ref_circuit.delay(112, 0, unit="dt")
ref_circuit.delay(1872, 1, unit="dt") # 2032 - 160
ref_circuit.delay(432, 2, unit="dt") # 2032 - 1600
ref_circuit.measure(0, 0)
ref_circuit.x(1).c_if(0, 1)
ref_circuit.delay(160, 0, unit="dt")
ref_circuit.measure(2, 0)
self.assertEqual(aligned_circuit, ref_circuit)
class TestPulseGateValidation(QiskitTestCase):
"""A test for pulse gate validation pass."""
def setUp(self):
super().setUp()
self.pulse_gate_validation_pass = ValidatePulseGates(granularity=16, min_length=64)
def test_invalid_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# this will cause backend error since this doesn't fit with waveform memory chunk.
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_short_pulse_duration_multiple_pulse(self):
"""Kill pass manager if invalid pulse gate is found."""
# this is invalid duration pulse
# however total gate schedule length is 64, which accidentally satisfies the constraints
# this should fail in the validation
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
custom_gate.insert(
32, pulse.Play(pulse.Constant(32, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
with self.assertRaises(TranspilerError):
self.pulse_gate_validation_pass(circuit)
def test_valid_pulse_duration(self):
"""No error raises if valid calibration is provided."""
# this is valid duration pulse
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160, 0.1), pulse.DriveChannel(0)), inplace=True
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.add_calibration("x", qubits=(0,), schedule=custom_gate)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
def test_no_calibration(self):
"""No error raises if no calibration is addedd."""
circuit = QuantumCircuit(1)
circuit.x(0)
# just not raise an error
self.pulse_gate_validation_pass(circuit)
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import cmult
# Input N
N = 3
c = QuantumRegister(1)
a = QuantumRegister(N)
b = QuantumRegister(N)
m = QuantumRegister(2*N)
cm = ClassicalRegister(2*N)
qc = QuantumCircuit(c, a, b, m, cm)
# Input
# a = 010 = 2
qc.x(a[1])
# b = 011 = 3
qc.x(b[0])
qc.x(b[1])
qc.x(c)# turns operation on
cmult(qc, c, a, b, m, N)
qc.measure(m, cm)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
def digit_sum(n):
num_str = str(n)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
return sum
# CZ (Controlled-Z)
# control qubit: q0
# target qubit: q1
def CZ(qp,q0,q1):
qp.h(q1)
qp.cx(q0,q1)
qp.h(q1)
# f-SWAP
# taking into account the one-directionality of CNOT gates in the available devices
def fSWAP(qp,q0,q1):
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
CZ(qp,q0,q1)
# CH (Controlled-Haddamard)
# control qubit: q1
# target qubit: q0
def CH2(qp,q0,q1):
qp.sdg(q0)
qp.h(q0)
qp.tdg(q0)
qp.h(q0)
qp.h(q1)
qp.cx(q0,q1)
qp.h(q0)
qp.h(q1)
qp.t(q0)
qp.h(q0)
qp.s(q0)
# Fourier transform gates
def F2(qp,q0,q1):
qp.cx(q0,q1)
CH2(qp,q0,q1)
qp.cx(q0,q1)
CZ(qp,q0,q1)
def F0(qp,q0,q1):
F2(qp,q0,q1)
def F1(qp,q0,q1):
F2(qp,q0,q1)
qp.sdg(q0)
from math import pi
# ROTATIONAL GATES
def RZ(qp,th,q0):
qp.u1(-th,q0)
def RY(qp,th,q0):
qp.u3(th,0.,0.,q0)
def RX(qp,th,q0):
qp.u3(th,0.,pi,q0)
# CRX (Controlled-RX)
# control qubit: q0
# target qubit: q1
def CRX(qp,th,q0,q1):
RZ(qp,pi/2.0,q1)
RY(qp,th/2.0,q1)
qp.cx(q0,q1)
RY(qp,-th/2.0,q1)
qp.cx(q0,q1)
RZ(qp,-pi/2.0,q1)
# Bogoliubov B_1
def B(qp,thk,q0,q1):
qp.x(q1)
qp.cx(q1,q0)
CRX(qp,thk,q0,q1)
qp.cx(q1,q0)
qp.x(q1)
# This circuit can be implemented in ibmqx5 using qubits (q0,q1,q2,q3)=(6,7,11,10)
# It can also be implemented between other qubits or in ibqmx2 and ibqmx4 using fermionic SWAPS
# For instance, the lines commented correspond to the implementations:
# ibmqx2 (q0,q1,q2,q3)=(4,2,0,1)
# ibmqx4 (q0,q1,q2,q3)=(3,2,1,0)
def Udisg(qc,lam,q0,q1,q2,q3):
k=1
n=4
th1=-np.arccos((lam-np.cos(2*pi*k/n))/np.sqrt((lam-np.cos(2*pi*k/n))**2+np.sin(2*pi*k/n)**2))
B(Udis,th1,q0,q1)
F1(Udis,q0,q1)
F0(Udis,q2,q3)
#fSWAP(Udis,q2,q1) # for ibmqx2
#fSWAP(Udis,q1,q2) # for ibmqx4
F0(Udis,q0,q2)
F0(Udis,q1,q3)
#fSWAP(Udis,q2,q1) # for ibmqx2
#fSWAP(Udis,q1,q2) # for ibmqx4
def Initial(qc,lam,q0,q1,q2,q3):
if lam <1:
qc.x(q3)
def Ising(qc,ini,udis,mes,lam,q0,q1,q2,q3,c0,c1,c2,c3):
Initial(ini,lam,q0,q1,q2,q3)
Udisg(udis,lam,q0,q1,q2,q3)
mes.measure(q0,c0)
mes.measure(q1,c1)
mes.measure(q2,c2)
mes.measure(q3,c3)
qc.add_circuit("Ising",ini+udis+mes)
#import sys
#sys.path.append("../../")
# importing the QISKit
from qiskit import QuantumCircuit,QuantumProgram
#import Qconfig
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from scipy import linalg as la
# Simulator
shots = 1024
backend ='ibmqx_qasm_simulator'
coupling_map = None
mag_sim = []
for i in range(8):
Isex = QuantumProgram()
q = Isex.create_quantum_register("q",4)
c = Isex.create_classical_register("c", 4)
Udis = Isex.create_circuit("Udis", [q], [c])
ini = Isex.create_circuit("ini",[q],[c])
mes = Isex.create_circuit("mes",[q],[c])
lam=i*0.25
Ising(Isex,ini,Udis,mes,lam,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3])
# Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
result = Isex.execute(["Ising"], backend=backend,
coupling_map=coupling_map, shots=shots,timeout=240000)
res=result.get_counts("Ising")
r1=list(res.keys())
r2=list(res.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag_sim.append(M/4)
# Real device
shots = 1024
#backend ='ibmqx5'
max_credits = 5
mag=[]
for i in range(8):
Isex = QuantumProgram()
q = Isex.create_quantum_register("q",12)
c = Isex.create_classical_register("c", 4)
Udis = Isex.create_circuit("Udis", [q], [c])
ini = Isex.create_circuit("ini",[q],[c])
mes = Isex.create_circuit("mes",[q],[c])
lam=i*0.25
Ising(Isex,ini,Udis,mes,lam,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3])
# Isex.set_api(Qconfig.APItoken, Qconfig.config["url"]) # set the APIToken and API url
result = Isex.execute(["Ising"], backend=backend,
max_credits=max_credits, wait=10, shots=shots,timeout=240000)
res=result.get_counts("Ising")
r1=list(res.keys())
r2=list(res.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag.append(M/4)
# As it is a system of only 4 particles, we can easily compute the exact result
def exact(lam):
if lam <1:
return lam/(2*np.sqrt(1+lam**2))
if lam >1:
return 1/2+lam/(2*np.sqrt(1+lam**2))
return None
vexact = np.vectorize(exact)
l=np.arange(0.0,2.0,0.01)
l1=np.arange(0.0,2.0,0.25)
plt.figure(figsize=(9,5))
plt.plot(l,vexact(l),'k',label='exact')
plt.plot(l1, mag_sim, 'bo',label='simulation')
plt.plot(l1, mag, 'r*',label='ibmqx5')
plt.xlabel('$\lambda$')
plt.ylabel('$<\sigma_{z}>$')
plt.legend()
plt.title('Magnetization of the ground state of n=4 Ising spin chain')
plt.show()
#This was the result when the real device is used:
def Initial_time(qc,t,lam,q0,q1,q2,q3):
qc.u3(np.arccos(lam/np.sqrt(1+lam**2)),pi/2.+4*t*np.sqrt(1+lam**2),0.,q0)
qc.cx(q0,q1)
def Ising_time(qc,ini,udis,mes,lam,t,q0,q1,q2,q3,c0,c1,c2,c3):
Initial_time(ini,t,lam,q0,q1,q2,q3)
Udisg(udis,lam,q0,q1,q2,q3)
mes.measure(q0,c0)
mes.measure(q1,c1)
mes.measure(q2,c2)
mes.measure(q3,c3)
qc.add_circuit("Ising_time",ini+udis+mes)
#Simulation
shots = 1024
backend = 'ibmqx_qasm_simulator'
coupling_map = None
# We compute the time evolution for lambda=0.5,0.9 and 1.8
nlam=3
magt_sim=[[] for _ in range(nlam)]
lam0=[0.5,0.9,1.8]
for j in range(nlam):
lam=lam0[j]
for i in range(9):
Isex_time = QuantumProgram()
q = Isex_time.create_quantum_register("q",4)
c = Isex_time.create_classical_register("c", 4)
Udis = Isex_time.create_circuit("Udis", [q], [c])
ini = Isex_time.create_circuit("ini",[q],[c])
mes = Isex_time.create_circuit("mes",[q],[c])
t=i*0.25
Ising_time(Isex_time,ini,Udis,mes,lam,t,q[0],q[1],q[2],q[3],c[0],c[1],c[2],c[3])
Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"])
result = Isex_time.execute(["Ising_time"], backend=backend,
coupling_map=coupling_map, shots=shots,timeout=240000)
res=result.get_counts("Ising_time")
r1=list(res.keys())
r2=list(res.values())
M=0
for k in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots
magt_sim[j].append(M/4)
shots = 1024
backend = 'ibmqx5'
max_credits = 5
# We compute the time evolution for lambda=0.5,0.9 and 1.8
nlam=3
magt=[[] for _ in range(nlam)]
lam0=[0.5,0.9,1.8]
for j in range(nlam):
lam=lam0[j]
for i in range(9):
Isex_time = QuantumProgram()
q = Isex_time.create_quantum_register("q",12)
c = Isex_time.create_classical_register("c", 4)
Udis = Isex_time.create_circuit("Udis", [q], [c])
ini = Isex_time.create_circuit("ini",[q],[c])
mes = Isex_time.create_circuit("mes",[q],[c])
t=i*0.25
Ising_time(Isex_time,ini,Udis,mes,lam,t,q[6],q[7],q[11],q[10],c[0],c[1],c[2],c[3])
Isex_time.set_api(Qconfig.APItoken, Qconfig.config["url"])
result = Isex_time.execute(["Ising_time"], backend=backend,
max_credits=max_credits, wait=10, shots=shots,timeout=240000)
res=result.get_counts("Ising_time")
r1=list(res.keys())
r2=list(res.values())
M=0
for k in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[k]))*r2[k]/shots
magt[j].append(M/4)
def exact_time(lam,tt):
Mt=(1 + 2*lam**2 + np.cos(4*tt*np.sqrt(1 + lam**2)))/(2 + 2*lam**2)
return Mt
vexact_t = np.vectorize(exact_time)
t=np.arange(0.0,2.0,0.01)
tt=np.arange(0.0,2.25,0.25)
plt.figure(figsize=(10,5))
plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$')
plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$')
plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$')
#plt.plot(tt, magt_sim[0], 'bo',label='simulation')
#plt.plot(tt, magt_sim[1], 'ro')
#plt.plot(tt, magt_sim[2], 'go')
plt.plot(tt, magt[0], 'b*',label='ibmqx5')
plt.plot(tt, magt[1], 'r*')
plt.plot(tt, magt[2], 'g*')
plt.plot(tt, magt[0], 'b--')
plt.plot(tt, magt[1], 'r--')
plt.plot(tt, magt[2], 'g--')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.legend()
plt.title('Time evolution |↑↑↑↑> state')
plt.show()
plt.figure(figsize=(13,3))
plt.subplot(1,3,1)
plt.plot(t,vexact_t(0.5,t),'b',label='$\lambda=0.5$')
plt.plot(tt, magt[0], 'b*',label='ibmqx5')
plt.plot(tt, magt[0], 'b--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=0.5$')
plt.subplot(132)
plt.plot(t,vexact_t(0.9,t),'r',label='$\lambda=0.9$')
plt.plot(tt, magt[1], 'r*',label='ibmqx5')
plt.plot(tt, magt[1], 'r--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=0.9$')
plt.subplot(133)
plt.plot(t,vexact_t(1.8,t),'g',label='$\lambda=1.8$')
plt.plot(tt, magt[2], 'g*',label='ibmqx5')
plt.plot(tt, magt[2], 'g--',label='ibmqx5')
plt.xlabel('time')
plt.ylabel('$<\sigma_{z}>$')
plt.title('$\lambda=1.8$')
plt.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
from typing import Union, List
from qiskit import QuantumCircuit
from qiskit.circuit.library import LinearFunction
from qiskit.quantum_info import Clifford
from .base import QiskitTranspilerService
logging.basicConfig()
logging.getLogger(__name__).setLevel(logging.INFO)
class AICliffordAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Clifford AI Synthesis API"""
def __init__(self):
super().__init__("clifford")
def transpile(
self,
circuits: List[Union[QuantumCircuit, Clifford]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={
"clifford_dict": [Clifford(circuit).to_dict() for circuit in circuits],
"qargs": qargs,
},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
class AILinearFunctionAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Linear Function AI Synthesis API"""
def __init__(self):
super().__init__("linear_functions")
def transpile(
self,
circuits: List[Union[QuantumCircuit, LinearFunction]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={
"clifford_dict": [Clifford(circuit).to_dict() for circuit in circuits],
"qargs": qargs,
},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
class AIPermutationAPI(QiskitTranspilerService):
"""A helper class that covers some basic funcionality from the Permutation AI Synthesis API"""
def __init__(self):
super().__init__("permutations")
def transpile(
self,
patterns: List[List[int]],
backend: str,
qargs: List[List[int]],
):
transpile_resps = self.request_and_wait(
endpoint="transpile",
body={"permutation": patterns, "qargs": qargs},
params={"backend": backend},
)
results = []
for transpile_resp in transpile_resps:
if transpile_resp.get("success") and transpile_resp.get("qasm") is not None:
results.append(QuantumCircuit.from_qasm_str(transpile_resp.get("qasm")))
else:
results.append(None)
return results
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the MergeAdjacentBarriers pass"""
import random
import unittest
from qiskit.transpiler.passes import MergeAdjacentBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_two_identical_barriers(self):
"""Merges two barriers that are identical into one
░ ░ ░
q_0: |0>─░──░─ -> q_0: |0>─░─
░ ░ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_numerous_identical_barriers(self):
"""Merges 5 identical barriers in a row into one
░ ░ ░ ░ ░ ░ ░
q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─
░ ░ ░ ░ ░ ░ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_of_different_sizes(self):
"""Test two barriers of different sizes are merged into one
░ ░ ░
q_0: |0>─░──░─ q_0: |0>─░─
░ ░ -> ░
q_1: |0>────░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_not_overlapping_barriers(self):
"""Test two barriers with no overlap are not merged
(NB in these pictures they look like 1 barrier but they are
actually 2 distinct barriers, this is just how the text
drawer draws them)
░ ░
q_0: |0>─░─ q_0: |0>─░─
░ -> ░
q_1: |0>─░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.barrier(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_before(self):
"""Test with an obstacle before the larger barrier
░ ░ ░
q_0: |0>──░───░─ q_0: |0>──────░─
┌───┐ ░ -> ┌───┐ ░
q_1: |0>┤ H ├─░─ q_1: |0>┤ H ├─░─
└───┘ ░ └───┘ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.h(qr[1])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_after(self):
"""Test with an obstacle after the larger barrier
░ ░ ░
q_0: |0>─░───░── q_0: |0>─░──────
░ ┌───┐ -> ░ ┌───┐
q_1: |0>─░─┤ H ├ q_1: |0>─░─┤ H ├
░ └───┘ ░ └───┘
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ -> q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ ░ └───┘ ░
"""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_long(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ -> ░ └───┘ ░
q_1: |0>─────────░─ q_1: |0>─────────░─
░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_narrow(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ -> ░ └───┘ ░
q_1: |0>─░───────░─ q_1: |0>─░───────░─
░ ░ ░ ░
"""
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_twoQ(self):
"""Test that barriers don't merge if there is an obstacle that
is blocking
░ ░ ░ ░
q_0: |0>─░───────░─ q_0: |0>─░───────░─
░ ░ ░ ░
q_1: |0>─░───■───── -> q_1: |0>─░───■─────
░ ┌─┴─┐ ░ ░ ┌─┴─┐ ░
q_2: |0>───┤ X ├─░─ q_2: |0>───┤ X ├─░─
└───┘ ░ └───┘ ░
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.barrier(0, 1)
circuit.cx(1, 2)
circuit.barrier(0, 2)
expected = QuantumCircuit(qr)
expected.barrier(0, 1)
expected.cx(1, 2)
expected.barrier(0, 2)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_output_deterministic(self):
"""Test that the output barriers have a deterministic ordering (independent of
PYTHONHASHSEED). This is important to guarantee that any subsequent topological iterations
through the circuit are also deterministic; it's in general not possible for all transpiler
passes to produce identical outputs across all valid topological orderings, especially if
those passes have some stochastic element."""
order = list(range(20))
random.Random(2023_02_10).shuffle(order)
circuit = QuantumCircuit(20)
circuit.barrier([5, 2, 3])
circuit.barrier([7, 11, 14, 2, 4])
circuit.barrier(order)
# All the barriers should get merged together.
expected = QuantumCircuit(20)
expected.barrier(range(20))
output = MergeAdjacentBarriers()(circuit)
self.assertEqual(expected, output)
# This assertion is that the ordering of the arguments in the barrier is fixed.
self.assertEqual(list(output.data[0].qubits), list(output.qubits))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
!pip install qiskit[visualization]
# Imports for Qiskit
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit import *
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.visualization import plot_histogram
import numpy as np
# Various imports
import numpy as np
from copy import deepcopy
from matplotlib import pyplot as plt
# IBMQ.save_account('Put your token')
# provider = IBMQ.load_account()
# IBMQ.get_provider(hub='ibm-q', group='open', project = 'main')
# Create the various registers needed
clock = QuantumRegister(2, name='clock')
input = QuantumRegister(1, name='b')
ancilla = QuantumRegister(1, name='ancilla')
measurement = ClassicalRegister(2, name='c')
# Create an empty circuit with the specified registers
circuit = QuantumCircuit(ancilla, clock, input, measurement)
circuit.barrier()
circuit.draw(output='mpl')
def qft_dagger(circ, q, n):
circ.h(clock[1]);
for j in reversed(range(n)):
for k in reversed(range(j+1,n)):
circ.cu1(-np.pi/float(2**(k-j)), q[k], q[j]);
circ.h(clock[0]);
circ.swap(clock[0], clock[1]);
def qft(circ, q, n):
circ.swap(clock[0], clock[1]);
circ.h(clock[0]);
for j in reversed(range(n)):
for k in reversed(range(j+1,n)):
circ.cu1(np.pi/float(2**(k-j)), q[k], q[j]);
circ.h(clock[1]);
def qpe(circ, clock, target):
circuit.barrier()
# e^{i*A*t}
circuit.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], input, label='U');
# e^{i*A*t*2}
circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2');
circuit.barrier();
# Perform an inverse QFT on the register holding the eigenvalues
qft_dagger(circuit, clock, 2)
def inv_qpe(circ, clock, target):
# Perform a QFT on the register holding the eigenvalues
qft(circuit, clock, 2)
circuit.barrier()
# e^{i*A*t*2}
circuit.cu(np.pi, np.pi, 0, 0, clock[1], input, label='U2');
#circuit.barrier();
# e^{i*A*t}
circuit.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], input, label='U');
circuit.barrier()
def hhl(circ, ancilla, clock, input, measurement):
qpe(circ, clock, input)
circuit.barrier()
# This section is to test and implement C = 1
circuit.cry(np.pi, clock[0], ancilla)
circuit.cry(np.pi/3, clock[1], ancilla)
circuit.barrier()
circuit.measure(ancilla, measurement[0])
circuit.barrier()
inv_qpe(circ, clock, input)
# State preparation. (various initial values)
# (restart from second cell if changed)
intial_state = [0,1]
# intial_state = [1,0]
# intial_state = [1/np.sqrt(2),1/np.sqrt(2)]
# intial_state = [np.sqrt(0.9),np.sqrt(0.1)]
circuit.initialize(intial_state, 3)
circuit.barrier()
# Perform a Hadamard Transform
circuit.h(clock)
hhl(circuit, ancilla, clock, input, measurement)
# Perform a Hadamard Transform
circuit.h(clock)
circuit.barrier()
circuit.measure(input, measurement[1])
circuit.draw('mpl',scale=1)
#print(circuit)
# Execute the circuit using the simulator
simulator = qiskit.BasicAer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1000)
#Get the result of the execution
result = job.result()
# Get the counts, the frequency of each answer
counts = result.get_counts(circuit)
# Display the results
plot_histogram(counts)
bcknd = Aer.get_backend('statevector_simulator')
job_sim = execute(circuit, bcknd)
result = job_sim.result()
o_state_result = result.get_statevector(circuit, decimals=3)
print(o_state_result)
provider.backends()
# Choose the backend on which to run the circuit
backend = provider.get_backend('ibmq_santiago')
from qiskit.tools.monitor import job_monitor
# Execute the job
job_exp = execute(circuit, backend=backend, shots=8192)
# Monitor the job to know where we are in the queue
job_monitor(job_exp, interval = 2)
# Get the results from the computation
results = job_exp.result()
# Get the statistics
answer = results.get_counts(circuit)
# Plot the results
plot_histogram(answer)
# Auto generated circuit (almost) matching the form from the Wong paper (using cu gates)
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
beta = 0
cycle_time = 0.5
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr, name="main")
intial_state = [0,1]
qc.initialize(intial_state, qr[3])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[1])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
# e^{i*A*t}
qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U');
# e^{i*A*t*2}
qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2');
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[2])
qc.cu1(-3.14159/2, qr[1], qr[2])
qc.h(qr[1])
qc.swap(qr[2], qr[1])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.cry(3.14159, qr[1], qr[0])
qc.cry(3.14159/3, qr[2], qr[0])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.swap(qr[2], qr[1])
qc.h(qr[1])
qc.cu1(3.14159/2, qr[1], qr[2])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
# e^{i*A*t*2}
qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2');
# e^{i*A*t}
qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U');
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[1])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.measure(qr[0], cr[0])
qc.measure(qr[3], cr[3])
from qiskit import execute, Aer
backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator
job = execute(qc, backend, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts are:", counts)
# Draw the circuit
print(qc)
#qc.draw('mpl',scale=1)
# Plot a histogram
from qiskit.visualization import plot_histogram
plot_histogram(counts)
qc.draw('mpl',scale=1)
# Same example as above but using the U3 and U1 gates instead of U1
# Initialize with RY instead of "initialize()"
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
beta = 1
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr, name="main")
# intial_state = [0,1]
# qc.initialize(intial_state, qr[3])
qc.ry(3.14159*beta, qr[3])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[1])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
# e^{i*A*t}
# qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, qr[1], qr[3], label='U');
# The CU gate is equivalent to a CU1 on the control bit followed by a CU3
qc.u1(3*3.14159/4, qr[1])
qc.cu3(3.14159/2, -3.14159/2, 3.14159/2, qr[1], qr[3])
# e^{i*A*t*2}
# qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2');
qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[2])
qc.cu1(-3.14159/2, qr[1], qr[2])
qc.h(qr[1])
qc.swap(qr[2], qr[1])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.cry(3.14159, qr[1], qr[0])
qc.cry(3.14159/3, qr[2], qr[0])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.swap(qr[2], qr[1])
qc.h(qr[1])
qc.cu1(3.14159/2, qr[1], qr[2])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
# e^{i*A*t*2}
# qc.cu(np.pi, np.pi, 0, 0, qr[2], qr[3], label='U2');
qc.cu3(3.14159, 3.14159, 0, qr[2], qr[3])
# e^{i*A*t}
# qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, qr[1], qr[3], label='U');
# The CU gate is equivalent to a CU1 on the control bit follwed by a CU3
qc.u1(-3*3.14159/4, qr[1])
qc.cu3(3.14159/2, 3.14159/2, -3.14159/2, qr[1], qr[3])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.h(qr[1])
qc.h(qr[2])
qc.barrier(qr[0], qr[1], qr[2], qr[3])
qc.measure(qr[0], cr[0])
qc.measure(qr[3], cr[3])
# qc.measure(qr, cr)
from qiskit import execute, Aer
backend = Aer.get_backend("qasm_simulator") # Use Aer qasm_simulator
job = execute(qc, backend, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts are:", counts)
# Draw the circuit
print(qc)
# Plot a histogram
from qiskit.visualization import plot_histogram
plot_histogram(counts)
qc.draw('mpl',scale=1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.